@rizom/ops 0.2.0-alpha.590 → 0.2.0-alpha.591
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 +5 -5
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/brains-ops.js
CHANGED
|
@@ -394,7 +394,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
394
394
|
`,after:`
|
|
395
395
|
`,now:{line:1,column:1},lineShift:0});if(n&&n.charCodeAt(n.length-1)!==10&&n.charCodeAt(n.length-1)!==13)n+=`
|
|
396
396
|
`;return n;function o(s){return i.stack.push(s),a;function a(){i.stack.pop()}}}function Fme(e){throw Error("Cannot handle value `"+e+"`, expected node")}function Hme(e){throw Error("Cannot handle unknown node `"+e.type+"`")}function Kme(e,t){if(e.type==="definition"&&e.type===t.type)return 0}function Jme(e,t){return QM(e,this,t)}function Vme(e,t){return XM(e,this,t)}function Wme(e,t){return nF(this,e,t)}var sF=S(()=>{WZ();QZ();MM();HM();JM();WM();YM();tF();iF()});var aF=S(()=>{sF()});function My(e){let t=this;t.compiler=r;function r(i){return zA(i,{...t.data("settings"),...e,extensions:t.data("toMarkdownExtensions")||[]})}}var cF=S(()=>{aF()});var lF=S(()=>{cF()});function NA(e){if(e)throw e}var bF=Se(function(hUe,yF){var Fy=Object.prototype.hasOwnProperty,gF=Object.prototype.toString,uF=Object.defineProperty,dF=Object.getOwnPropertyDescriptor,fF=function(t){if(typeof Array.isArray==="function")return Array.isArray(t);return gF.call(t)==="[object Array]"},pF=function(t){if(!t||gF.call(t)!=="[object Object]")return!1;var r=Fy.call(t,"constructor"),i=t.constructor&&t.constructor.prototype&&Fy.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!r&&!i)return!1;var n;for(n in t);return typeof n>"u"||Fy.call(t,n)},mF=function(t,r){if(uF&&r.name==="__proto__")uF(t,r.name,{enumerable:!0,configurable:!0,value:r.newValue,writable:!0});else t[r.name]=r.newValue},hF=function(t,r){if(r==="__proto__"){if(!Fy.call(t,r))return;else if(dF)return dF(t,r).value}return t[r]};yF.exports=function e(){var t,r,i,n,o,s,a=arguments[0],c=1,l=arguments.length,u=!1;if(typeof a==="boolean")u=a,a=arguments[1]||{},c=2;if(a==null||typeof a!=="object"&&typeof a!=="function")a={};for(;c<l;++c)if(t=arguments[c],t!=null){for(r in t)if(i=hF(a,r),n=hF(t,r),a!==n){if(u&&n&&(pF(n)||(o=fF(n)))){if(o)o=!1,s=i&&fF(i)?i:[];else s=i&&pF(i)?i:{};mF(a,{name:r,newValue:e(u,s,n)})}else if(typeof n<"u")mF(a,{name:r,newValue:n})}}return a}});function If(e){if(typeof e!=="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function DA(){let e=[],t={run:r,use:i};return t;function r(...n){let o=-1,s=n.pop();if(typeof s!=="function")throw TypeError("Expected function as last argument, not "+s);a(null,...n);function a(c,...l){let u=e[++o],f=-1;if(c){s(c);return}while(++f<n.length)if(l[f]===null||l[f]===void 0)l[f]=n[f];if(n=l,u)SF(u,a)(...l);else s(null,...l)}}function i(n){if(typeof n!=="function")throw TypeError("Expected `middelware` to be a function, not "+n);return e.push(n),t}}function SF(e,t){let r;return i;function i(...s){let a=e.length>s.length,c;if(a)s.push(n);try{c=e.apply(this,s)}catch(l){let u=l;if(a&&r)throw u;return n(u)}if(!a)if(c&&c.then&&typeof c.then==="function")c.then(o,n);else if(c instanceof Error)n(c);else o(c)}function n(s,...a){if(!r)r=!0,t(s,...a)}function o(s){n(null,s)}}var xF=()=>{};var sr;var wF=S(()=>{mA();sr=class sr extends Error{constructor(e,t,r){super();if(typeof t==="string")r=t,t=void 0;let i="",n={},o=!1;if(t)if("line"in t&&"column"in t)n={place:t};else if("start"in t&&"end"in t)n={place:t};else if("type"in t)n={ancestors:[t],place:t.position};else n={...t};if(typeof e==="string")i=e;else if(!n.cause&&e)o=!0,i=e.message,n.cause=e;if(!n.ruleId&&!n.source&&typeof r==="string"){let a=r.indexOf(":");if(a===-1)n.ruleId=r;else n.source=r.slice(0,a),n.ruleId=r.slice(a+1)}if(!n.place&&n.ancestors&&n.ancestors){let a=n.ancestors[n.ancestors.length-1];if(a)n.place=a.position}let s=n.place&&"start"in n.place?n.place.start:n.place;this.ancestors=n.ancestors||void 0,this.cause=n.cause||void 0,this.column=s?s.column:void 0,this.fatal=void 0,this.file="",this.message=i,this.line=s?s.line:void 0,this.name=ts(n.place)||"1:1",this.place=n.place||void 0,this.reason=this.message,this.ruleId=n.ruleId||void 0,this.source=n.source||void 0,this.stack=o&&n.cause&&typeof n.cause.stack==="string"?n.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};sr.prototype.file="";sr.prototype.name="";sr.prototype.reason="";sr.prototype.message="";sr.prototype.stack="";sr.prototype.column=void 0;sr.prototype.line=void 0;sr.prototype.ancestors=void 0;sr.prototype.cause=void 0;sr.prototype.fatal=void 0;sr.prototype.place=void 0;sr.prototype.ruleId=void 0;sr.prototype.source=void 0});var vF=S(()=>{wF()});import{default as Bn}from"path";var _F=()=>{};import{default as kF}from"process";var EF=()=>{};function Hy(e){return Boolean(e!==null&&typeof e==="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}import{fileURLToPath as IF}from"url";var TF=()=>{};class Ky{constructor(e){let t;if(!e)t={};else if(Hy(e))t={path:e};else if(typeof e==="string"||Gme(e))t={value:e};else t=e;this.cwd="cwd"in t?"":kF.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;while(++r<LA.length){let n=LA[r];if(n in t&&t[n]!==void 0&&t[n]!==null)this[n]=n==="history"?[...t[n]]:t[n]}let i;for(i in t)if(!LA.includes(i))this[i]=t[i]}get basename(){return typeof this.path==="string"?Bn.basename(this.path):void 0}set basename(e){jA(e,"basename"),BA(e,"basename"),this.path=Bn.join(this.dirname||"",e)}get dirname(){return typeof this.path==="string"?Bn.dirname(this.path):void 0}set dirname(e){AF(this.basename,"dirname"),this.path=Bn.join(e||"",this.basename)}get extname(){return typeof this.path==="string"?Bn.extname(this.path):void 0}set extname(e){if(BA(e,"extname"),AF(this.dirname,"extname"),e){if(e.codePointAt(0)!==46)throw Error("`extname` must start with `.`");if(e.includes(".",1))throw Error("`extname` cannot contain multiple dots")}this.path=Bn.join(this.dirname,this.stem+(e||""))}get path(){return this.history[this.history.length-1]}set path(e){if(Hy(e))e=IF(e);if(jA(e,"path"),this.path!==e)this.history.push(e)}get stem(){return typeof this.path==="string"?Bn.basename(this.path,this.extname):void 0}set stem(e){jA(e,"stem"),BA(e,"stem"),this.path=Bn.join(this.dirname||"",e+(this.extname||""))}fail(e,t,r){let i=this.message(e,t,r);throw i.fatal=!0,i}info(e,t,r){let i=this.message(e,t,r);return i.fatal=void 0,i}message(e,t,r){let i=new sr(e,t,r);if(this.path)i.name=this.path+":"+i.name,i.file=this.path;return i.fatal=!1,this.messages.push(i),i}toString(e){if(this.value===void 0)return"";if(typeof this.value==="string")return this.value;return new TextDecoder(e||void 0).decode(this.value)}}function BA(e,t){if(e&&e.includes(Bn.sep))throw Error("`"+t+"` cannot be a path: did not expect `"+Bn.sep+"`")}function jA(e,t){if(!e)throw Error("`"+t+"` cannot be empty")}function AF(e,t){if(!e)throw Error("Setting `"+t+"` requires `path` to be set too")}function Gme(e){return Boolean(e&&typeof e==="object"&&"byteLength"in e&&"byteOffset"in e)}var LA;var $F=S(()=>{vF();_F();EF();TF();LA=["history","path","basename","stem","extname","dirname"]});var CF=S(()=>{$F()});var RF=function(e){let i=this.constructor.prototype,n=i[e],o=function(){return n.apply(o,arguments)};return Object.setPrototypeOf(o,i),o};function UA(e,t){if(typeof t!=="function")throw TypeError("Cannot `"+e+"` without `parser`")}function qA(e,t){if(typeof t!=="function")throw TypeError("Cannot `"+e+"` without `compiler`")}function ZA(e,t){if(t)throw Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function OF(e){if(!If(e)||typeof e.type!=="string")throw TypeError("Expected node, got `"+e+"`")}function PF(e,t,r){if(!r)throw Error("`"+e+"` finished async. Use `"+t+"` instead")}function Jy(e){return Yme(e)?e:new Ky(e)}function Yme(e){return Boolean(e&&typeof e==="object"&&"message"in e&&"messages"in e)}function Xme(e){return typeof e==="string"||ehe(e)}function ehe(e){return Boolean(e&&typeof e==="object"&&"byteLength"in e&&"byteOffset"in e)}var Vy,Qme,MA,FA;var zF=S(()=>{tt();xF();CF();Vy=pu(bF(),1),Qme={}.hasOwnProperty;MA=class MA extends RF{constructor(){super("copy");this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=DA()}copy(){let e=new MA,t=-1;while(++t<this.attachers.length){let r=this.attachers[t];e.use(...r)}return e.data(Vy.default(!0,{},this.namespace)),e}data(e,t){if(typeof e==="string"){if(arguments.length===2)return ZA("data",this.frozen),this.namespace[e]=t,this;return Qme.call(this.namespace,e)&&this.namespace[e]||void 0}if(e)return ZA("data",this.frozen),this.namespace=e,this;return this.namespace}freeze(){if(this.frozen)return this;let e=this;while(++this.freezeIndex<this.attachers.length){let[t,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;if(r[0]===!0)r[0]=void 0;let i=t.call(e,...r);if(typeof i==="function")this.transformers.use(i)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(e){this.freeze();let t=Jy(e),r=this.parser||this.Parser;return UA("parse",r),r(String(t),t)}process(e,t){let r=this;return this.freeze(),UA("process",this.parser||this.Parser),qA("process",this.compiler||this.Compiler),t?i(void 0,t):new Promise(i);function i(n,o){let s=Jy(e),a=r.parse(s);r.run(a,s,function(l,u,f){if(l||!u||!f)return c(l);let p=u,m=r.stringify(p,f);if(Xme(m))f.value=m;else f.result=m;c(l,f)});function c(l,u){if(l||!u)o(l);else if(n)n(u);else B(t,"`done` is defined if `resolve` is not"),t(void 0,u)}}}processSync(e){let t=!1,r;return this.freeze(),UA("processSync",this.parser||this.Parser),qA("processSync",this.compiler||this.Compiler),this.process(e,i),PF("processSync","process",t),B(r,"we either bailed on an error or have a tree"),r;function i(n,o){t=!0,NA(n),r=o}}run(e,t,r){OF(e),this.freeze();let i=this.transformers;if(!r&&typeof t==="function")r=t,t=void 0;return r?n(void 0,r):new Promise(n);function n(o,s){B(typeof t!=="function","`file` can\u2019t be a `done` anymore, we checked");let a=Jy(t);i.run(e,a,c);function c(l,u,f){let p=u||e;if(l)s(l);else if(o)o(p);else B(r,"`done` is defined if `resolve` is not"),r(void 0,p,f)}}}runSync(e,t){let r=!1,i;return this.run(e,t,n),PF("runSync","run",r),B(i,"we either bailed on an error or have a tree"),i;function n(o,s){NA(o),i=s,r=!0}}stringify(e,t){this.freeze();let r=Jy(t),i=this.compiler||this.Compiler;return qA("stringify",i),OF(e),i(e,r)}use(e,...t){let r=this.attachers,i=this.namespace;if(ZA("use",this.frozen),e===null||e===void 0);else if(typeof e==="function")a(e,t);else if(typeof e==="object")if(Array.isArray(e))s(e);else o(e);else throw TypeError("Expected usable value, not `"+e+"`");return this;function n(c){if(typeof c==="function")a(c,[]);else if(typeof c==="object")if(Array.isArray(c)){let[l,...u]=c;a(l,u)}else o(c);else throw TypeError("Expected usable value, not `"+c+"`")}function o(c){if(!("plugins"in c)&&!("settings"in c))throw Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");if(s(c.plugins),c.settings)i.settings=Vy.default(!0,i.settings,c.settings)}function s(c){let l=-1;if(c===null||c===void 0);else if(Array.isArray(c))while(++l<c.length){let u=c[l];n(u)}else throw TypeError("Expected a list of plugins, not `"+c+"`")}function a(c,l){let u=-1,f=-1;while(++u<r.length)if(r[u][0]===c){f=u;break}if(f===-1)r.push([c,...l]);else if(l.length>0){let[p,...m]=l,y=r[f][1];if(If(y)&&If(p))p=Vy.default(!0,y,p);r[f]=[c,p,...m]}}}};FA=new MA().freeze()});var NF=S(()=>{zF()});var DF;var LF=S(()=>{KZ();lF();NF();DF=FA().use(Dy).use(My).freeze()});var tqe;var BF=S(()=>{Ae();tqe=d.record(d.string(),d.unknown())});var iqe;var jF=S(()=>{Ae();Jc();iqe=d.record(d.string(),d.unknown())});var UF=S(()=>{Jc()});var qF=S(()=>{yf();tq();d4();f4();BF();jF();UF();kT()});var lhe;var ZF=S(()=>{Ae();lhe=d.object({slug:d.string(),title:d.string(),type:d.string(),entityId:d.string(),contentHash:d.string()})});var KA=S(()=>{qF();ZF()});var MF=S(()=>{KA();Ae()});var uhe,dhe;var Wy=S(()=>{Ae();pi();uhe={url:d.string(),typeLabel:d.string(),listUrl:d.string(),listLabel:d.string()},dhe=d.object({name:d.string(),description:d.string(),schema:d.unknown(),basePrompt:d.string().optional(),useKnowledgeContext:d.boolean().optional(),requiredPermission:d.enum(["admin","trusted","public"]),formatter:d.unknown().optional(),overlayFormatter:d.unknown().optional(),layout:d.object({component:d.unknown().optional(),fullscreen:d.boolean().optional(),formats:d.unknown().optional()}).optional(),dataSourceId:d.string().optional()})});var Gy=S(()=>{Wy()});var KF=S(()=>{Gy()});var JA=()=>{};var phe,mhe,kl,JF,hhe;var VF=S(()=>{pi();Ae();JA();phe=d.enum(["admin","trusted","public"]),mhe=d.enum(["create","update","delete","extract","publish"]),kl=d.enum(["never","admin","trusted","public"]),JF=d.strictObject({create:kl.optional(),update:kl.optional(),delete:kl.optional(),extract:kl.optional(),publish:kl.optional()}),hhe=d.record(d.string(),JF)});var WF=S(()=>{Gy();Wy()});var ghe,yhe,Qy,bhe,She,xhe;var GF=S(()=>{Ae();ghe=d.enum(["site-content-preview","site-content-production"]),yhe=d.enum(["web","image","pdf","epub"]),Qy=d.custom((e)=>typeof e==="function"),bhe=d.object({name:d.string(),schema:d.unknown(),description:d.string().optional(),pluginId:d.string(),renderers:d.object({web:d.union([Qy,d.string()]).optional(),image:d.union([Qy,d.string()]).optional(),pdf:d.union([Qy,d.string()]).optional(),epub:d.union([Qy,d.string()]).optional()})}),She=d.object({enableContentGeneration:d.boolean().default(!1),outputDir:d.string(),workingDir:d.string().optional(),environment:d.enum(["preview","production"]).default("preview"),siteConfig:d.object({title:d.string(),description:d.string(),url:d.string().optional()}).optional()}),xhe=d.object({success:d.boolean(),routesBuilt:d.number(),errors:d.array(d.string()).optional(),warnings:d.array(d.string()).optional()})});var QF=S(()=>{Wy();KF();Gy();VF();JA();WF();GF()});var YF=S(()=>{KA();QF();Ae()});var _4e;var XF=S(()=>{fy();LF();_4e=DF()});var vhe,_he;var e3=S(()=>{XF();Ae();_T();vhe=ly.omit({url:!0,analyticsScript:!0}),_he=vhe.extend({title:d.string().optional().describe("Optional site title override"),description:d.string().optional().describe("Optional site description override")})});function VA(e,t={}){let r=t3(e),i=t3(t.sharedDomain??"rizom.ai").replace(/^\./,""),n=`.${i}`;if(r.endsWith(n)){let o=r.slice(0,-n.length);if(o.length>0&&!o.includes("."))return`${o}-preview.${i}`}return`preview.${r}`}function t3(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}var r3=()=>{};var n3=S(()=>{r3()});var khe,Ehe;var i3=S(()=>{Ae();xT();khe=d.string(),Ehe=d.custom((e)=>{if(!dy(e))return!1;let{plugin:t,...r}=e;if(t!==void 0&&typeof t!=="function")return!1;return WU.safeParse(r).success})});var o3=S(()=>{wT();_T();MF();YF();e3();n3();i3()});function s3(e,t={}){return VA(e,t)}var a3=S(()=>{o3()});var m3={};Ht(m3,{assertPilotUsersRemoved:()=>p3,createPilotOffboardDriver:()=>l3,offboardPilotUsers:()=>Rhe});import{access as Ihe,readdir as The,readFile as Ahe,rm as Tf,writeFile as $he}from"fs/promises";import{basename as Che,join as Vi}from"path";async function Rhe(e,t){let r=[...new Set(t.handles.map((f)=>Pr.parse(f)))].sort((f,p)=>f.localeCompare(p));if(r.length===0)throw Error("At least one pilot handle is required");let i=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!i&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let o=t.env??process.env,s=t.logger??console.info,a=await Ct(e),c=r.map((f)=>Ohe(a,f,o)),l=t.driver??l3({env:o,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),u=await Promise.all(c.map(async(f)=>({target:f,inspection:await l.inspect(f)})));if(zhe(u),Nhe(u,i,s),!i){for(let f of u)if(!f.inspection.contentRepoArchived)await l.archiveContentRepo(f.target),s(`[${f.target.handle}] archived ${f.target.contentRepo}`);for(let f of u)for(let p of f.inspection.dnsRecords)await l.deleteDnsRecord(f.target,p),s(`[${f.target.handle}] deleted DNS ${p.name}`);for(let f of u)if(f.inspection.server)await l.deleteServer(f.target,f.inspection.server),s(`[${f.target.handle}] deleted ${f.target.instanceName}`);await Phe(c,l,t.sleep??((f)=>new Promise((p)=>setTimeout(p,f)))),await Dhe(e,r),await Uo(e),await p3(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:i,handles:r,confirmation:n,plans:u}}function Ohe(e,t,r){let i=e.users.find((u)=>u.handle===t),n=`${t}${e.pilot.domainSuffix}`,o=i?.domain??n,s=s3(o,{sharedDomain:e.pilot.domainSuffix}),a=i?.cloudflareZoneId??Yy(r,"CF_ZONE_ID"),c=i?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,l=c.includes("/")?c:`${e.pilot.githubOrg}/${c}`;return{handle:t,instanceName:`rover-${t}`,domain:o,previewDomain:s,...o===n?{}:{wwwDomain:`www.${o}`},contentRepo:l,cloudflareZoneId:a}}async function Phe(e,t,r){for(let i of e)for(let n=1;n<=20;n+=1){let o=await t.inspect(i);if(!o.server&&o.dnsRecords.length===0&&o.contentRepoArchived)break;if(n===20)throw Error(`[${i.handle}] provider cleanup did not converge`);await r(1500)}}function zhe(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 i=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!i.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 Nhe(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:i})=>i.handle).join(", ")}`);for(let{target:i,inspection:n}of e){let o=n.server?`delete ${i.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 ${i.contentRepo}`;r(`[${i.handle}] server: ${o}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function Dhe(e,t){let r=new Set(t),i=Vi(e,"cohorts");for(let n of(await The(i)).filter((o)=>o.endsWith(".yaml"))){let o=Vi(i,n),s=await Ahe(o,"utf8"),a=di(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let c=a.get("members",!0);if(!gT(c))throw Error(`${n}: members must be a sequence`);let l=c.items.filter((u)=>!ll(u)||typeof u.value!=="string"||!r.has(u.value));if(l.length===c.items.length)continue;if(l.length===0){await Tf(o);continue}c.items=l,Pn.parse(a.toJS()),await $he(o,a.toString())}for(let n of t)await Promise.all([Tf(Vi(e,"users",`${n}.yaml`),{force:!0}),Tf(Vi(e,"users",`${n}.secrets.yaml`),{force:!0}),Tf(Vi(e,"users",`${n}.secrets.yaml.age`),{force:!0}),Tf(Vi(e,"users",n),{recursive:!0,force:!0})])}function l3(e){let t=e.fetchImpl??fetch,r=Yy(e.env,"HCLOUD_TOKEN"),i=Yy(e.env,"CF_API_TOKEN"),n=Yy(e.env,e.contentRepoTokenName);return{async inspect(o){let[s,a,c]=await Promise.all([Lhe(t,r,o.instanceName),Promise.all([o.domain,o.previewDomain,...o.wwwDomain?[o.wwwDomain]:[]].map((l)=>Bhe(t,i,o.cloudflareZoneId,l))).then((l)=>l.flat()),jhe(t,n,o.contentRepo)]);if(s.length>1)throw Error(`[${o.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:c.archived}},async archiveContentRepo(o){await El(t,`https://api.github.com/repos/${o.contentRepo}`,{method:"PATCH",headers:u3(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(o,s){if(Il(await El(t,`https://api.cloudflare.com/client/v4/zones/${o.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:d3(i)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(o,s){await El(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function Lhe(e,t,r){let i=new URL("https://api.hetzner.cloud/v1/servers");i.searchParams.set("label_selector",`brain=${r}`);let o=Il(await El(e,i.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(o))throw Error("Hetzner server lookup returned an invalid payload");return o.map((s)=>{let a=Il(s),c=c3(a.public_net),l=c3(c?.ipv4);return{id:Uhe(a.id,"Hetzner server id"),name:Af(a.name,"Hetzner server name"),...typeof l?.ip==="string"?{ip:l.ip}:{}}})}async function Bhe(e,t,r,i){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",i);let o=Il(await El(e,n.toString(),{headers:d3(t)},"Cloudflare DNS lookup")),s=o.result;if(o.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${i}`);return s.map((a)=>{let c=Il(a),l=Af(c.type,"Cloudflare record type");if(l!=="A"&&l!=="CNAME")throw Error(`Unsupported Cloudflare record type ${l} for ${i}`);return{id:Af(c.id,"Cloudflare record id"),name:Af(c.name,"Cloudflare record name"),type:l,content:Af(c.content,"Cloudflare record content")}})}async function jhe(e,t,r){let i=Il(await El(e,`https://api.github.com/repos/${r}`,{headers:u3(t)},"GitHub repository lookup"));if(typeof i.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:i.archived}}async function El(e,t,r,i,n=!1){let o=await e(t,r),s=await o.text();if(!o.ok)throw Error(`${i} failed (${o.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${i} returned an invalid JSON response`)}}function u3(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function d3(e){return{Authorization:`Bearer ${e}`}}function Yy(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function f3(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Il(e){if(!f3(e))throw Error("Provider returned an unexpected payload");return e}function c3(e){return f3(e)?e:void 0}function Af(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function Uhe(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function qhe(e){try{return await Ihe(e),!0}catch{return!1}}async function p3(e,t){for(let r of t)for(let i of[Vi(e,"users",`${r}.yaml`),Vi(e,"users",`${r}.secrets.yaml.age`),Vi(e,"users",r)])if(await qhe(i))throw Error(`Offboarded user state remains: ${Che(i)}`)}var h3=S(()=>{hf();zn();a3();Zd();qi()});var g3="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as y3}from"crypto";function Mhe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!ns||ns.length<e)ns=Buffer.allocUnsafe(e*Zhe),y3.getRandomValues(ns),Tl=0;else if(Tl+e>ns.length)y3.getRandomValues(ns),Tl=0}catch(t){throw ns=void 0,t}Tl+=e}function b3(e=21){Mhe(e|=0);let t="";for(let r=Tl-e;r<Tl;r++)t+=g3[ns[r]&63];return t}var Zhe=128,ns,Tl;var S3=()=>{};function Wi(e=12){return b3(e)}var $f=S(()=>{S3()});import{openSync as Fhe,writeSync as Hhe}from"fs";class on{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??ka.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=Fhe(this.logFile,"a")}catch{}}static getInstance(e){if(!on.instance)on.instance=new on(e);else if(e?.useStderr!==void 0)on.instance.useStderr=e.useStderr;return on.instance}static resetInstance(){on.instance=null}static createFresh(e){return new on(e)}formatEntry(e,t,r){let i=new Date().toISOString();if(this.format==="json"){let n={ts:i,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?`[${i}] [${this.context}] ${t}`:`[${i}] ${t}`}write(e,t,r,i){if(this.format==="json")e(this.formatEntry(t,r,i));else if(i.length>0)e(this.formatEntry(t,r,[]),...i);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,i);try{Hhe(this.fileHandle,n+`
|
|
397
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=ka.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=ka.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=ka.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=ka.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<=ka.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ka.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new on({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ka,wZe;var WA=S(()=>{ka={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};wZe=on.getInstance()});var GA,Khe,Al,EZe;var Cf=S(()=>{pi();Ae();GA=d.enum(["file_operations","content_operations","data_processing","batch_processing"]),Khe=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:GA,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:pl.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:Go.optional()}),Al=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:GA,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:pl.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:Go.optional(),rootJobId:d.string()}),EZe=d.enum(["none","skip","replace","coalesce"])});var Jhe,is=15000;var Rf=S(()=>{Cf();Ae();Jhe=d.object({id:d.string(),type:d.string(),data:d.string(),status:d.enum(["pending","processing","completed","failed"]),source:d.string().nullable(),priority:d.number(),retryCount:d.number(),maxRetries:d.number(),lastError:d.string().nullable(),createdAt:d.number(),scheduledFor:d.number(),startedAt:d.number().nullable(),completedAt:d.number().nullable(),attemptId:d.string().nullable(),workerSlotId:d.string().nullable(),workerSessionId:d.string().nullable(),leaseExpiresAt:d.number().nullable(),attemptHeartbeatAt:d.number().nullable(),runtimeUpdatedAt:d.number().nullable(),metadata:Al,progress:d.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:d.unknown().nullable().optional()})});var QA,x3,Ue,Vhe,Whe,w3,Ghe;var os=S(()=>{Ae();Cf();QA=d.enum(["pending","processing","completed","failed"]),x3=d.enum(["completed","failed"]),Ue={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Vhe=d.object({id:d.string(),type:d.string(),status:QA,data:d.unknown(),result:d.unknown().optional(),lastError:d.string().optional().nullable(),attempts:d.number(),maxRetries:d.number(),priority:d.number(),createdAt:d.date(),updatedAt:d.date(),processedAt:d.date().optional().nullable(),completedAt:d.date().optional().nullable(),failedAt:d.date().optional().nullable()}),Whe=d.object({jobId:d.string(),type:d.string(),status:x3,result:d.unknown().optional(),error:d.string().optional()}),w3=d.object({success:d.literal(!1),error:d.string().optional()}),Ghe=d.object({id:d.string(),type:d.enum(["job","batch"]),status:QA,message:d.string().optional(),progress:d.object({current:d.number(),total:d.number(),percentage:d.number()}).optional(),aggregationKey:d.string().optional(),batchDetails:d.object({totalOperations:d.number(),completedOperations:d.number(),failedOperations:d.number(),currentOperation:d.string().optional(),errors:d.array(d.string()).optional()}).optional(),jobDetails:d.object({jobType:d.string(),priority:d.number(),retryCount:d.number()}).optional(),metadata:Al})});var Be,ar;var jn=S(()=>{Be=class Be extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};ar=class ar extends Be{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function v3(e){let t=Qhe.exec(e);if(t===null)throw new Be(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?Yhe(r.authority):void 0,o=Ea(r.path),s=r.query!==void 0?ege(r.query):void 0,a=r.fragment!==void 0?Ea(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function Yhe(e){let t=Xhe.exec(e);if(t===null)throw new Be("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=Ea(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:Ea(r.username),password:r.password!==void 0?Ea(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function ege(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:Ea(n.replaceAll("+"," ")),value:Ea(o.replaceAll("+"," "))})}return{pairs:r}}function Ea(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Be(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function Of(e,t,r){if(t===void 0)throw new Be(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=tge(t.host),o=rge(t.port),a=`//${nge(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function tge(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function rge(e){return e!==void 0?`:${e}`:""}function nge(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Qhe,Xhe;var Xy=S(()=>{jn();Qhe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Xhe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Cl,_3,k3,Pf,eb,ige,cr,E3,A3=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),$3=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),C3=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=Pf[t>>18&63]+Pf[t>>12&63]+Pf[t>>6&63]+Pf[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},e$,YA,tb=(e,t=!1)=>t?A3(YA(e)):YA(e),oge=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?cr(192|t>>>6)+cr(128|t&63):cr(224|t>>>12&15)+cr(128|t>>>6&63)+cr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return cr(240|t>>>18&7)+cr(128|t>>>12&63)+cr(128|t>>>6&63)+cr(128|t&63)}},sge,R3=(e)=>e.replace(sge,oge),I3,$l=(e,t=!1)=>t?A3(I3(e)):I3(e),T3=(e)=>$l(e,!0),age,cge=(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 cr((r>>>10)+55296)+cr((r&1023)+56320);case 3:return cr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return cr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},O3=(e)=>e.replace(age,cge),P3=(e)=>{if(e=e.replace(/\s+/g,""),!ige.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=eb[e.charAt(o++)]<<18|eb[e.charAt(o++)]<<12|(r=eb[e.charAt(o++)])<<6|(i=eb[e.charAt(o++)]),r===64)n.push(cr(t>>16&255));else if(i===64)n.push(cr(t>>16&255,t>>8&255));else n.push(cr(t>>16&255,t>>8&255,t&255));return n.join("")},t$,z3,N3=(e)=>z3(D3(e)),lge,D3=(e)=>$3(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),XA=(e)=>lge(D3(e)),uge=(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)},L3=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),B3=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,L3(r));e("fromBase64",function(){return XA(this)}),e("toBase64",function(t){return $l(this,t)}),e("toBase64URI",function(){return $l(this,!0)}),e("toBase64URL",function(){return $l(this,!0)}),e("toUint8Array",function(){return N3(this)})},j3=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,L3(r));e("toBase64",function(t){return tb(this,t)}),e("toBase64URI",function(){return tb(this,!0)}),e("toBase64URL",function(){return tb(this,!0)})},dge=()=>{B3(),j3()},Rl;var rb=S(()=>{Cl=typeof Buffer==="function",_3=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,k3=typeof TextEncoder==="function"?new TextEncoder:void 0,Pf=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),eb=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(Pf),ige=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,cr=String.fromCharCode.bind(String),E3=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),e$=typeof btoa==="function"?(e)=>btoa(e):Cl?(e)=>Buffer.from(e,"binary").toString("base64"):C3,YA=Cl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(cr.apply(null,e.subarray(i,i+4096)));return e$(r.join(""))},sge=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,I3=Cl?(e)=>Buffer.from(e,"utf8").toString("base64"):k3?(e)=>YA(k3.encode(e)):(e)=>e$(R3(e)),age=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,t$=typeof atob==="function"?(e)=>atob($3(e)):Cl?(e)=>Buffer.from(e,"base64").toString("binary"):P3,z3=Cl?(e)=>E3(Buffer.from(e,"base64")):(e)=>E3(t$(e).split("").map((t)=>t.charCodeAt(0))),lge=Cl?(e)=>Buffer.from(e,"base64").toString("utf8"):_3?(e)=>_3.decode(z3(e)):(e)=>O3(t$(e)),Rl={version:"3.8.0",VERSION:"3.8.0",atob:t$,atobPolyfill:P3,btoa:e$,btoaPolyfill:C3,fromBase64:XA,toBase64:$l,encode:$l,encodeURI:T3,encodeURL:T3,utob:R3,btou:O3,decode:XA,isValid:uge,fromUint8Array:tb,toUint8Array:N3,extendString:B3,extendUint8Array:j3,extendBuiltins:dge}});function ss(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 Ol{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(fge),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function fge(e){return Array.prototype.map.call(e,pge)}function pge(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Rl.fromUint8Array(new Uint8Array(e));else return e}var mi="https://github.com/libsql/libsql-client-ts#supported-urls";var Pl=S(()=>{rb()});function q3(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function zf(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===U3)r="file::memory:";let c=v3(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===U3&&c.authority===void 0,f;if(u)f={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else f={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(f,g))throw new Be(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let _=f[g];if(_.values!==void 0&&!_.values.includes(b))throw new Be(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${_.values.map((T)=>'"'+T+'"').join(", ")}]`,"URL_INVALID");if(_.update!==void 0)_?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Be('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Be(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Be(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 U3=":memory:";var Nf=S(()=>{jn();Xy();Pl()});var M3=Se(function(bn){var mge=bn&&bn.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),hge=bn&&bn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Z3=bn&&bn.__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))mge(t,e,r)}return hge(t,e),t};Object.defineProperty(bn,"__esModule",{value:!0});bn.load=bn.currentTarget=void 0;var gge=Z3(fr("path")),yge=Z3(fr("fs"));function bge(){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 Sge()?`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}`)}bn.currentTarget=bge;function Sge(){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 xge(e){let t=gge.join(e,"index.node");return yge.existsSync(t)?fr(t):null}bn.load=xge});var K3=Se(function(HZe,H3){var F3=()=>process.platform==="linux",r$=null,wge=()=>{if(!r$)r$=F3()&&process.report?process.report.getReport():{};return r$};H3.exports={isLinux:F3,getReport:wge}});var W3=Se(function(KZe,V3){var J3=fr("fs"),vge=(e)=>J3.readFileSync(e,"utf-8"),_ge=(e)=>new Promise((t,r)=>{J3.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});V3.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:vge,readFile:_ge}});var f5=Se(function(JZe,d5){var Q3=fr("child_process"),{isLinux:zl,getReport:Y3}=K3(),{LDD_PATH:nb,readFile:X3,readFileSync:e5}=W3(),hi,gi,as="",t5=()=>{if(!as)return new Promise((e)=>{Q3.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{as=t?" ":r,e(as)})});return as},r5=()=>{if(!as)try{as=Q3.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){as=" "}return as},Gi="glibc",n5=/GLIBC\s(\d+\.\d+)/,Ia="musl",kge=Gi.toUpperCase(),Ege=Ia.toLowerCase(),Ige=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),i5=()=>{let e=Y3();if(e.header&&e.header.glibcVersionRuntime)return Gi;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Ige))return Ia}return null},o5=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Gi))return Gi;if(r&&r.includes(Ia))return Ia;return null},s5=(e)=>{if(e.includes(Ege))return Ia;if(e.includes(kge))return Gi;return null},Tge=async()=>{if(hi!==void 0)return hi;hi=null;try{let e=await X3(nb);hi=s5(e)}catch(e){}return hi},Age=()=>{if(hi!==void 0)return hi;hi=null;try{let e=e5(nb);hi=s5(e)}catch(e){}return hi},a5=async()=>{let e=null;if(zl()){if(e=await Tge(),!e)e=i5();if(!e){let t=await t5();e=o5(t)}}return e},c5=()=>{let e=null;if(zl()){if(e=Age(),!e)e=i5();if(!e){let t=r5();e=o5(t)}}return e},$ge=async()=>zl()&&await a5()!==Gi,Cge=()=>zl()&&c5()!==Gi,Rge=async()=>{if(gi!==void 0)return gi;gi=null;try{let t=(await X3(nb)).match(n5);if(t)gi=t[1]}catch(e){}return gi},Oge=()=>{if(gi!==void 0)return gi;gi=null;try{let t=e5(nb).match(n5);if(t)gi=t[1]}catch(e){}return gi},l5=()=>{let e=Y3();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},G3=(e)=>e.trim().split(/\s+/)[1],u5=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(Gi))return G3(t);if(r&&i&&r.includes(Ia))return G3(i);return null},Pge=async()=>{let e=null;if(zl()){if(e=await Rge(),!e)e=l5();if(!e){let t=await t5();e=u5(t)}}return e},zge=()=>{let e=null;if(zl()){if(e=Oge(),!e)e=l5();if(!e){let t=r5();e=u5(t)}}return e};d5.exports={GLIBC:Gi,MUSL:Ia,family:a5,familySync:c5,isNonGlibcLinux:$ge,isNonGlibcLinuxSync:Cge,version:Pge,versionSync:zge}});var m5=Se(function(VZe,p5){var Nge={ALLOW:0,DENY:1};p5.exports=Nge});var g5=Se(function(WZe,h5){var n$={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ta(e,t,r){if(new.target!==Ta)return new Ta(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),n$.value=""+e,Object.defineProperty(this,"message",n$),Error.captureStackTrace(this,Ta),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ta,Error);Object.setPrototypeOf(Ta.prototype,Error.prototype);Object.defineProperty(Ta.prototype,"name",n$);h5.exports=Ta});var k5=Se(function(GZe,ib){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Dge,currentTarget:Lge}=M3(),{familySync:y5,GLIBC:Bge,MUSL:jge}=f5();function Uge(){if(process.env.LIBSQL_JS_DEV)return Dge(__dirname);let e=Lge();if(y5()==Bge)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"&&y5()==jge)e="linux-arm-musleabihf";return fr(`@libsql/${e}`)}var{databaseOpen:qge,databaseOpenWithSync:Zge,databaseInTransaction:Mge,databaseInterrupt:Fge,databaseClose:Hge,databaseSyncSync:Kge,databaseSyncUntilSync:Jge,databaseExecSync:Vge,databasePrepareSync:Wge,databaseDefaultSafeIntegers:Gge,databaseAuthorizer:Qge,databaseLoadExtension:Yge,databaseMaxWriteReplicationIndex:Xge,statementRaw:eye,statementIsReader:tye,statementGet:b5,statementRun:S5,statementInterrupt:rye,statementRowsSync:x5,statementColumns:nye,statementSafeIntegers:iye,rowsNext:oye}=Uge(),sye=m5(),w5=g5();function Nl(e){if(e.libsqlError)return new w5(e.message,e.code,e.rawCode);return e}class v5{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=Zge(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=qge(e,o,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 Mge(n)}}})}sync(){return Kge.call(this.db)}syncUntil(e){return Jge.call(this.db,e)}prepare(e){try{let t=Wge.call(this.db,e);return new _5(t)}catch(t){throw Nl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){Qge.call(this.db,e)}loadExtension(...e){Yge.call(this.db,...e)}maxWriteReplicationIndex(){return Xge.call(this.db)}exec(e){try{Vge.call(this.db,e)}catch(t){throw Nl(t)}}interrupt(){Fge.call(this.db)}close(){Hge.call(this.db),this.open=!1}defaultSafeIntegers(e){return Gge.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class _5{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return eye.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return tye.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return S5.call(this.stmt,e[0]);else return S5.call(this.stmt,e.flat())}catch(t){throw Nl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return b5.call(this.stmt,e[0]);else return b5.call(this.stmt,e.flat())}catch(t){throw Nl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=x5.call(this.stmt,e[0]);else t=x5.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)oye.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw Nl(i)}},[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 Nl(t)}}interrupt(){rye.call(this.stmt)}columns(){return nye.call(this.stmt)}safeIntegers(e){return iye.call(this.stmt,e??!0),this}}ib.exports=v5;ib.exports.Authorization=sye;ib.exports.SqliteError=w5});import{Buffer as I5}from"buffer";function T5(e){if(e.scheme!=="file")throw new Be(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Be(`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 ${mi}`,"URL_INVALID");if(t.port!==void 0)throw new Be("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Be("File URL cannot have username and password","URL_INVALID")}let r=q3(e);if(r&&e.syncUrl)throw new Be(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new Df.default(i,n);return Mt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new A5(i,n,o,e.intMode)}class A5{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Mt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Mt(r,ss(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new ar("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Mt(r,s,this.#n))}catch(o){if(o instanceof ar)throw o;if(o instanceof Be)throw new ar(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Mt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Mt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Mt(t,"PRAGMA foreign_keys=off",this.#n),Mt(t,ss("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new ar("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Mt(t,e[i],this.#n))}catch(n){if(n instanceof ar)throw n;if(n instanceof Be)throw new ar(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Mt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n);Mt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Mt(t,ss(e),this.#n),this.#r=null,new $5(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return C5(t,e)}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 Df.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new Df.default(this.#e,this.#t);return this.#r}}class $5{#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(),Mt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Mt(this.#e,n,this.#t))}catch(i){if(i instanceof ar)throw i;if(i instanceof Be)throw new ar(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),C5(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Mt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Mt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Mt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Be("The transaction is closed","TRANSACTION_CLOSED")}}function Mt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>E5(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=E5(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>aye(p,a,r)),u=0,f=void 0;return new Ol(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new Ol([],[],[],c,l)}}catch(o){throw R5(o)}}function aye(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=cye(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function cye(e,t){if(typeof e==="bigint")if(t==="number"){if(e<lye||e>uye)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 I5)return e.buffer;return e}function E5(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<dye||e>fye)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 I5.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 C5(e,t){try{e.exec(t)}catch(r){throw R5(r)}}function R5(e){if(e instanceof Df.default.SqliteError){let t=e.code,r=pye(e.rawCode);return new Be(e.message,r,t,e.rawCode,e)}return e}function pye(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return mye[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Df,lye,uye=9007199254740991n,dye,fye=9223372036854775807n,mye;var O5=S(()=>{jn();Nf();Pl();Df=pu(k5(),1);jn();lye=-9007199254740991n;dye=-9223372036854775808n;mye={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 cs;var i$=S(()=>{if(typeof WebSocket<"u")cs=WebSocket;else if(typeof global<"u")cs=global.WebSocket;else if(typeof window<"u")cs=window.WebSocket;else if(typeof self<"u")cs=self.WebSocket});class Dl{constructor(){this.intMode="number"}intMode}var st,je,Lf,Ot,Bf,Ll,Aa,Un,xr,yi;var Pt=S(()=>{st=class st extends Error{constructor(e){super(e);this.name="ClientError"}};je=class je extends st{constructor(e){super(e);this.name="ProtoError"}};Lf=class Lf extends st{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};Ot=class Ot extends st{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Bf=class Bf extends st{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};Ll=class Ll extends st{constructor(e){super(e);this.name="WebSocketError"}};Aa=class Aa extends st{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Un=class Un extends st{constructor(e){super(e);this.name="ProtocolVersionError"}};xr=class xr extends st{constructor(e){super(e);this.name="InternalError"}};yi=class yi extends st{constructor(e){super(e);this.name="MisuseError"}}});function Fr(e){if(typeof e==="string")return e;throw Bl(e,"string")}function sn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw Bl(e,"string or null")}function Qi(e){if(typeof e==="number")return e;throw Bl(e,"number")}function ls(e){if(typeof e==="boolean")return e;throw Bl(e,"boolean")}function jf(e){if(Array.isArray(e))return e;throw Bl(e,"array")}function Lt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw Bl(e,"object")}function qn(e,t){return jf(e).map((r)=>t(Lt(r)))}function Bl(e,t){if(e===void 0)return new je(`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 je(`Expected ${t}, received ${r}`)}function $a(e,t){return t(Lt(e))}var jl=S(()=>{Pt()});class P5{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function Uf(e,t){let r=[],i=new P5(r);return i.begin(),t(i,e),i.end(),r.join("")}var Ca=0,qf=1,Zf=2,z5=5;class N5{#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 D5{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new je(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Zf);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return us(this.bytes(),e)}int32(){return this.#r(Ca),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(Ca),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(qf),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===Ca)this.#e.skipVarint();else if(this.#t===qf)this.#e.skip(8);else if(this.#t===Zf){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===z5)this.#e.skip(4);else throw new je(`Unexpected wire type ${this.#t}`);this.#t=-1}}function us(e,t){let r=new N5(e),i=new D5(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var o$=S(()=>{Pt()});class s${#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,Zf),this.#o(t.byteLength),this.#i(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 i=new s$;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,Ca),this.#o(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,Ca),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,qf),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Mf(e,t){let r=new s$;return t(r,e),r.data()}var L5=()=>{};var a$=S(()=>{jl();o$();L5()});class ds{#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 xr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var c$=S(()=>{Pt()});function rt(e,t){throw new xr(t)}var Sn=S(()=>{Pt()});function Ul(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<gye||e>yye)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 l$(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 yi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new je("Received unrecognized type of Value");else throw rt(e,"Impossible type of Value")}var gye,yye=9223372036854775807n;var u$=S(()=>{Pt();Sn();gye=-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 sb(e,t){let r=Ra(e),i=e.rows.map((n)=>B5(r.columnNames,n,t));return{...r,rows:i}}function ab(e,t){let r=Ra(e),i;if(e.rows.length>0)i=B5(r.columnNames,e.rows[0],t);return{...r,row:i}}function cb(e,t){let r=Ra(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=l$(e.rows[0][0],t);return{...r,value:i}}function B5(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=l$(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function Yi(e){return new Lf(e.message,e)}var Ff=S(()=>{Pt();u$()});class Oa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new yi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new Ot("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new st("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 Hf(e,t){if(t instanceof Oa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var ql=S(()=>{Pt()});class fs{#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 Kf{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(Ul(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]=Ul(t),this}bindName(e,t){return this._namedArgs.set(e,Ul(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function lb(e,t,r){let i,n=[],o=[];if(t instanceof Kf){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>Ul(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:Ul(l)}));else i=t;let{sql:s,sqlId:a}=Hf(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var ub=S(()=>{ql();u$()});class db{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new d$(this)}execute(){if(this.#t)throw new yi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Sye(this._stream,this._steps,e);else return bye(this._stream,this._steps,e)}}function bye(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function Sye(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new je("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new je("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,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new je("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new je("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!==o.step)throw new je("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new je("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Yi(a.error);else if(a.type==="none")throw new je("Server produced unrecognized CursorEntry");else throw rt(a,"Impossible CursorEntry")}if(o!==void 0)throw new je("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class d${_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,sb)}queryRow(e){return this.#t(e,!0,ab)}queryValue(e){return this.#t(e,!0,cb)}run(e){return this.#t(e,!1,Ra)}#t(e,t,r){if(this._index!==void 0)throw new yi("This BatchStep has already been added to the batch");let i=lb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new je("Server returned both result and error"));else if(u!==void 0)a(Yi(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class xt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new xt(e._batch,{type:"ok",step:j5(e)})}static error(e){return new xt(e._batch,{type:"error",step:j5(e)})}static not(e){return new xt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)U5(e,r);return new xt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)U5(e,r);return new xt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new xt(e,{type:"is_autocommit"})}}function j5(e){if(e._index===void 0)throw new yi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function U5(e,t){if(t._batch!==e)throw new yi("Cannot mix BatchCond objects for different Batch objects")}var f$=S(()=>{Pt();Ff();ub();Sn()});function q5(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Zl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,sb)}queryRow(e){return this.#e(e,!0,ab)}queryValue(e){return this.#e(e,!0,cb)}run(e){return this.#e(e,!1,Ra)}#e(e,t,r){let i=lb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new db(this,e)}describe(e){let t=Hf(this._sqlOwner(),e);return this._describe(t).then(q5)}sequence(e){let t=Hf(this._sqlOwner(),e);return this._sequence(t)}intMode}var fb=S(()=>{f$();Ff();ql();ub()});class Jf{}var xye=1000,wye=10,p$;var Z5=S(()=>{Pt();p$=class p$ extends Jf{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new fs,this.#i=new fs,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new Ot("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<wye)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:xye}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new st("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var Vf;var m$=S(()=>{Pt();fb();Z5();Vf=class Vf extends Zl{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new Vf(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new fs,this.#n=void 0,this.#i=!1,this.#o=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 xr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new Ot("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new xr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new Ot("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new Ot("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.#i){this.#l(new st("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new p$(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new st("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Wf(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,M5),e.arrayObjects("named_args",t.namedArgs,vye),e.boolean("want_rows",t.wantRows)}function vye(e,t){e.string("name",t.name),e.object("value",t.value,M5)}function Ml(e,t){e.arrayObjects("steps",t.steps,_ye)}function _ye(e,t){if(t.condition!==void 0)e.object("condition",t.condition,h$);e.object("stmt",t.stmt,Wf)}function h$(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,h$);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,h$);else if(t.type==="is_autocommit");else throw rt(t,"Impossible type of BatchCond")}function M5(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",Rl.fromUint8Array(t));else if(t===void 0);else throw rt(t,"Impossible type of Value")}var g$=S(()=>{rb();Sn()});function F5(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,kye);else throw rt(t,"Impossible type of ClientMsg")}function kye(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,Wf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Ml);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Ml);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 rt(t,"Impossible type of Request")}var H5=S(()=>{g$();Sn()});function Gf(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,J5);for(let r of t.namedArgs)e.message(4,r,Eye);e.bool(5,t.wantRows)}function Eye(e,t){e.string(1,t.name),e.message(2,t.value,J5)}function Fl(e,t){for(let r of t.steps)e.message(1,r,Iye)}function Iye(e,t){if(t.condition!==void 0)e.message(1,t.condition,y$);e.message(2,t.stmt,Gf)}function y$(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,y$);else if(t.type==="and")e.message(4,t.conds,K5);else if(t.type==="or")e.message(5,t.conds,K5);else if(t.type==="is_autocommit")e.message(6,void 0,V5);else throw rt(t,"Impossible type of BatchCond")}function K5(e,t){for(let r of t)e.message(1,r,y$)}function J5(e,t){if(t===null)e.message(1,void 0,V5);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 rt(t,"Impossible type of Value")}function V5(e,t){}var b$=S(()=>{Sn()});function W5(e,t){if(t.type==="hello")e.message(1,t,Tye);else if(t.type==="request")e.message(2,t,Aye);else throw rt(t,"Impossible type of ClientMsg")}function Tye(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Aye(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,$ye);else if(r.type==="close_stream")e.message(3,r,Cye);else if(r.type==="execute")e.message(4,r,Rye);else if(r.type==="batch")e.message(5,r,Oye);else if(r.type==="open_cursor")e.message(6,r,Pye);else if(r.type==="close_cursor")e.message(7,r,zye);else if(r.type==="fetch_cursor")e.message(8,r,Nye);else if(r.type==="sequence")e.message(9,r,Dye);else if(r.type==="describe")e.message(10,r,Lye);else if(r.type==="store_sql")e.message(11,r,Bye);else if(r.type==="close_sql")e.message(12,r,jye);else if(r.type==="get_autocommit")e.message(13,r,Uye);else throw rt(r,"Impossible type of Request")}function $ye(e,t){e.int32(1,t.streamId)}function Cye(e,t){e.int32(1,t.streamId)}function Rye(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Gf)}function Oye(e,t){e.int32(1,t.streamId),e.message(2,t.batch,Fl)}function Pye(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,Fl)}function zye(e,t){e.int32(1,t.cursorId)}function Nye(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Dye(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 Lye(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 Bye(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function jye(e,t){e.int32(1,t.sqlId)}function Uye(e,t){e.int32(1,t.streamId)}var G5=S(()=>{b$();Sn()});function ps(e){let t=Fr(e.message),r=sn(e.code);return{message:t,code:r}}function Qf(e){let t=qn(e.cols,Q5),r=jf(e.rows).map((s)=>qn(s,Y5)),i=Qi(e.affected_row_count),n=sn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function Q5(e){let t=sn(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function pb(e){let t=new Map;jf(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,Qf(Lt(i)))});let r=new Map;return jf(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,ps(Lt(i)))}),{stepResults:t,stepErrors:r}}function mb(e){let t=Fr(e.type);if(t==="step_begin"){let r=Qi(e.step),i=qn(e.cols,Q5);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=Qi(e.affected_row_count),i=sn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Qi(e.step),i=ps(Lt(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:qn(e.row,Y5)};else if(t==="error")return{type:"error",error:ps(Lt(e.error))};else throw new je("Unexpected type of CursorEntry")}function hb(e){let t=qn(e.params,qye),r=qn(e.cols,Zye),i=ls(e.is_explain),n=ls(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function qye(e){return{name:sn(e.name)}}function Zye(e){let t=Fr(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function Y5(e){let t=Fr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Fr(e.value);return BigInt(r)}else if(t==="float")return Qi(e.value);else if(t==="text")return Fr(e.value);else if(t==="blob")return Rl.toUint8Array(Fr(e.base64));else throw new je("Unexpected type of Value")}var gb=S(()=>{rb();Pt();jl()});function X5(e){let t=Fr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ps(Lt(e.error))};else if(t==="response_ok"){let r=Qi(e.request_id),i=Mye(Lt(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=Qi(e.request_id),i=ps(Lt(e.error));return{type:"response_error",requestId:r,error:i}}else throw new je("Unexpected type of ServerMsg")}function Mye(e){let t=Fr(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:Qf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:pb(Lt(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=qn(e.entries,mb),i=ls(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:hb(Lt(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:ls(e.is_autocommit)};else throw new je("Unexpected type of Response")}var e8=S(()=>{Pt();jl();gb()});var xn,ms,t8,r8,Hl,Fye,Hye,yb,Kye,Jye,Vye,Kl,Wye,Gye,Qye;var bb=S(()=>{xn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ms={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(t8))},2(e,t){t.rows.push(e.message(r8))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},t8={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},r8={default(){return[]},1(e,t){t.push(e.message(Qye))}},Hl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(Fye);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(Hye);t.stepErrors.set(r,i)}},Fye={default(){return[0,ms.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ms)}},Hye={default(){return[0,xn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(xn)}},yb={default(){return{type:"none"}},1(e){return e.message(Kye)},2(e){return e.message(Jye)},3(e){return e.message(Vye)},4(e){return{type:"row",row:e.message(r8)}},5(e){return{type:"error",error:e.message(xn)}}},Kye={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(t8))}},Jye={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Vye={default(){return{type:"step_error",step:0,error:xn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(xn)}},Kl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Wye))},2(e,t){t.cols.push(e.message(Gye))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Wye={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Gye={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Qye={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 n8,Yye,Xye,ebe,tbe,rbe,nbe,ibe,obe;var i8=S(()=>{bb();n8={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Yye)},3(e){return e.message(ebe)},4(e){return e.message(Xye)}},Yye={default(){return{type:"hello_error",error:xn.default()}},1(e,t){t.error=e.message(xn)}},Xye={default(){return{type:"response_error",requestId:0,error:xn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(xn)}},ebe={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(tbe)},5(e,t){t.response=e.message(rbe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(nbe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(ibe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(obe)}},tbe={default(){return{type:"execute",result:ms.default()}},1(e,t){t.result=e.message(ms)}},rbe={default(){return{type:"batch",result:Hl.default()}},1(e,t){t.result=e.message(Hl)}},nbe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(yb))},2(e,t){t.done=e.bool()}},ibe={default(){return{type:"describe",result:Kl.default()}},1(e,t){t.result=e.message(Kl)}},obe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var o8,S$,Sb;var xb=S(()=>{a$();Pt();c$();Ff();ql();Sn();m$();H5();G5();e8();i8();o8=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),S$=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Sb=class Sb extends Dl{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new ds,this._streamIdAlloc=new ds,this._cursorIdAlloc=new ds,this.#l=new ds,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 xr("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 st("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.#o={version:1,encoding:"json"};else if(this.#o=S$.get(e),this.#o===void 0){this.#u(new je(`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.#o.encoding;if(t==="json"){let r=Uf(e,F5);this.#e.send(r)}else if(t==="protobuf"){let r=Mf(e,W5);this.#e.send(r)}else throw rt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Un(`${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.#o.version<e)throw new Un(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new Ot("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 Ll(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new Ll(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new je("Received non-text message from server with JSON encoding"));return}t=$a(JSON.parse(e.data),X5)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new je("Received non-binary message from server with Protobuf encoding"));return}t=us(new Uint8Array(e.data),n8)}else throw rt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new je("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new je("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw Yi(e.error);return}else if(!this.#i)throw new je("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 je("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new je("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 je("Received unexpected error response");this.#c.free(t),r.errorCallback(Yi(e.error))}else throw rt(e,"Impossible ServerMsg type")}openStream(){return Vf.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Oa(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new st("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Pa;var s8=S(()=>{if(typeof queueMicrotask<"u")Pa=queueMicrotask;else{let e=Promise.resolve();Pa=(t)=>{e.then(t)}}});class x${#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function a8(e){let t=sn(e.baton),r=sn(e.base_url),i=qn(e.results,sbe);return{baton:t,baseUrl:r,results:i}}function sbe(e){let t=Fr(e.type);if(t==="ok")return{type:"ok",response:abe(Lt(e.response))};else if(t==="error")return{type:"error",error:ps(Lt(e.error))};else throw new je("Unexpected type of StreamResult")}function abe(e){let t=Fr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Qf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:pb(Lt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:hb(Lt(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:ls(e.is_autocommit)};else throw new je("Unexpected type of StreamResponse")}function c8(e){let t=sn(e.baton),r=sn(e.base_url);return{baton:t,baseUrl:r}}var w$=S(()=>{Pt();jl();gb()});var l8,cbe,lbe,ube,dbe,fbe,pbe,u8;var v$=S(()=>{bb();l8={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(cbe))}},cbe={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(lbe)}},2(e){return{type:"error",error:e.message(xn)}}},lbe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(ube)},3(e){return e.message(dbe)},4(e){return{type:"sequence"}},5(e){return e.message(fbe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(pbe)}},ube={default(){return{type:"execute",result:ms.default()}},1(e,t){t.result=e.message(ms)}},dbe={default(){return{type:"batch",result:Hl.default()}},1(e,t){t.result=e.message(Hl)}},fbe={default(){return{type:"describe",result:Kl.default()}},1(e,t){t.result=e.message(Kl)}},pbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},u8={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var _$;var d8=S(()=>{jl();o$();Pt();Sn();w$();v$();gb();bb();_$=class _$ extends Jf{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new x$(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new je("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(c8,u8);if(t===void 0)throw new je("Empty response to cursor request");return t}next(){return this.#a(mb,yb)}close(){this._setClosed(new st("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new Ot("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return $a(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return us(n,t)}else throw rt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new xr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new je("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function f8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,mbe)}function mbe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Wf);else if(t.type==="batch")e.object("batch",t.batch,Ml);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 rt(t,"Impossible type of StreamRequest")}function p8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Ml)}var k$=S(()=>{g$();Sn()});function m8(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,hbe)}function hbe(e,t){if(t.type==="close")e.message(1,t,gbe);else if(t.type==="execute")e.message(2,t,ybe);else if(t.type==="batch")e.message(3,t,bbe);else if(t.type==="sequence")e.message(4,t,Sbe);else if(t.type==="describe")e.message(5,t,xbe);else if(t.type==="store_sql")e.message(6,t,wbe);else if(t.type==="close_sql")e.message(7,t,vbe);else if(t.type==="get_autocommit")e.message(8,t,_be);else throw rt(t,"Impossible type of StreamRequest")}function gbe(e,t){}function ybe(e,t){e.message(1,t.stmt,Gf)}function bbe(e,t){e.message(1,t.batch,Fl)}function Sbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function xbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function wbe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function vbe(e,t){e.int32(1,t.sqlId)}function _be(e,t){}function h8(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,Fl)}var E$=S(()=>{b$();Sn()});function kbe(e,t){if(t.results.length!==e.length)throw new je("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new je("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(Yi(i.error));else if(i.type==="none")throw new je("Received unrecognized type of StreamResult");else throw rt(i,"Received impossible type of StreamResult")}}async function Ebe(e,t){if(t==="json"){let r=await e.json();return $a(r,a8)}if(t==="protobuf"){let r=await e.arrayBuffer();return us(new Uint8Array(r),l8)}throw await e.body?.cancel(),rt(t,"Impossible encoding")}async function Ibe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return Yi(i);return new Aa(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new Aa(r,e.status)}return await e.body?.cancel(),new Aa(r,e.status)}var wb;var I$=S(()=>{Pt();a$();c$();s8();Ff();ql();fb();Sn();d8();k$();E$();k$();E$();w$();v$();wb=class wb extends Zl{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new fs,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new ds}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 Oa(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 xr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Pa(()=>this.#u())}close(){this._setClosed(new st("Stream was manually closed"))}closeGracefully(){this.#l=!0,Pa(()=>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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Pa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new Ot("Stream is closed",this.#f);else if(this.#l)throw new Ot("Stream is closing",void 0);else this.#a.push(e),Pa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new st("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw rt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#S(t,e),(r)=>Ebe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>kbe(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new _$(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){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 Ibe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#x(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,f8,m8)}#w(e,t){if(t.cursorPath===void 0)throw new Un(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#x(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,p8,h8)}#x(e,t,r,i,n){let o,s;if(r==="json")o=Uf(t,i),s="application/json";else if(r==="protobuf")o=Mf(t,n),s="application/x-protobuf";else throw rt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function Abe(e,t){let r=e;for(let i of Tbe){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return T$}var Tbe,T$,vb;var A$=S(()=>{Pt();I$();Tbe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],T$={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};vb=class vb extends Dl{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=Abe(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(T$),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=T$.version)return;else if(this._endpoint===void 0)throw new Un(`${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 Un(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new Ot("Client is closed",this.#i);let e=new wb(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new st("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new Ot("Client was closed",e))}}});var g8=S(()=>{Pt()});function $$(e,t,r=2){if(typeof cs>"u")throw new Bf("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(S$.keys());else i=Array.from(o8.keys());let n=new cs(e,i);return new Sb(n,t)}function C$(e,t,r,i,n=2){return new vb(e instanceof URL?e:new URL(e),t,r,i,n)}var _b=S(()=>{i$();xb();Pt();A$();xb();i$();f$();g8();ql();ub();fb();A$();I$();xb();m$();Pt()});class Yf{#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 Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Xi),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(ss(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(xt.ok(c));if(this.#t>=3)u.condition(xt.not(xt.isAutocommit(o)));let f=u.query(l);return f.catch(()=>{return}),c=u,f}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(xt.ok(s));if(this.#t>=3)c.condition(xt.not(xt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new ar("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(Vl(s))}catch(s){if(s instanceof ar)throw s;let a=yt(s);if(a instanceof Be)throw new ar(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(ss(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Be("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function Jl(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(ss(e)),a=o,c=i.map((m)=>{let y=r.step().condition(xt.ok(a));if(t>=3)y.condition(xt.not(xt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(xt.ok(a));if(t>=3)l.condition(xt.not(xt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(xt.not(xt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new ar("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(Vl(y))}catch(y){if(y instanceof ar)throw y;let g=yt(y);if(g instanceof Be)throw new ar(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function Xi(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 i=new Kf(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function Vl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new Ol(t,r,i,n,o)}function yt(e){if(e instanceof st){let t=y8(e);return new Be(e.message,t,void 0,void 0,e)}return e}function y8(e){if(e instanceof Lf&&e.code!==void 0)return e.code;else if(e instanceof je)return"HRANA_PROTO_ERROR";else if(e instanceof Ot)return e.cause instanceof st?y8(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof Ll)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Aa)return"SERVER_ERROR";else if(e instanceof Un)return"PROTOCOL_VERSION_ERROR";else if(e instanceof xr)return"INTERNAL_ERROR";else return"UNKNOWN"}var O$=S(()=>{_b();jn();Pl()});class Wl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new b8,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class b8{#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 P$=Se(function(G3e,x8){function $be(e){var t=0,r=[];function i(){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 o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function Cbe(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function S8(e){return e.queue=0,e.map=Cbe,e}x8.exports=function(e){if(e)return S8($be(e));else return S8(function(t){return t()})}});function _8(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Be(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Be('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Be('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Of(e.scheme,e.authority,e.path),r;try{r=$$(t,e.authToken)}catch(i){if(i instanceof Bf){let n=e.scheme==="wss"?"https":"http",o=Of(n,e.authority,e.path);throw new Be(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${mi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new k8(r,t,e.authToken,e.intMode,e.concurrency)}class k8{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=v8.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 i=await this.#s();try{let n=Xi(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return Vl(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Xi),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await Jl(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Xi),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await Jl("deferred",i,n,r,!0)}catch(r){throw yt(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 E8(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Be("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Rbe&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=w8}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=$$(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Wl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=w8;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var v8,Rbe=60000,w8=100,E8;var I8=S(()=>{_b();jn();Nf();O$();Xy();Pl();v8=pu(P$(),1);jn();E8=class E8 extends Yf{#e;#t;constructor(e,t,r,i){super(r,i);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 A8(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Be(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Be('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Be('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Of(e.scheme,e.authority,e.path);return new C8(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class C8{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=C$(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=T8.default(this.#i)}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 i=Xi(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return Vl(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(Xi),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new Wl(s,$8).apply(i);let l=s.batch(!1);o=Jl(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Xi),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=Jl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new R8(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Be("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=C$(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var T8,$8=30,R8;var O8=S(()=>{_b();jn();Nf();O$();Xy();Pl();T8=pu(P$(),1);jn();R8=class R8 extends Yf{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Wl(e,$8)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Gl(e){return Obe(zf(e,!0))}function Obe(e){if(e.scheme==="wss"||e.scheme==="ws")return _8(e);else if(e.scheme==="https"||e.scheme==="http")return A8(e);else return T5(e)}var z$=S(()=>{Nf();O5();I8();O8();jn()});function ae(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,J))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(J in r&&r[J]===t[J])return!0;r=Object.getPrototypeOf(r)}return!1}var J;var ze=S(()=>{J=Symbol.for("drizzle:entityKind")});var nt;var Zn=S(()=>{ze();nt=class nt{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[J]="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 Xf;var kb=S(()=>{ze();Xf=class Xf{static[J]="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 wr;var Ql=S(()=>{wr=Symbol.for("drizzle:Name")});var N$,P8;var z8=S(()=>{ze();Ql();N$=class N${static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 P8(e,this)}};P8=class P8{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function Eb(e,...t){return e(...t)}var D$=()=>{};function L$(e,t){return`${e[wr]}_${t.join("_")}_unique`}var N8,Pbe,D8;var L8=S(()=>{ze();Ql();N8=class N8{constructor(e,t){this.name=t,this.columns=e}static[J]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new D8(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Pbe=class Pbe{static[J]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new N8(e,this.name)}};D8=class D8{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??L$(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[J]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function B8(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function j8(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=B8(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=j8(e,i+1);r.push(c),i=l;continue}let[s,a]=B8(e,i,!1);r.push(s),i=a}return[r,i]}function U8(e){let[t]=j8(e,1);return t}function B$(e){return`{${e.map((t)=>{if(Array.isArray(t))return B$(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var q8=()=>{};var ep,Yl,Z8,zbe,M8,j$;var F8=S(()=>{kb();Zn();ze();z8();D$();L8();q8();ep=class ep extends Xf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(e){return new M8(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:i})=>Eb((n,o)=>{let s=new N$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new Z8(e,this.config)}};Yl=class Yl extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=L$(e,[t.name]);super(e,t);this.table=e}static[J]="PgColumn"};Z8=class Z8 extends Yl{static[J]="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}};zbe=class zbe{static[J]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};M8=class M8 extends ep{static[J]="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 j$(e,this.config,t)}};j$=class j$ extends Yl{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=U8(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ae(this.baseColumn,j$)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return B$(r)}}});function J8(e){return!!e&&typeof e==="function"&&H8 in e&&e[H8]===!0}var Nbe,K8,H8,Dbe,V8;var W8=S(()=>{ze();F8();Nbe=class Nbe extends ep{static[J]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new K8(e,this.config)}};K8=class K8 extends Yl{static[J]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};H8=Symbol.for("drizzle:isPgEnum");Dbe=class Dbe extends ep{static[J]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new V8(e,this.config)}};V8=class V8 extends Yl{static[J]="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 wt,tp;var Mn=S(()=>{ze();wt=class wt{static[J]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};tp=class tp extends wt{static[J]="WithSubquery"}});var G8="0.45.2";var Q8=()=>{};var U$,q$,Y8;var X8=S(()=>{D$();Q8();Y8={startActiveSpan(e,t){if(!U$)return t();if(!q$)q$=U$.trace.getTracer("drizzle-orm",G8);return Eb((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),U$,q$)}}});var vt;var eo=S(()=>{vt=Symbol.for("drizzle:ViewBaseConfig")});function hs(e){return e[wr]}function za(e){return`${e[Ib]??"public"}.${e[wr]}`}var Ib,Tb,eH,Z$,M$,rp,tH,Lbe,we;var vr=S(()=>{ze();Ql();Ib=Symbol.for("drizzle:Schema"),Tb=Symbol.for("drizzle:Columns"),eH=Symbol.for("drizzle:ExtraConfigColumns"),Z$=Symbol.for("drizzle:OriginalName"),M$=Symbol.for("drizzle:BaseName"),rp=Symbol.for("drizzle:IsAlias"),tH=Symbol.for("drizzle:ExtraConfigBuilder"),Lbe=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[J]="Table";static Symbol={Name:wr,Schema:Ib,OriginalName:Z$,Columns:Tb,ExtraConfigColumns:eH,BaseName:M$,IsAlias:rp,ExtraConfigBuilder:tH};[wr];[Z$];[Ib];[Tb];[eH];[M$];[rp]=!1;[Lbe]=!0;[tH]=void 0;constructor(e,t,r){this[wr]=this[Z$]=e,this[Ib]=t,this[M$]=r}}});function F$(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function jbe(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 rH(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function U(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Ft(e[0]));for(let[i,n]of t.entries())r.push(n,new Ft(e[i+1]));return new Te(r)}function np(e,t){return e.map((r)=>{if(ae(r,gs)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ae(r,an)&&ae(r.value,gs)){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 Bbe,Ft,Te,Ab,nH,iH,a8e,an,gs,Ube,wn;var lr=S(()=>{ze();W8();Mn();X8();eo();Zn();vr();Bbe=class Bbe{static[J]="FakePrimitiveParam"};Ft=class Ft{static[J]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Te([this])}};Te=class Te{constructor(e){this.queryChunks=e;for(let t of e)if(ae(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[J]="SQL";decoder=nH;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Y8.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return jbe(e.map((l)=>{if(ae(l,Ft))return{sql:l.value.join(""),params:[]};if(ae(l,Ab))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Ft("(")];for(let[f,p]of l.entries())if(u.push(p),f<l.length-1)u.push(new Ft(", "));return u.push(new Ft(")")),this.buildQueryFromSourceParams(u,r)}if(ae(l,Te))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ae(l,we)){let u=l[we.Symbol.Schema],f=l[we.Symbol.Name];return{sql:u===void 0||l[rp]?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,nt)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let f=l.table[we.Symbol.Schema];return{sql:l.table[rp]||f===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(f)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ae(l,wn)){let u=l[vt].schema,f=l[vt].name;return{sql:u===void 0||l[vt].isAlias?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,an)){if(ae(l.value,gs))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ae(u,Te))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let f=["none"];if(s)f=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:f}}if(ae(l,gs))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ae(l,Te.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ae(l,wt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Ft("("),l._.sql,new Ft(") "),new Ab(l._.alias)],r)}if(J8(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(F$(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Ft("("),l.getSQL(),new Ft(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 Te.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}};Ab=class Ab{constructor(e){this.value=e}static[J]="Name";brand;getSQL(){return new Te([this])}};nH={mapFromDriverValue:(e)=>e},iH={mapToDriverValue:(e)=>e},a8e={...nH,...iH};an=class an{constructor(e,t=iH){this.value=e,this.encoder=t}static[J]="Param";brand;getSQL(){return new Te([this])}};((e)=>{function t(){return new Te([])}e.empty=t;function r(c){return new Te(c)}e.fromList=r;function i(c){return new Te([new Ft(c)])}e.raw=i;function n(c,l){let u=[];for(let[f,p]of c.entries()){if(f>0&&l!==void 0)u.push(l);u.push(p)}return new Te(u)}e.join=n;function o(c){return new Ab(c)}e.identifier=o;function s(c){return new gs(c)}e.placeholder=s;function a(c,l){return new an(c,l)}e.param=a})(U||(U={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Te||(Te={}));gs=class gs{constructor(e){this.name=e}static[J]="Placeholder";getSQL(){return new Te([this])}};Ube=Symbol.for("drizzle:IsDrizzleView");wn=class wn{static[J]="View";[vt];[Ube]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[vt]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Te([this])}};nt.prototype.getSQL=function(){return new Te([this])};we.prototype.getSQL=function(){return new Te([this])};wt.prototype.getSQL=function(){return new Te([this])}});function H$(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ae(a,nt))l=a;else if(ae(a,Te))l=a.decoder;else if(ae(a,wt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[f,p]of s.entries())if(f<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ae(a,nt)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?hs(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==hs(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function vn(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ae(n,nt)||ae(n,Te)||ae(n,Te.Aliased)||ae(n,wt))r.push({path:o,field:n});else if(ae(n,we))r.push(...vn(n[we.Symbol.Columns],o));else r.push(...vn(n,o));return r},[])}function ip(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function $b(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ae(n,Te)||ae(n,nt))return[i,n];else return[i,new an(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function oH(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function Cb(e){return e[we.Symbol.Columns]}function op(e){return ae(e,wt)?e._.alias:ae(e,wn)?e[vt].name:ae(e,Te)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function bi(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function sH(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 K$;var Dr=S(()=>{Zn();ze();lr();Mn();vr();eo();K$=typeof TextDecoder>"u"?null:new TextDecoder});var aH,J$,V$;var Rb=S(()=>{ze();aH=class aH{static[J]="ConsoleLogWriter";write(e){console.log(e)}};J$=class J${static[J]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new aH}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};V$=class V${static[J]="NoopLogger";logQuery(){}}});var cH,lH,W$;var uH=S(()=>{ze();vr();cH=Symbol.for("drizzle:PgInlineForeignKeys"),lH=Symbol.for("drizzle:EnableRLS");W$=class W$ extends we{static[J]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:cH,EnableRLS:lH});[cH]=[];[lH]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var G$,dH;var fH=S(()=>{ze();uH();G$=class G${static[J]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new dH(e,this.columns,this.name)}};dH=class dH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[W$.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Hr(e,t){if(rH(t)&&!F$(e)&&!ae(e,an)&&!ae(e,gs)&&!ae(e,nt)&&!ae(e,we)&&!ae(e,wn))return new an(e,t);return e}function Et(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" and ")),new Ft(")")])}function Si(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" or ")),new Ft(")")])}function mH(e){return U`not ${e}`}function ys(e,t){if(Array.isArray(t)){if(t.length===0)return U`false`;return U`${e} in ${t.map((r)=>Hr(r,e))}`}return U`${e} in ${Hr(t,e)}`}function Ob(e,t){if(Array.isArray(t)){if(t.length===0)return U`true`;return U`${e} not in ${t.map((r)=>Hr(r,e))}`}return U`${e} not in ${Hr(t,e)}`}function _n(e){return U`${e} is null`}function yH(e){return U`${e} is not null`}function Pb(e){return U`exists ${e}`}function ap(e){return U`not exists ${e}`}function bH(e,t,r){return U`${e} between ${Hr(t,e)} and ${Hr(r,e)}`}function SH(e,t,r){return U`${e} not between ${Hr(t,e)} and ${Hr(r,e)}`}function xH(e,t){return U`${e} like ${t}`}function wH(e,t){return U`${e} not like ${t}`}function vH(e,t){return U`${e} ilike ${t}`}function _H(e,t){return U`${e} not ilike ${t}`}var Qe=(e,t)=>U`${e} = ${Hr(t,e)}`,pH=(e,t)=>U`${e} <> ${Hr(t,e)}`,sp=(e,t)=>U`${e} > ${Hr(t,e)}`,hH=(e,t)=>U`${e} >= ${Hr(t,e)}`,gH=(e,t)=>U`${e} < ${Hr(t,e)}`,Xl=(e,t)=>U`${e} <= ${Hr(t,e)}`;var kH=S(()=>{Zn();ze();vr();lr()});function to(e){return U`${e} asc`}function Na(e){return U`${e} desc`}var EH=S(()=>{lr()});var Q$=S(()=>{kH();EH()});function TH(){return{and:Et,between:bH,eq:Qe,exists:Pb,gt:sp,gte:hH,ilike:vH,inArray:ys,isNull:_n,isNotNull:yH,like:xH,lt:gH,lte:Xl,ne:pH,not:mH,notBetween:SH,notExists:ap,notLike:wH,notIlike:_H,notInArray:Ob,or:Si,sql:U}}function AH(){return{sql:U,asc:to,desc:Na}}function $H(e,t){if(Object.keys(e).length===1&&"default"in e&&!ae(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ae(s,we)){let a=za(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ae(u,G$))n[o].primaryKey.push(...u.columns)}}else if(ae(s,IH)){let a=za(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[f,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[f]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[f]=p}}return{tables:n,tableNamesMap:r}}function qbe(e){return function(r,i){return new bs(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function Zbe(e){return function(r,i){return new cp(e,r,i)}}function CH(e,t,r){if(ae(r,bs)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[za(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[za(o)];if(!s)throw Error(`Table "${o[we.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 "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ae(a[0],bs)&&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 RH(e){return{one:qbe(e),many:Zbe(e)}}function zb(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ae(c,bs)?u&&zb(e,e[a.relationTableTsKey],u,a.selection,n):u.map((f)=>zb(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ae(l,nt))u=l;else if(ae(l,Te))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var Y$,IH,bs,cp;var lp=S(()=>{vr();Zn();ze();fH();Q$();lr();Y$=class Y${constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName};IH=class IH{constructor(e,t){this.table=e,this.config=t}static[J]="Relations"};bs=class bs extends Y${constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[J]="One";withFieldName(e){let t=new bs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};cp=class cp extends Y${constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[J]="Many";withFieldName(e){let t=new cp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function up(e,t){return new Proxy(e,new Da(t,!1))}function xi(e,t){return new Proxy(e,new eu(new Proxy(e.table,new Da(t,!1))))}function X$(e,t){return new Te.Aliased(dp(e.sql,t),e.fieldAlias)}function dp(e,t){return U.join(e.queryChunks.map((r)=>{if(ae(r,nt))return xi(r,t);if(ae(r,Te))return dp(r,t);if(ae(r,Te.Aliased))return X$(r,t);return r}))}var eu,Da,Mbe;var fp=S(()=>{Zn();ze();lr();vr();eo();eu=class eu{constructor(e){this.table=e}static[J]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Da=class Da{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[J]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===vt)return{...e[vt],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new eu(new Proxy(e,this)))}),n}let r=e[t];if(ae(r,nt))return new Proxy(r,new eu(new Proxy(e,this)));return r}};Mbe=class Mbe{constructor(e){this.alias=e}static[J]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return up(e.sourceTable,this.alias);return e[t]}}});var bt;var La=S(()=>{fp();Zn();ze();lr();Mn();eo();bt=class bt{static[J]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===vt)return{...e[vt],selectedFields:new Proxy(e[vt].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ae(e,wt)?e._.selectedFields:ae(e,wn)?e[vt].selectedFields:e)[t];if(ae(i,Te.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ae(i,Te)){if(this.config.sqlBehavior==="sql")return i;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(ae(i,nt)){if(this.config.alias)return new Proxy(i,new eu(new Proxy(i.table,new Da(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Lr;var ro=S(()=>{ze();Lr=class Lr{static[J]="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 eC,OH;var tC=S(()=>{ze();Ql();eC=class eC{static[J]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 OH(e,this)}};OH=class OH{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function rC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var PH,Fbe,zH;var nC=S(()=>{ze();Ql();PH=class PH{constructor(e,t){this.name=t,this.columns=e}static[J]="SQLiteUniqueConstraintBuilder";columns;build(e){return new zH(e,this.columns,this.name)}};Fbe=class Fbe{static[J]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new PH(e,this.name)}};zH=class zH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??rC(this.table,this.columns.map((i)=>i.name))}static[J]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Gt,It;var Ss=S(()=>{kb();Zn();ze();tC();nC();Gt=class Gt extends Xf{static[J]="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:i})=>((n,o)=>{let s=new eC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};It=class It extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=rC(e,[t.name]);super(e,t);this.table=e}static[J]="SQLiteColumn"}});function qH(e,t){let{name:r,config:i}=bi(e,t);if(i?.mode==="json")return new LH(r);if(i?.mode==="bigint")return new NH(r);return new jH(r)}var NH,DH,LH,BH,jH,UH;var iC=S(()=>{ze();Dr();Ss();NH=class NH extends Gt{static[J]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new DH(e,this.config)}};DH=class DH extends It{static[J]="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(K$.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};LH=class LH extends Gt{static[J]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new BH(e,this.config)}};BH=class BH extends It{static[J]="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(K$.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};jH=class jH extends Gt{static[J]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new UH(e,this.config)}};UH=class UH extends It{static[J]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function FH(e){return(t,r)=>{let{name:i,config:n}=bi(t,r);return new ZH(i,n,e)}}var ZH,MH;var oC=S(()=>{ze();Dr();Ss();ZH=class ZH extends Gt{static[J]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new MH(e,this.config)}};MH=class MH extends It{static[J]="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 _r(e,t){let{name:r,config:i}=bi(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new JH(r,i.mode);if(i?.mode==="boolean")return new WH(r,i.mode);return new HH(r)}var Nb,Db,HH,KH,JH,VH,WH,GH;var sC=S(()=>{ze();lr();Dr();Ss();Nb=class Nb extends Gt{static[J]="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()}};Db=class Db extends It{static[J]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};HH=class HH extends Nb{static[J]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new KH(e,this.config)}};KH=class KH extends Db{static[J]="SQLiteInteger"};JH=class JH extends Nb{static[J]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(U`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new VH(e,this.config)}};VH=class VH extends Db{static[J]="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}};WH=class WH extends Nb{static[J]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new GH(e,this.config)}};GH=class GH extends Db{static[J]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function nK(e,t){let{name:r,config:i}=bi(e,t),n=i?.mode;return n==="number"?new XH(r):n==="bigint"?new tK(r):new QH(r)}var QH,YH,XH,eK,tK,rK;var aC=S(()=>{ze();Dr();Ss();QH=class QH extends Gt{static[J]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new YH(e,this.config)}};YH=class YH extends It{static[J]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};XH=class XH extends Gt{static[J]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new eK(e,this.config)}};eK=class eK extends It{static[J]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};tK=class tK extends Gt{static[J]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new rK(e,this.config)}};rK=class rK extends It{static[J]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function sK(e){return new iK(e??"")}var iK,oK;var cC=S(()=>{ze();Ss();iK=class iK extends Gt{static[J]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new oK(e,this.config)}};oK=class oK extends It{static[J]="SQLiteReal";getSQLType(){return"real"}}});function ur(e,t={}){let{name:r,config:i}=bi(e,t);if(i.mode==="json")return new lK(r);return new aK(r,i)}var aK,cK,lK,uK;var lC=S(()=>{ze();Dr();Ss();aK=class aK extends Gt{static[J]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new cK(e,this.config)}};cK=class cK extends It{static[J]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};lK=class lK extends Gt{static[J]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new uK(e,this.config)}};uK=class uK extends It{static[J]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function dK(){return{blob:qH,customType:FH,integer:_r,numeric:nK,real:sK,text:ur}}var fK=S(()=>{iC();oC();sC();aC();cC();lC()});function Hbe(e,t,r,i,n=e){let o=new Bt(e,i,n),s=typeof t==="function"?t(dK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let f=u;f.setName(l);let p=f.build(o);return o[uC].push(...f.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Bt.Symbol.ExtraConfigBuilder]=r;return c}var uC,Bt,pp=(e,t,r)=>Hbe(e,t,r);var no=S(()=>{ze();vr();fK();uC=Symbol.for("drizzle:SQLiteInlineForeignKeys");Bt=class Bt extends we{static[J]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:uC});[we.Symbol.Columns];[uC]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var Kbe,pK;var mK=S(()=>{ze();Kbe=class Kbe{constructor(e,t){this.name=e,this.value=t}static[J]="SQLiteCheckBuilder";brand;build(e){return new pK(e,this)}};pK=class pK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[J]="SQLiteCheck";name;value}});function io(e){return new hK(e,!1)}var hK,gK,yK;var bK=S(()=>{ze();hK=class hK{constructor(e,t){this.name=e,this.unique=t}static[J]="SQLiteIndexBuilderOn";on(...e){return new gK(this.name,e,this.unique)}};gK=class gK{static[J]="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 yK(this.config,e)}};yK=class yK{static[J]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Jbe,SK;var xK=S(()=>{ze();no();Jbe=class Jbe{static[J]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new SK(e,this.columns,this.name)}};SK=class SK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Bt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Fn(e){if(ae(e,Bt))return[`${e[we.Symbol.BaseName]}`];if(ae(e,wt))return e._.usedTables??[];if(ae(e,Te))return e.usedTables??[];return[]}var tu=S(()=>{ze();lr();Mn();vr();no()});var Lb;var wK=S(()=>{ze();ro();La();no();vr();Dr();tu();Lb=class Lb extends Lr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[J]="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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=vn(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:Fn(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 Vbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Wbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function Gbe(e){return e}var dC;var vK=S(()=>{ze();vr();dC=class dC{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Vbe:e==="camelCase"?Wbe:Gbe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var ru,oo,fC;var Bb=S(()=>{ze();ru=class ru extends Error{static[J]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};oo=class oo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
397
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=ka.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=ka.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=ka.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=ka.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<=ka.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ka.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new on({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ka,vZe;var WA=S(()=>{ka={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};vZe=on.getInstance()});var GA,Khe,Al,IZe;var Cf=S(()=>{pi();Ae();GA=d.enum(["file_operations","content_operations","data_processing","batch_processing"]),Khe=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:GA,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:pl.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:Go.optional()}),Al=d.looseObject({pluginId:d.string().optional(),progressToken:d.union([d.string(),d.number()]).optional(),operationType:GA,operationTarget:d.string().optional(),interfaceType:d.string().optional(),conversationId:d.string().optional(),channelId:d.string().optional(),requestedByActor:pl.optional(),requestedByUserId:d.string().optional(),requestedByInterface:d.string().optional(),silent:d.boolean().optional(),provenance:Go.optional(),rootJobId:d.string()}),IZe=d.enum(["none","skip","replace","coalesce"])});var Jhe,is=15000;var Rf=S(()=>{Cf();Ae();Jhe=d.object({id:d.string(),type:d.string(),data:d.string(),status:d.enum(["pending","processing","completed","failed"]),source:d.string().nullable(),priority:d.number(),retryCount:d.number(),maxRetries:d.number(),lastError:d.string().nullable(),createdAt:d.number(),scheduledFor:d.number(),startedAt:d.number().nullable(),completedAt:d.number().nullable(),attemptId:d.string().nullable(),workerSlotId:d.string().nullable(),workerSessionId:d.string().nullable(),leaseExpiresAt:d.number().nullable(),attemptHeartbeatAt:d.number().nullable(),runtimeUpdatedAt:d.number().nullable(),metadata:Al,progress:d.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:d.unknown().nullable().optional()})});var QA,x3,Ue,Vhe,Whe,w3,Ghe;var os=S(()=>{Ae();Cf();QA=d.enum(["pending","processing","completed","failed"]),x3=d.enum(["completed","failed"]),Ue={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Vhe=d.object({id:d.string(),type:d.string(),status:QA,data:d.unknown(),result:d.unknown().optional(),lastError:d.string().optional().nullable(),attempts:d.number(),maxRetries:d.number(),priority:d.number(),createdAt:d.date(),updatedAt:d.date(),processedAt:d.date().optional().nullable(),completedAt:d.date().optional().nullable(),failedAt:d.date().optional().nullable()}),Whe=d.object({jobId:d.string(),type:d.string(),status:x3,result:d.unknown().optional(),error:d.string().optional()}),w3=d.object({success:d.literal(!1),error:d.string().optional()}),Ghe=d.object({id:d.string(),type:d.enum(["job","batch"]),status:QA,message:d.string().optional(),progress:d.object({current:d.number(),total:d.number(),percentage:d.number()}).optional(),aggregationKey:d.string().optional(),batchDetails:d.object({totalOperations:d.number(),completedOperations:d.number(),failedOperations:d.number(),currentOperation:d.string().optional(),errors:d.array(d.string()).optional()}).optional(),jobDetails:d.object({jobType:d.string(),priority:d.number(),retryCount:d.number()}).optional(),metadata:Al})});var Be,ar;var jn=S(()=>{Be=class Be extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};ar=class ar extends Be{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function v3(e){let t=Qhe.exec(e);if(t===null)throw new Be(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?Yhe(r.authority):void 0,o=Ea(r.path),s=r.query!==void 0?ege(r.query):void 0,a=r.fragment!==void 0?Ea(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function Yhe(e){let t=Xhe.exec(e);if(t===null)throw new Be("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=Ea(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:Ea(r.username),password:r.password!==void 0?Ea(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function ege(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:Ea(n.replaceAll("+"," ")),value:Ea(o.replaceAll("+"," "))})}return{pairs:r}}function Ea(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Be(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function Of(e,t,r){if(t===void 0)throw new Be(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=tge(t.host),o=rge(t.port),a=`//${nge(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function tge(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function rge(e){return e!==void 0?`:${e}`:""}function nge(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Qhe,Xhe;var Xy=S(()=>{jn();Qhe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Xhe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Cl,_3,k3,Pf,eb,ige,cr,E3,A3=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),$3=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),C3=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=Pf[t>>18&63]+Pf[t>>12&63]+Pf[t>>6&63]+Pf[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},e$,YA,tb=(e,t=!1)=>t?A3(YA(e)):YA(e),oge=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?cr(192|t>>>6)+cr(128|t&63):cr(224|t>>>12&15)+cr(128|t>>>6&63)+cr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return cr(240|t>>>18&7)+cr(128|t>>>12&63)+cr(128|t>>>6&63)+cr(128|t&63)}},sge,R3=(e)=>e.replace(sge,oge),I3,$l=(e,t=!1)=>t?A3(I3(e)):I3(e),T3=(e)=>$l(e,!0),age,cge=(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 cr((r>>>10)+55296)+cr((r&1023)+56320);case 3:return cr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return cr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},O3=(e)=>e.replace(age,cge),P3=(e)=>{if(e=e.replace(/\s+/g,""),!ige.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=eb[e.charAt(o++)]<<18|eb[e.charAt(o++)]<<12|(r=eb[e.charAt(o++)])<<6|(i=eb[e.charAt(o++)]),r===64)n.push(cr(t>>16&255));else if(i===64)n.push(cr(t>>16&255,t>>8&255));else n.push(cr(t>>16&255,t>>8&255,t&255));return n.join("")},t$,z3,N3=(e)=>z3(D3(e)),lge,D3=(e)=>$3(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),XA=(e)=>lge(D3(e)),uge=(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)},L3=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),B3=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,L3(r));e("fromBase64",function(){return XA(this)}),e("toBase64",function(t){return $l(this,t)}),e("toBase64URI",function(){return $l(this,!0)}),e("toBase64URL",function(){return $l(this,!0)}),e("toUint8Array",function(){return N3(this)})},j3=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,L3(r));e("toBase64",function(t){return tb(this,t)}),e("toBase64URI",function(){return tb(this,!0)}),e("toBase64URL",function(){return tb(this,!0)})},dge=()=>{B3(),j3()},Rl;var rb=S(()=>{Cl=typeof Buffer==="function",_3=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,k3=typeof TextEncoder==="function"?new TextEncoder:void 0,Pf=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),eb=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(Pf),ige=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,cr=String.fromCharCode.bind(String),E3=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),e$=typeof btoa==="function"?(e)=>btoa(e):Cl?(e)=>Buffer.from(e,"binary").toString("base64"):C3,YA=Cl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(cr.apply(null,e.subarray(i,i+4096)));return e$(r.join(""))},sge=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,I3=Cl?(e)=>Buffer.from(e,"utf8").toString("base64"):k3?(e)=>YA(k3.encode(e)):(e)=>e$(R3(e)),age=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,t$=typeof atob==="function"?(e)=>atob($3(e)):Cl?(e)=>Buffer.from(e,"base64").toString("binary"):P3,z3=Cl?(e)=>E3(Buffer.from(e,"base64")):(e)=>E3(t$(e).split("").map((t)=>t.charCodeAt(0))),lge=Cl?(e)=>Buffer.from(e,"base64").toString("utf8"):_3?(e)=>_3.decode(z3(e)):(e)=>O3(t$(e)),Rl={version:"3.8.0",VERSION:"3.8.0",atob:t$,atobPolyfill:P3,btoa:e$,btoaPolyfill:C3,fromBase64:XA,toBase64:$l,encode:$l,encodeURI:T3,encodeURL:T3,utob:R3,btou:O3,decode:XA,isValid:uge,fromUint8Array:tb,toUint8Array:N3,extendString:B3,extendUint8Array:j3,extendBuiltins:dge}});function ss(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 Ol{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(fge),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function fge(e){return Array.prototype.map.call(e,pge)}function pge(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Rl.fromUint8Array(new Uint8Array(e));else return e}var mi="https://github.com/libsql/libsql-client-ts#supported-urls";var Pl=S(()=>{rb()});function q3(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function zf(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===U3)r="file::memory:";let c=v3(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===U3&&c.authority===void 0,f;if(u)f={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else f={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(f,g))throw new Be(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let _=f[g];if(_.values!==void 0&&!_.values.includes(b))throw new Be(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${_.values.map((T)=>'"'+T+'"').join(", ")}]`,"URL_INVALID");if(_.update!==void 0)_?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Be('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Be(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Be(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 U3=":memory:";var Nf=S(()=>{jn();Xy();Pl()});var M3=Se(function(bn){var mge=bn&&bn.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),hge=bn&&bn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Z3=bn&&bn.__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))mge(t,e,r)}return hge(t,e),t};Object.defineProperty(bn,"__esModule",{value:!0});bn.load=bn.currentTarget=void 0;var gge=Z3(fr("path")),yge=Z3(fr("fs"));function bge(){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 Sge()?`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}`)}bn.currentTarget=bge;function Sge(){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 xge(e){let t=gge.join(e,"index.node");return yge.existsSync(t)?fr(t):null}bn.load=xge});var K3=Se(function(KZe,H3){var F3=()=>process.platform==="linux",r$=null,wge=()=>{if(!r$)r$=F3()&&process.report?process.report.getReport():{};return r$};H3.exports={isLinux:F3,getReport:wge}});var W3=Se(function(JZe,V3){var J3=fr("fs"),vge=(e)=>J3.readFileSync(e,"utf-8"),_ge=(e)=>new Promise((t,r)=>{J3.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});V3.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:vge,readFile:_ge}});var f5=Se(function(VZe,d5){var Q3=fr("child_process"),{isLinux:zl,getReport:Y3}=K3(),{LDD_PATH:nb,readFile:X3,readFileSync:e5}=W3(),hi,gi,as="",t5=()=>{if(!as)return new Promise((e)=>{Q3.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{as=t?" ":r,e(as)})});return as},r5=()=>{if(!as)try{as=Q3.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){as=" "}return as},Gi="glibc",n5=/GLIBC\s(\d+\.\d+)/,Ia="musl",kge=Gi.toUpperCase(),Ege=Ia.toLowerCase(),Ige=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),i5=()=>{let e=Y3();if(e.header&&e.header.glibcVersionRuntime)return Gi;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Ige))return Ia}return null},o5=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Gi))return Gi;if(r&&r.includes(Ia))return Ia;return null},s5=(e)=>{if(e.includes(Ege))return Ia;if(e.includes(kge))return Gi;return null},Tge=async()=>{if(hi!==void 0)return hi;hi=null;try{let e=await X3(nb);hi=s5(e)}catch(e){}return hi},Age=()=>{if(hi!==void 0)return hi;hi=null;try{let e=e5(nb);hi=s5(e)}catch(e){}return hi},a5=async()=>{let e=null;if(zl()){if(e=await Tge(),!e)e=i5();if(!e){let t=await t5();e=o5(t)}}return e},c5=()=>{let e=null;if(zl()){if(e=Age(),!e)e=i5();if(!e){let t=r5();e=o5(t)}}return e},$ge=async()=>zl()&&await a5()!==Gi,Cge=()=>zl()&&c5()!==Gi,Rge=async()=>{if(gi!==void 0)return gi;gi=null;try{let t=(await X3(nb)).match(n5);if(t)gi=t[1]}catch(e){}return gi},Oge=()=>{if(gi!==void 0)return gi;gi=null;try{let t=e5(nb).match(n5);if(t)gi=t[1]}catch(e){}return gi},l5=()=>{let e=Y3();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},G3=(e)=>e.trim().split(/\s+/)[1],u5=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(Gi))return G3(t);if(r&&i&&r.includes(Ia))return G3(i);return null},Pge=async()=>{let e=null;if(zl()){if(e=await Rge(),!e)e=l5();if(!e){let t=await t5();e=u5(t)}}return e},zge=()=>{let e=null;if(zl()){if(e=Oge(),!e)e=l5();if(!e){let t=r5();e=u5(t)}}return e};d5.exports={GLIBC:Gi,MUSL:Ia,family:a5,familySync:c5,isNonGlibcLinux:$ge,isNonGlibcLinuxSync:Cge,version:Pge,versionSync:zge}});var m5=Se(function(WZe,p5){var Nge={ALLOW:0,DENY:1};p5.exports=Nge});var g5=Se(function(GZe,h5){var n$={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function Ta(e,t,r){if(new.target!==Ta)return new Ta(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),n$.value=""+e,Object.defineProperty(this,"message",n$),Error.captureStackTrace(this,Ta),this.code=t,this.rawCode=r}Object.setPrototypeOf(Ta,Error);Object.setPrototypeOf(Ta.prototype,Error.prototype);Object.defineProperty(Ta.prototype,"name",n$);h5.exports=Ta});var k5=Se(function(QZe,ib){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Dge,currentTarget:Lge}=M3(),{familySync:y5,GLIBC:Bge,MUSL:jge}=f5();function Uge(){if(process.env.LIBSQL_JS_DEV)return Dge(__dirname);let e=Lge();if(y5()==Bge)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"&&y5()==jge)e="linux-arm-musleabihf";return fr(`@libsql/${e}`)}var{databaseOpen:qge,databaseOpenWithSync:Zge,databaseInTransaction:Mge,databaseInterrupt:Fge,databaseClose:Hge,databaseSyncSync:Kge,databaseSyncUntilSync:Jge,databaseExecSync:Vge,databasePrepareSync:Wge,databaseDefaultSafeIntegers:Gge,databaseAuthorizer:Qge,databaseLoadExtension:Yge,databaseMaxWriteReplicationIndex:Xge,statementRaw:eye,statementIsReader:tye,statementGet:b5,statementRun:S5,statementInterrupt:rye,statementRowsSync:x5,statementColumns:nye,statementSafeIntegers:iye,rowsNext:oye}=Uge(),sye=m5(),w5=g5();function Nl(e){if(e.libsqlError)return new w5(e.message,e.code,e.rawCode);return e}class v5{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=Zge(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=qge(e,o,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 Mge(n)}}})}sync(){return Kge.call(this.db)}syncUntil(e){return Jge.call(this.db,e)}prepare(e){try{let t=Wge.call(this.db,e);return new _5(t)}catch(t){throw Nl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){Qge.call(this.db,e)}loadExtension(...e){Yge.call(this.db,...e)}maxWriteReplicationIndex(){return Xge.call(this.db)}exec(e){try{Vge.call(this.db,e)}catch(t){throw Nl(t)}}interrupt(){Fge.call(this.db)}close(){Hge.call(this.db),this.open=!1}defaultSafeIntegers(e){return Gge.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class _5{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return eye.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return tye.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return S5.call(this.stmt,e[0]);else return S5.call(this.stmt,e.flat())}catch(t){throw Nl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return b5.call(this.stmt,e[0]);else return b5.call(this.stmt,e.flat())}catch(t){throw Nl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=x5.call(this.stmt,e[0]);else t=x5.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)oye.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw Nl(i)}},[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 Nl(t)}}interrupt(){rye.call(this.stmt)}columns(){return nye.call(this.stmt)}safeIntegers(e){return iye.call(this.stmt,e??!0),this}}ib.exports=v5;ib.exports.Authorization=sye;ib.exports.SqliteError=w5});import{Buffer as I5}from"buffer";function T5(e){if(e.scheme!=="file")throw new Be(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Be(`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 ${mi}`,"URL_INVALID");if(t.port!==void 0)throw new Be("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Be("File URL cannot have username and password","URL_INVALID")}let r=q3(e);if(r&&e.syncUrl)throw new Be(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new Df.default(i,n);return Mt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new A5(i,n,o,e.intMode)}class A5{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Mt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Mt(r,ss(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new ar("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Mt(r,s,this.#n))}catch(o){if(o instanceof ar)throw o;if(o instanceof Be)throw new ar(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Mt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Mt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Mt(t,"PRAGMA foreign_keys=off",this.#n),Mt(t,ss("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new ar("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Mt(t,e[i],this.#n))}catch(n){if(n instanceof ar)throw n;if(n instanceof Be)throw new ar(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Mt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n);Mt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Mt(t,ss(e),this.#n),this.#r=null,new $5(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return C5(t,e)}finally{if(t.inTransaction)Mt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 Df.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new Df.default(this.#e,this.#t);return this.#r}}class $5{#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(),Mt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Mt(this.#e,n,this.#t))}catch(i){if(i instanceof ar)throw i;if(i instanceof Be)throw new ar(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),C5(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Mt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Mt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Mt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Be("The transaction is closed","TRANSACTION_CLOSED")}}function Mt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>E5(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=E5(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>aye(p,a,r)),u=0,f=void 0;return new Ol(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new Ol([],[],[],c,l)}}catch(o){throw R5(o)}}function aye(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=cye(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function cye(e,t){if(typeof e==="bigint")if(t==="number"){if(e<lye||e>uye)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 I5)return e.buffer;return e}function E5(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<dye||e>fye)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 I5.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 C5(e,t){try{e.exec(t)}catch(r){throw R5(r)}}function R5(e){if(e instanceof Df.default.SqliteError){let t=e.code,r=pye(e.rawCode);return new Be(e.message,r,t,e.rawCode,e)}return e}function pye(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return mye[t]??`SQLITE_UNKNOWN_${t.toString()}`}var Df,lye,uye=9007199254740991n,dye,fye=9223372036854775807n,mye;var O5=S(()=>{jn();Nf();Pl();Df=pu(k5(),1);jn();lye=-9007199254740991n;dye=-9223372036854775808n;mye={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 cs;var i$=S(()=>{if(typeof WebSocket<"u")cs=WebSocket;else if(typeof global<"u")cs=global.WebSocket;else if(typeof window<"u")cs=window.WebSocket;else if(typeof self<"u")cs=self.WebSocket});class Dl{constructor(){this.intMode="number"}intMode}var st,je,Lf,Ot,Bf,Ll,Aa,Un,xr,yi;var Pt=S(()=>{st=class st extends Error{constructor(e){super(e);this.name="ClientError"}};je=class je extends st{constructor(e){super(e);this.name="ProtoError"}};Lf=class Lf extends st{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};Ot=class Ot extends st{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Bf=class Bf extends st{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};Ll=class Ll extends st{constructor(e){super(e);this.name="WebSocketError"}};Aa=class Aa extends st{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Un=class Un extends st{constructor(e){super(e);this.name="ProtocolVersionError"}};xr=class xr extends st{constructor(e){super(e);this.name="InternalError"}};yi=class yi extends st{constructor(e){super(e);this.name="MisuseError"}}});function Fr(e){if(typeof e==="string")return e;throw Bl(e,"string")}function sn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw Bl(e,"string or null")}function Qi(e){if(typeof e==="number")return e;throw Bl(e,"number")}function ls(e){if(typeof e==="boolean")return e;throw Bl(e,"boolean")}function jf(e){if(Array.isArray(e))return e;throw Bl(e,"array")}function Lt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw Bl(e,"object")}function qn(e,t){return jf(e).map((r)=>t(Lt(r)))}function Bl(e,t){if(e===void 0)return new je(`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 je(`Expected ${t}, received ${r}`)}function $a(e,t){return t(Lt(e))}var jl=S(()=>{Pt()});class P5{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function Uf(e,t){let r=[],i=new P5(r);return i.begin(),t(i,e),i.end(),r.join("")}var Ca=0,qf=1,Zf=2,z5=5;class N5{#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 D5{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new je(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Zf);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return us(this.bytes(),e)}int32(){return this.#r(Ca),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(Ca),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(qf),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===Ca)this.#e.skipVarint();else if(this.#t===qf)this.#e.skip(8);else if(this.#t===Zf){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===z5)this.#e.skip(4);else throw new je(`Unexpected wire type ${this.#t}`);this.#t=-1}}function us(e,t){let r=new N5(e),i=new D5(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var o$=S(()=>{Pt()});class s${#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,Zf),this.#o(t.byteLength),this.#i(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 i=new s$;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,Ca),this.#o(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,Ca),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,qf),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Mf(e,t){let r=new s$;return t(r,e),r.data()}var L5=()=>{};var a$=S(()=>{jl();o$();L5()});class ds{#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 xr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var c$=S(()=>{Pt()});function rt(e,t){throw new xr(t)}var Sn=S(()=>{Pt()});function Ul(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<gye||e>yye)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 l$(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 yi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new je("Received unrecognized type of Value");else throw rt(e,"Impossible type of Value")}var gye,yye=9223372036854775807n;var u$=S(()=>{Pt();Sn();gye=-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 sb(e,t){let r=Ra(e),i=e.rows.map((n)=>B5(r.columnNames,n,t));return{...r,rows:i}}function ab(e,t){let r=Ra(e),i;if(e.rows.length>0)i=B5(r.columnNames,e.rows[0],t);return{...r,row:i}}function cb(e,t){let r=Ra(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=l$(e.rows[0][0],t);return{...r,value:i}}function B5(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=l$(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function Yi(e){return new Lf(e.message,e)}var Ff=S(()=>{Pt();u$()});class Oa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new yi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new Ot("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new st("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 Hf(e,t){if(t instanceof Oa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var ql=S(()=>{Pt()});class fs{#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 Kf{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(Ul(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]=Ul(t),this}bindName(e,t){return this._namedArgs.set(e,Ul(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function lb(e,t,r){let i,n=[],o=[];if(t instanceof Kf){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>Ul(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:Ul(l)}));else i=t;let{sql:s,sqlId:a}=Hf(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var ub=S(()=>{ql();u$()});class db{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new d$(this)}execute(){if(this.#t)throw new yi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Sye(this._stream,this._steps,e);else return bye(this._stream,this._steps,e)}}function bye(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function Sye(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new je("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new je("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,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new je("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new je("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!==o.step)throw new je("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new je("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Yi(a.error);else if(a.type==="none")throw new je("Server produced unrecognized CursorEntry");else throw rt(a,"Impossible CursorEntry")}if(o!==void 0)throw new je("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class d${_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,sb)}queryRow(e){return this.#t(e,!0,ab)}queryValue(e){return this.#t(e,!0,cb)}run(e){return this.#t(e,!1,Ra)}#t(e,t,r){if(this._index!==void 0)throw new yi("This BatchStep has already been added to the batch");let i=lb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new je("Server returned both result and error"));else if(u!==void 0)a(Yi(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class xt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new xt(e._batch,{type:"ok",step:j5(e)})}static error(e){return new xt(e._batch,{type:"error",step:j5(e)})}static not(e){return new xt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)U5(e,r);return new xt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)U5(e,r);return new xt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new xt(e,{type:"is_autocommit"})}}function j5(e){if(e._index===void 0)throw new yi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function U5(e,t){if(t._batch!==e)throw new yi("Cannot mix BatchCond objects for different Batch objects")}var f$=S(()=>{Pt();Ff();ub();Sn()});function q5(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class Zl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,sb)}queryRow(e){return this.#e(e,!0,ab)}queryValue(e){return this.#e(e,!0,cb)}run(e){return this.#e(e,!1,Ra)}#e(e,t,r){let i=lb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new db(this,e)}describe(e){let t=Hf(this._sqlOwner(),e);return this._describe(t).then(q5)}sequence(e){let t=Hf(this._sqlOwner(),e);return this._sequence(t)}intMode}var fb=S(()=>{f$();Ff();ql();ub()});class Jf{}var xye=1000,wye=10,p$;var Z5=S(()=>{Pt();p$=class p$ extends Jf{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new fs,this.#i=new fs,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new Ot("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<wye)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:xye}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new st("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var Vf;var m$=S(()=>{Pt();fb();Z5();Vf=class Vf extends Zl{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new Vf(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new fs,this.#n=void 0,this.#i=!1,this.#o=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 xr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new Ot("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new xr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new Ot("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new Ot("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.#i){this.#l(new st("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new p$(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new st("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Wf(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,M5),e.arrayObjects("named_args",t.namedArgs,vye),e.boolean("want_rows",t.wantRows)}function vye(e,t){e.string("name",t.name),e.object("value",t.value,M5)}function Ml(e,t){e.arrayObjects("steps",t.steps,_ye)}function _ye(e,t){if(t.condition!==void 0)e.object("condition",t.condition,h$);e.object("stmt",t.stmt,Wf)}function h$(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,h$);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,h$);else if(t.type==="is_autocommit");else throw rt(t,"Impossible type of BatchCond")}function M5(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",Rl.fromUint8Array(t));else if(t===void 0);else throw rt(t,"Impossible type of Value")}var g$=S(()=>{rb();Sn()});function F5(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,kye);else throw rt(t,"Impossible type of ClientMsg")}function kye(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,Wf);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Ml);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Ml);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 rt(t,"Impossible type of Request")}var H5=S(()=>{g$();Sn()});function Gf(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,J5);for(let r of t.namedArgs)e.message(4,r,Eye);e.bool(5,t.wantRows)}function Eye(e,t){e.string(1,t.name),e.message(2,t.value,J5)}function Fl(e,t){for(let r of t.steps)e.message(1,r,Iye)}function Iye(e,t){if(t.condition!==void 0)e.message(1,t.condition,y$);e.message(2,t.stmt,Gf)}function y$(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,y$);else if(t.type==="and")e.message(4,t.conds,K5);else if(t.type==="or")e.message(5,t.conds,K5);else if(t.type==="is_autocommit")e.message(6,void 0,V5);else throw rt(t,"Impossible type of BatchCond")}function K5(e,t){for(let r of t)e.message(1,r,y$)}function J5(e,t){if(t===null)e.message(1,void 0,V5);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 rt(t,"Impossible type of Value")}function V5(e,t){}var b$=S(()=>{Sn()});function W5(e,t){if(t.type==="hello")e.message(1,t,Tye);else if(t.type==="request")e.message(2,t,Aye);else throw rt(t,"Impossible type of ClientMsg")}function Tye(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Aye(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,$ye);else if(r.type==="close_stream")e.message(3,r,Cye);else if(r.type==="execute")e.message(4,r,Rye);else if(r.type==="batch")e.message(5,r,Oye);else if(r.type==="open_cursor")e.message(6,r,Pye);else if(r.type==="close_cursor")e.message(7,r,zye);else if(r.type==="fetch_cursor")e.message(8,r,Nye);else if(r.type==="sequence")e.message(9,r,Dye);else if(r.type==="describe")e.message(10,r,Lye);else if(r.type==="store_sql")e.message(11,r,Bye);else if(r.type==="close_sql")e.message(12,r,jye);else if(r.type==="get_autocommit")e.message(13,r,Uye);else throw rt(r,"Impossible type of Request")}function $ye(e,t){e.int32(1,t.streamId)}function Cye(e,t){e.int32(1,t.streamId)}function Rye(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Gf)}function Oye(e,t){e.int32(1,t.streamId),e.message(2,t.batch,Fl)}function Pye(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,Fl)}function zye(e,t){e.int32(1,t.cursorId)}function Nye(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Dye(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 Lye(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 Bye(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function jye(e,t){e.int32(1,t.sqlId)}function Uye(e,t){e.int32(1,t.streamId)}var G5=S(()=>{b$();Sn()});function ps(e){let t=Fr(e.message),r=sn(e.code);return{message:t,code:r}}function Qf(e){let t=qn(e.cols,Q5),r=jf(e.rows).map((s)=>qn(s,Y5)),i=Qi(e.affected_row_count),n=sn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function Q5(e){let t=sn(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function pb(e){let t=new Map;jf(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,Qf(Lt(i)))});let r=new Map;return jf(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,ps(Lt(i)))}),{stepResults:t,stepErrors:r}}function mb(e){let t=Fr(e.type);if(t==="step_begin"){let r=Qi(e.step),i=qn(e.cols,Q5);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=Qi(e.affected_row_count),i=sn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Qi(e.step),i=ps(Lt(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:qn(e.row,Y5)};else if(t==="error")return{type:"error",error:ps(Lt(e.error))};else throw new je("Unexpected type of CursorEntry")}function hb(e){let t=qn(e.params,qye),r=qn(e.cols,Zye),i=ls(e.is_explain),n=ls(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function qye(e){return{name:sn(e.name)}}function Zye(e){let t=Fr(e.name),r=sn(e.decltype);return{name:t,decltype:r}}function Y5(e){let t=Fr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Fr(e.value);return BigInt(r)}else if(t==="float")return Qi(e.value);else if(t==="text")return Fr(e.value);else if(t==="blob")return Rl.toUint8Array(Fr(e.base64));else throw new je("Unexpected type of Value")}var gb=S(()=>{rb();Pt();jl()});function X5(e){let t=Fr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ps(Lt(e.error))};else if(t==="response_ok"){let r=Qi(e.request_id),i=Mye(Lt(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=Qi(e.request_id),i=ps(Lt(e.error));return{type:"response_error",requestId:r,error:i}}else throw new je("Unexpected type of ServerMsg")}function Mye(e){let t=Fr(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:Qf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:pb(Lt(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=qn(e.entries,mb),i=ls(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:hb(Lt(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:ls(e.is_autocommit)};else throw new je("Unexpected type of Response")}var e8=S(()=>{Pt();jl();gb()});var xn,ms,t8,r8,Hl,Fye,Hye,yb,Kye,Jye,Vye,Kl,Wye,Gye,Qye;var bb=S(()=>{xn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ms={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(t8))},2(e,t){t.rows.push(e.message(r8))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},t8={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},r8={default(){return[]},1(e,t){t.push(e.message(Qye))}},Hl={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(Fye);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(Hye);t.stepErrors.set(r,i)}},Fye={default(){return[0,ms.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ms)}},Hye={default(){return[0,xn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(xn)}},yb={default(){return{type:"none"}},1(e){return e.message(Kye)},2(e){return e.message(Jye)},3(e){return e.message(Vye)},4(e){return{type:"row",row:e.message(r8)}},5(e){return{type:"error",error:e.message(xn)}}},Kye={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(t8))}},Jye={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Vye={default(){return{type:"step_error",step:0,error:xn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(xn)}},Kl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Wye))},2(e,t){t.cols.push(e.message(Gye))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Wye={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Gye={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Qye={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 n8,Yye,Xye,ebe,tbe,rbe,nbe,ibe,obe;var i8=S(()=>{bb();n8={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Yye)},3(e){return e.message(ebe)},4(e){return e.message(Xye)}},Yye={default(){return{type:"hello_error",error:xn.default()}},1(e,t){t.error=e.message(xn)}},Xye={default(){return{type:"response_error",requestId:0,error:xn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(xn)}},ebe={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(tbe)},5(e,t){t.response=e.message(rbe)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(nbe)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(ibe)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(obe)}},tbe={default(){return{type:"execute",result:ms.default()}},1(e,t){t.result=e.message(ms)}},rbe={default(){return{type:"batch",result:Hl.default()}},1(e,t){t.result=e.message(Hl)}},nbe={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(yb))},2(e,t){t.done=e.bool()}},ibe={default(){return{type:"describe",result:Kl.default()}},1(e,t){t.result=e.message(Kl)}},obe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var o8,S$,Sb;var xb=S(()=>{a$();Pt();c$();Ff();ql();Sn();m$();H5();G5();e8();i8();o8=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),S$=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Sb=class Sb extends Dl{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new ds,this._streamIdAlloc=new ds,this._cursorIdAlloc=new ds,this.#l=new ds,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 xr("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 st("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.#o={version:1,encoding:"json"};else if(this.#o=S$.get(e),this.#o===void 0){this.#u(new je(`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.#o.encoding;if(t==="json"){let r=Uf(e,F5);this.#e.send(r)}else if(t==="protobuf"){let r=Mf(e,W5);this.#e.send(r)}else throw rt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Un(`${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.#o.version<e)throw new Un(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new Ot("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 Ll(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new Ll(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new je("Received non-text message from server with JSON encoding"));return}t=$a(JSON.parse(e.data),X5)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new je("Received non-binary message from server with Protobuf encoding"));return}t=us(new Uint8Array(e.data),n8)}else throw rt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new je("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new je("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw Yi(e.error);return}else if(!this.#i)throw new je("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 je("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new je("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 je("Received unexpected error response");this.#c.free(t),r.errorCallback(Yi(e.error))}else throw rt(e,"Impossible ServerMsg type")}openStream(){return Vf.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Oa(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new st("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Pa;var s8=S(()=>{if(typeof queueMicrotask<"u")Pa=queueMicrotask;else{let e=Promise.resolve();Pa=(t)=>{e.then(t)}}});class x${#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function a8(e){let t=sn(e.baton),r=sn(e.base_url),i=qn(e.results,sbe);return{baton:t,baseUrl:r,results:i}}function sbe(e){let t=Fr(e.type);if(t==="ok")return{type:"ok",response:abe(Lt(e.response))};else if(t==="error")return{type:"error",error:ps(Lt(e.error))};else throw new je("Unexpected type of StreamResult")}function abe(e){let t=Fr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Qf(Lt(e.result))};else if(t==="batch")return{type:"batch",result:pb(Lt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:hb(Lt(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:ls(e.is_autocommit)};else throw new je("Unexpected type of StreamResponse")}function c8(e){let t=sn(e.baton),r=sn(e.base_url);return{baton:t,baseUrl:r}}var w$=S(()=>{Pt();jl();gb()});var l8,cbe,lbe,ube,dbe,fbe,pbe,u8;var v$=S(()=>{bb();l8={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(cbe))}},cbe={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(lbe)}},2(e){return{type:"error",error:e.message(xn)}}},lbe={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(ube)},3(e){return e.message(dbe)},4(e){return{type:"sequence"}},5(e){return e.message(fbe)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(pbe)}},ube={default(){return{type:"execute",result:ms.default()}},1(e,t){t.result=e.message(ms)}},dbe={default(){return{type:"batch",result:Hl.default()}},1(e,t){t.result=e.message(Hl)}},fbe={default(){return{type:"describe",result:Kl.default()}},1(e,t){t.result=e.message(Kl)}},pbe={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},u8={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var _$;var d8=S(()=>{jl();o$();Pt();Sn();w$();v$();gb();bb();_$=class _$ extends Jf{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new x$(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new je("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(c8,u8);if(t===void 0)throw new je("Empty response to cursor request");return t}next(){return this.#a(mb,yb)}close(){this._setClosed(new st("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new Ot("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return $a(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return us(n,t)}else throw rt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new xr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new je("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function f8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,mbe)}function mbe(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Wf);else if(t.type==="batch")e.object("batch",t.batch,Ml);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 rt(t,"Impossible type of StreamRequest")}function p8(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Ml)}var k$=S(()=>{g$();Sn()});function m8(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,hbe)}function hbe(e,t){if(t.type==="close")e.message(1,t,gbe);else if(t.type==="execute")e.message(2,t,ybe);else if(t.type==="batch")e.message(3,t,bbe);else if(t.type==="sequence")e.message(4,t,Sbe);else if(t.type==="describe")e.message(5,t,xbe);else if(t.type==="store_sql")e.message(6,t,wbe);else if(t.type==="close_sql")e.message(7,t,vbe);else if(t.type==="get_autocommit")e.message(8,t,_be);else throw rt(t,"Impossible type of StreamRequest")}function gbe(e,t){}function ybe(e,t){e.message(1,t.stmt,Gf)}function bbe(e,t){e.message(1,t.batch,Fl)}function Sbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function xbe(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function wbe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function vbe(e,t){e.int32(1,t.sqlId)}function _be(e,t){}function h8(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,Fl)}var E$=S(()=>{b$();Sn()});function kbe(e,t){if(t.results.length!==e.length)throw new je("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new je("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(Yi(i.error));else if(i.type==="none")throw new je("Received unrecognized type of StreamResult");else throw rt(i,"Received impossible type of StreamResult")}}async function Ebe(e,t){if(t==="json"){let r=await e.json();return $a(r,a8)}if(t==="protobuf"){let r=await e.arrayBuffer();return us(new Uint8Array(r),l8)}throw await e.body?.cancel(),rt(t,"Impossible encoding")}async function Ibe(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return Yi(i);return new Aa(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new Aa(r,e.status)}return await e.body?.cancel(),new Aa(r,e.status)}var wb;var I$=S(()=>{Pt();a$();c$();s8();Ff();ql();fb();Sn();d8();k$();E$();k$();E$();w$();v$();wb=class wb extends Zl{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new fs,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new ds}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 Oa(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 xr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Pa(()=>this.#u())}close(){this._setClosed(new st("Stream was manually closed"))}closeGracefully(){this.#l=!0,Pa(()=>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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Pa(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new Ot("Stream is closed",this.#f);else if(this.#l)throw new Ot("Stream is closing",void 0);else this.#a.push(e),Pa(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new st("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw rt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#S(t,e),(r)=>Ebe(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>kbe(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new _$(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){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 Ibe(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#x(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,f8,m8)}#w(e,t){if(t.cursorPath===void 0)throw new Un(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#x(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,p8,h8)}#x(e,t,r,i,n){let o,s;if(r==="json")o=Uf(t,i),s="application/json";else if(r==="protobuf")o=Mf(t,n),s="application/x-protobuf";else throw rt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function Abe(e,t){let r=e;for(let i of Tbe){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return T$}var Tbe,T$,vb;var A$=S(()=>{Pt();I$();Tbe=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],T$={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};vb=class vb extends Dl{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=Abe(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(T$),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=T$.version)return;else if(this._endpoint===void 0)throw new Un(`${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 Un(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new Ot("Client is closed",this.#i);let e=new wb(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new st("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new Ot("Client was closed",e))}}});var g8=S(()=>{Pt()});function $$(e,t,r=2){if(typeof cs>"u")throw new Bf("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(S$.keys());else i=Array.from(o8.keys());let n=new cs(e,i);return new Sb(n,t)}function C$(e,t,r,i,n=2){return new vb(e instanceof URL?e:new URL(e),t,r,i,n)}var _b=S(()=>{i$();xb();Pt();A$();xb();i$();f$();g8();ql();ub();fb();A$();I$();xb();m$();Pt()});class Yf{#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 Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Xi),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(ss(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(xt.ok(c));if(this.#t>=3)u.condition(xt.not(xt.isAutocommit(o)));let f=u.query(l);return f.catch(()=>{return}),c=u,f}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(xt.ok(s));if(this.#t>=3)c.condition(xt.not(xt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new ar("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(Vl(s))}catch(s){if(s instanceof ar)throw s;let a=yt(s);if(a instanceof Be)throw new ar(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Be("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(ss(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Be("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function Jl(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(ss(e)),a=o,c=i.map((m)=>{let y=r.step().condition(xt.ok(a));if(t>=3)y.condition(xt.not(xt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(xt.ok(a));if(t>=3)l.condition(xt.not(xt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(xt.not(xt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new ar("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(Vl(y))}catch(y){if(y instanceof ar)throw y;let g=yt(y);if(g instanceof Be)throw new ar(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function Xi(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 i=new Kf(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function Vl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new Ol(t,r,i,n,o)}function yt(e){if(e instanceof st){let t=y8(e);return new Be(e.message,t,void 0,void 0,e)}return e}function y8(e){if(e instanceof Lf&&e.code!==void 0)return e.code;else if(e instanceof je)return"HRANA_PROTO_ERROR";else if(e instanceof Ot)return e.cause instanceof st?y8(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof Ll)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof Aa)return"SERVER_ERROR";else if(e instanceof Un)return"PROTOCOL_VERSION_ERROR";else if(e instanceof xr)return"INTERNAL_ERROR";else return"UNKNOWN"}var O$=S(()=>{_b();jn();Pl()});class Wl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new b8,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class b8{#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 P$=Se(function(Q3e,x8){function $be(e){var t=0,r=[];function i(){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 o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function Cbe(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function S8(e){return e.queue=0,e.map=Cbe,e}x8.exports=function(e){if(e)return S8($be(e));else return S8(function(t){return t()})}});function _8(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Be(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Be('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Be('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Of(e.scheme,e.authority,e.path),r;try{r=$$(t,e.authToken)}catch(i){if(i instanceof Bf){let n=e.scheme==="wss"?"https":"http",o=Of(n,e.authority,e.path);throw new Be(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${mi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new k8(r,t,e.authToken,e.intMode,e.concurrency)}class k8{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=v8.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 i=await this.#s();try{let n=Xi(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return Vl(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Xi),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await Jl(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Xi),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await Jl("deferred",i,n,r,!0)}catch(r){throw yt(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 E8(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Be("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Be("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Rbe&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=w8}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=$$(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Wl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=w8;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var v8,Rbe=60000,w8=100,E8;var I8=S(()=>{_b();jn();Nf();O$();Xy();Pl();v8=pu(P$(),1);jn();E8=class E8 extends Yf{#e;#t;constructor(e,t,r,i){super(r,i);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 A8(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Be(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${mi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Be("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Be('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Be('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=Of(e.scheme,e.authority,e.path);return new C8(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class C8{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=C$(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=T8.default(this.#i)}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 i=Xi(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return Vl(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(Xi),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new Wl(s,$8).apply(i);let l=s.batch(!1);o=Jl(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Xi),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=Jl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new R8(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Be("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=C$(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var T8,$8=30,R8;var O8=S(()=>{_b();jn();Nf();O$();Xy();Pl();T8=pu(P$(),1);jn();R8=class R8 extends Yf{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Wl(e,$8)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Gl(e){return Obe(zf(e,!0))}function Obe(e){if(e.scheme==="wss"||e.scheme==="ws")return _8(e);else if(e.scheme==="https"||e.scheme==="http")return A8(e);else return T5(e)}var z$=S(()=>{Nf();O5();I8();O8();jn()});function ae(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,J))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(J in r&&r[J]===t[J])return!0;r=Object.getPrototypeOf(r)}return!1}var J;var ze=S(()=>{J=Symbol.for("drizzle:entityKind")});var nt;var Zn=S(()=>{ze();nt=class nt{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[J]="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 Xf;var kb=S(()=>{ze();Xf=class Xf{static[J]="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 wr;var Ql=S(()=>{wr=Symbol.for("drizzle:Name")});var N$,P8;var z8=S(()=>{ze();Ql();N$=class N${static[J]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 P8(e,this)}};P8=class P8{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function Eb(e,...t){return e(...t)}var D$=()=>{};function L$(e,t){return`${e[wr]}_${t.join("_")}_unique`}var N8,Pbe,D8;var L8=S(()=>{ze();Ql();N8=class N8{constructor(e,t){this.name=t,this.columns=e}static[J]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new D8(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Pbe=class Pbe{static[J]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new N8(e,this.name)}};D8=class D8{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??L$(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[J]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function B8(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function j8(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=B8(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=j8(e,i+1);r.push(c),i=l;continue}let[s,a]=B8(e,i,!1);r.push(s),i=a}return[r,i]}function U8(e){let[t]=j8(e,1);return t}function B$(e){return`{${e.map((t)=>{if(Array.isArray(t))return B$(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var q8=()=>{};var ep,Yl,Z8,zbe,M8,j$;var F8=S(()=>{kb();Zn();ze();z8();D$();L8();q8();ep=class ep extends Xf{foreignKeyConfigs=[];static[J]="PgColumnBuilder";array(e){return new M8(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:i})=>Eb((n,o)=>{let s=new N$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new Z8(e,this.config)}};Yl=class Yl extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=L$(e,[t.name]);super(e,t);this.table=e}static[J]="PgColumn"};Z8=class Z8 extends Yl{static[J]="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}};zbe=class zbe{static[J]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};M8=class M8 extends ep{static[J]="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 j$(e,this.config,t)}};j$=class j$ extends Yl{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[J]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=U8(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ae(this.baseColumn,j$)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return B$(r)}}});function J8(e){return!!e&&typeof e==="function"&&H8 in e&&e[H8]===!0}var Nbe,K8,H8,Dbe,V8;var W8=S(()=>{ze();F8();Nbe=class Nbe extends ep{static[J]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new K8(e,this.config)}};K8=class K8 extends Yl{static[J]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};H8=Symbol.for("drizzle:isPgEnum");Dbe=class Dbe extends ep{static[J]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new V8(e,this.config)}};V8=class V8 extends Yl{static[J]="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 wt,tp;var Mn=S(()=>{ze();wt=class wt{static[J]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};tp=class tp extends wt{static[J]="WithSubquery"}});var G8="0.45.2";var Q8=()=>{};var U$,q$,Y8;var X8=S(()=>{D$();Q8();Y8={startActiveSpan(e,t){if(!U$)return t();if(!q$)q$=U$.trace.getTracer("drizzle-orm",G8);return Eb((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),U$,q$)}}});var vt;var eo=S(()=>{vt=Symbol.for("drizzle:ViewBaseConfig")});function hs(e){return e[wr]}function za(e){return`${e[Ib]??"public"}.${e[wr]}`}var Ib,Tb,eH,Z$,M$,rp,tH,Lbe,we;var vr=S(()=>{ze();Ql();Ib=Symbol.for("drizzle:Schema"),Tb=Symbol.for("drizzle:Columns"),eH=Symbol.for("drizzle:ExtraConfigColumns"),Z$=Symbol.for("drizzle:OriginalName"),M$=Symbol.for("drizzle:BaseName"),rp=Symbol.for("drizzle:IsAlias"),tH=Symbol.for("drizzle:ExtraConfigBuilder"),Lbe=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[J]="Table";static Symbol={Name:wr,Schema:Ib,OriginalName:Z$,Columns:Tb,ExtraConfigColumns:eH,BaseName:M$,IsAlias:rp,ExtraConfigBuilder:tH};[wr];[Z$];[Ib];[Tb];[eH];[M$];[rp]=!1;[Lbe]=!0;[tH]=void 0;constructor(e,t,r){this[wr]=this[Z$]=e,this[Ib]=t,this[M$]=r}}});function F$(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function jbe(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 rH(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function U(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Ft(e[0]));for(let[i,n]of t.entries())r.push(n,new Ft(e[i+1]));return new Te(r)}function np(e,t){return e.map((r)=>{if(ae(r,gs)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ae(r,an)&&ae(r.value,gs)){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 Bbe,Ft,Te,Ab,nH,iH,c8e,an,gs,Ube,wn;var lr=S(()=>{ze();W8();Mn();X8();eo();Zn();vr();Bbe=class Bbe{static[J]="FakePrimitiveParam"};Ft=class Ft{static[J]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Te([this])}};Te=class Te{constructor(e){this.queryChunks=e;for(let t of e)if(ae(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[J]="SQL";decoder=nH;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return Y8.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return jbe(e.map((l)=>{if(ae(l,Ft))return{sql:l.value.join(""),params:[]};if(ae(l,Ab))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Ft("(")];for(let[f,p]of l.entries())if(u.push(p),f<l.length-1)u.push(new Ft(", "));return u.push(new Ft(")")),this.buildQueryFromSourceParams(u,r)}if(ae(l,Te))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ae(l,we)){let u=l[we.Symbol.Schema],f=l[we.Symbol.Name];return{sql:u===void 0||l[rp]?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,nt)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let f=l.table[we.Symbol.Schema];return{sql:l.table[rp]||f===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(f)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ae(l,wn)){let u=l[vt].schema,f=l[vt].name;return{sql:u===void 0||l[vt].isAlias?n(f):n(u)+"."+n(f),params:[]}}if(ae(l,an)){if(ae(l.value,gs))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ae(u,Te))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let f=["none"];if(s)f=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:f}}if(ae(l,gs))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ae(l,Te.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ae(l,wt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Ft("("),l._.sql,new Ft(") "),new Ab(l._.alias)],r)}if(J8(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(F$(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Ft("("),l.getSQL(),new Ft(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 Te.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}};Ab=class Ab{constructor(e){this.value=e}static[J]="Name";brand;getSQL(){return new Te([this])}};nH={mapFromDriverValue:(e)=>e},iH={mapToDriverValue:(e)=>e},c8e={...nH,...iH};an=class an{constructor(e,t=iH){this.value=e,this.encoder=t}static[J]="Param";brand;getSQL(){return new Te([this])}};((e)=>{function t(){return new Te([])}e.empty=t;function r(c){return new Te(c)}e.fromList=r;function i(c){return new Te([new Ft(c)])}e.raw=i;function n(c,l){let u=[];for(let[f,p]of c.entries()){if(f>0&&l!==void 0)u.push(l);u.push(p)}return new Te(u)}e.join=n;function o(c){return new Ab(c)}e.identifier=o;function s(c){return new gs(c)}e.placeholder=s;function a(c,l){return new an(c,l)}e.param=a})(U||(U={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[J]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Te||(Te={}));gs=class gs{constructor(e){this.name=e}static[J]="Placeholder";getSQL(){return new Te([this])}};Ube=Symbol.for("drizzle:IsDrizzleView");wn=class wn{static[J]="View";[vt];[Ube]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[vt]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new Te([this])}};nt.prototype.getSQL=function(){return new Te([this])};we.prototype.getSQL=function(){return new Te([this])};wt.prototype.getSQL=function(){return new Te([this])}});function H$(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ae(a,nt))l=a;else if(ae(a,Te))l=a.decoder;else if(ae(a,wt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[f,p]of s.entries())if(f<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ae(a,nt)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?hs(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==hs(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function vn(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ae(n,nt)||ae(n,Te)||ae(n,Te.Aliased)||ae(n,wt))r.push({path:o,field:n});else if(ae(n,we))r.push(...vn(n[we.Symbol.Columns],o));else r.push(...vn(n,o));return r},[])}function ip(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function $b(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ae(n,Te)||ae(n,nt))return[i,n];else return[i,new an(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function oH(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function Cb(e){return e[we.Symbol.Columns]}function op(e){return ae(e,wt)?e._.alias:ae(e,wn)?e[vt].name:ae(e,Te)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function bi(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function sH(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 K$;var Dr=S(()=>{Zn();ze();lr();Mn();vr();eo();K$=typeof TextDecoder>"u"?null:new TextDecoder});var aH,J$,V$;var Rb=S(()=>{ze();aH=class aH{static[J]="ConsoleLogWriter";write(e){console.log(e)}};J$=class J${static[J]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new aH}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};V$=class V${static[J]="NoopLogger";logQuery(){}}});var cH,lH,W$;var uH=S(()=>{ze();vr();cH=Symbol.for("drizzle:PgInlineForeignKeys"),lH=Symbol.for("drizzle:EnableRLS");W$=class W$ extends we{static[J]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:cH,EnableRLS:lH});[cH]=[];[lH]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var G$,dH;var fH=S(()=>{ze();uH();G$=class G${static[J]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new dH(e,this.columns,this.name)}};dH=class dH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[W$.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Hr(e,t){if(rH(t)&&!F$(e)&&!ae(e,an)&&!ae(e,gs)&&!ae(e,nt)&&!ae(e,we)&&!ae(e,wn))return new an(e,t);return e}function Et(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" and ")),new Ft(")")])}function Si(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Te(t);return new Te([new Ft("("),U.join(t,new Ft(" or ")),new Ft(")")])}function mH(e){return U`not ${e}`}function ys(e,t){if(Array.isArray(t)){if(t.length===0)return U`false`;return U`${e} in ${t.map((r)=>Hr(r,e))}`}return U`${e} in ${Hr(t,e)}`}function Ob(e,t){if(Array.isArray(t)){if(t.length===0)return U`true`;return U`${e} not in ${t.map((r)=>Hr(r,e))}`}return U`${e} not in ${Hr(t,e)}`}function _n(e){return U`${e} is null`}function yH(e){return U`${e} is not null`}function Pb(e){return U`exists ${e}`}function ap(e){return U`not exists ${e}`}function bH(e,t,r){return U`${e} between ${Hr(t,e)} and ${Hr(r,e)}`}function SH(e,t,r){return U`${e} not between ${Hr(t,e)} and ${Hr(r,e)}`}function xH(e,t){return U`${e} like ${t}`}function wH(e,t){return U`${e} not like ${t}`}function vH(e,t){return U`${e} ilike ${t}`}function _H(e,t){return U`${e} not ilike ${t}`}var Qe=(e,t)=>U`${e} = ${Hr(t,e)}`,pH=(e,t)=>U`${e} <> ${Hr(t,e)}`,sp=(e,t)=>U`${e} > ${Hr(t,e)}`,hH=(e,t)=>U`${e} >= ${Hr(t,e)}`,gH=(e,t)=>U`${e} < ${Hr(t,e)}`,Xl=(e,t)=>U`${e} <= ${Hr(t,e)}`;var kH=S(()=>{Zn();ze();vr();lr()});function to(e){return U`${e} asc`}function Na(e){return U`${e} desc`}var EH=S(()=>{lr()});var Q$=S(()=>{kH();EH()});function TH(){return{and:Et,between:bH,eq:Qe,exists:Pb,gt:sp,gte:hH,ilike:vH,inArray:ys,isNull:_n,isNotNull:yH,like:xH,lt:gH,lte:Xl,ne:pH,not:mH,notBetween:SH,notExists:ap,notLike:wH,notIlike:_H,notInArray:Ob,or:Si,sql:U}}function AH(){return{sql:U,asc:to,desc:Na}}function $H(e,t){if(Object.keys(e).length===1&&"default"in e&&!ae(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ae(s,we)){let a=za(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ae(u,G$))n[o].primaryKey.push(...u.columns)}}else if(ae(s,IH)){let a=za(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[f,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[f]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[f]=p}}return{tables:n,tableNamesMap:r}}function qbe(e){return function(r,i){return new bs(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function Zbe(e){return function(r,i){return new cp(e,r,i)}}function CH(e,t,r){if(ae(r,bs)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[za(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[za(o)];if(!s)throw Error(`Table "${o[we.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 "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ae(a[0],bs)&&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 RH(e){return{one:qbe(e),many:Zbe(e)}}function zb(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ae(c,bs)?u&&zb(e,e[a.relationTableTsKey],u,a.selection,n):u.map((f)=>zb(e,e[a.relationTableTsKey],f,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ae(l,nt))u=l;else if(ae(l,Te))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var Y$,IH,bs,cp;var lp=S(()=>{vr();Zn();ze();fH();Q$();lr();Y$=class Y${constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[J]="Relation";referencedTableName;fieldName};IH=class IH{constructor(e,t){this.table=e,this.config=t}static[J]="Relations"};bs=class bs extends Y${constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[J]="One";withFieldName(e){let t=new bs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};cp=class cp extends Y${constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[J]="Many";withFieldName(e){let t=new cp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function up(e,t){return new Proxy(e,new Da(t,!1))}function xi(e,t){return new Proxy(e,new eu(new Proxy(e.table,new Da(t,!1))))}function X$(e,t){return new Te.Aliased(dp(e.sql,t),e.fieldAlias)}function dp(e,t){return U.join(e.queryChunks.map((r)=>{if(ae(r,nt))return xi(r,t);if(ae(r,Te))return dp(r,t);if(ae(r,Te.Aliased))return X$(r,t);return r}))}var eu,Da,Mbe;var fp=S(()=>{Zn();ze();lr();vr();eo();eu=class eu{constructor(e){this.table=e}static[J]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Da=class Da{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[J]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===vt)return{...e[vt],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new eu(new Proxy(e,this)))}),n}let r=e[t];if(ae(r,nt))return new Proxy(r,new eu(new Proxy(e,this)));return r}};Mbe=class Mbe{constructor(e){this.alias=e}static[J]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return up(e.sourceTable,this.alias);return e[t]}}});var bt;var La=S(()=>{fp();Zn();ze();lr();Mn();eo();bt=class bt{static[J]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===vt)return{...e[vt],selectedFields:new Proxy(e[vt].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ae(e,wt)?e._.selectedFields:ae(e,wn)?e[vt].selectedFields:e)[t];if(ae(i,Te.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ae(i,Te)){if(this.config.sqlBehavior==="sql")return i;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(ae(i,nt)){if(this.config.alias)return new Proxy(i,new eu(new Proxy(i.table,new Da(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Lr;var ro=S(()=>{ze();Lr=class Lr{static[J]="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 eC,OH;var tC=S(()=>{ze();Ql();eC=class eC{static[J]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 OH(e,this)}};OH=class OH{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[J]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[wr],...i,r[0].table[wr],...n];return e??`${o.join("_")}_fk`}}});function rC(e,t){return`${e[wr]}_${t.join("_")}_unique`}var PH,Fbe,zH;var nC=S(()=>{ze();Ql();PH=class PH{constructor(e,t){this.name=t,this.columns=e}static[J]="SQLiteUniqueConstraintBuilder";columns;build(e){return new zH(e,this.columns,this.name)}};Fbe=class Fbe{static[J]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new PH(e,this.name)}};zH=class zH{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??rC(this.table,this.columns.map((i)=>i.name))}static[J]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Gt,It;var Ss=S(()=>{kb();Zn();ze();tC();nC();Gt=class Gt extends Xf{static[J]="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:i})=>((n,o)=>{let s=new eC(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};It=class It extends nt{constructor(e,t){if(!t.uniqueName)t.uniqueName=rC(e,[t.name]);super(e,t);this.table=e}static[J]="SQLiteColumn"}});function qH(e,t){let{name:r,config:i}=bi(e,t);if(i?.mode==="json")return new LH(r);if(i?.mode==="bigint")return new NH(r);return new jH(r)}var NH,DH,LH,BH,jH,UH;var iC=S(()=>{ze();Dr();Ss();NH=class NH extends Gt{static[J]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new DH(e,this.config)}};DH=class DH extends It{static[J]="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(K$.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};LH=class LH extends Gt{static[J]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new BH(e,this.config)}};BH=class BH extends It{static[J]="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(K$.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};jH=class jH extends Gt{static[J]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new UH(e,this.config)}};UH=class UH extends It{static[J]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function FH(e){return(t,r)=>{let{name:i,config:n}=bi(t,r);return new ZH(i,n,e)}}var ZH,MH;var oC=S(()=>{ze();Dr();Ss();ZH=class ZH extends Gt{static[J]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new MH(e,this.config)}};MH=class MH extends It{static[J]="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 _r(e,t){let{name:r,config:i}=bi(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new JH(r,i.mode);if(i?.mode==="boolean")return new WH(r,i.mode);return new HH(r)}var Nb,Db,HH,KH,JH,VH,WH,GH;var sC=S(()=>{ze();lr();Dr();Ss();Nb=class Nb extends Gt{static[J]="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()}};Db=class Db extends It{static[J]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};HH=class HH extends Nb{static[J]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new KH(e,this.config)}};KH=class KH extends Db{static[J]="SQLiteInteger"};JH=class JH extends Nb{static[J]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(U`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new VH(e,this.config)}};VH=class VH extends Db{static[J]="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}};WH=class WH extends Nb{static[J]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new GH(e,this.config)}};GH=class GH extends Db{static[J]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function nK(e,t){let{name:r,config:i}=bi(e,t),n=i?.mode;return n==="number"?new XH(r):n==="bigint"?new tK(r):new QH(r)}var QH,YH,XH,eK,tK,rK;var aC=S(()=>{ze();Dr();Ss();QH=class QH extends Gt{static[J]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new YH(e,this.config)}};YH=class YH extends It{static[J]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};XH=class XH extends Gt{static[J]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new eK(e,this.config)}};eK=class eK extends It{static[J]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};tK=class tK extends Gt{static[J]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new rK(e,this.config)}};rK=class rK extends It{static[J]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function sK(e){return new iK(e??"")}var iK,oK;var cC=S(()=>{ze();Ss();iK=class iK extends Gt{static[J]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new oK(e,this.config)}};oK=class oK extends It{static[J]="SQLiteReal";getSQLType(){return"real"}}});function ur(e,t={}){let{name:r,config:i}=bi(e,t);if(i.mode==="json")return new lK(r);return new aK(r,i)}var aK,cK,lK,uK;var lC=S(()=>{ze();Dr();Ss();aK=class aK extends Gt{static[J]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new cK(e,this.config)}};cK=class cK extends It{static[J]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};lK=class lK extends Gt{static[J]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new uK(e,this.config)}};uK=class uK extends It{static[J]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function dK(){return{blob:qH,customType:FH,integer:_r,numeric:nK,real:sK,text:ur}}var fK=S(()=>{iC();oC();sC();aC();cC();lC()});function Hbe(e,t,r,i,n=e){let o=new Bt(e,i,n),s=typeof t==="function"?t(dK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let f=u;f.setName(l);let p=f.build(o);return o[uC].push(...f.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Bt.Symbol.ExtraConfigBuilder]=r;return c}var uC,Bt,pp=(e,t,r)=>Hbe(e,t,r);var no=S(()=>{ze();vr();fK();uC=Symbol.for("drizzle:SQLiteInlineForeignKeys");Bt=class Bt extends we{static[J]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:uC});[we.Symbol.Columns];[uC]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var Kbe,pK;var mK=S(()=>{ze();Kbe=class Kbe{constructor(e,t){this.name=e,this.value=t}static[J]="SQLiteCheckBuilder";brand;build(e){return new pK(e,this)}};pK=class pK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[J]="SQLiteCheck";name;value}});function io(e){return new hK(e,!1)}var hK,gK,yK;var bK=S(()=>{ze();hK=class hK{constructor(e,t){this.name=e,this.unique=t}static[J]="SQLiteIndexBuilderOn";on(...e){return new gK(this.name,e,this.unique)}};gK=class gK{static[J]="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 yK(this.config,e)}};yK=class yK{static[J]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Jbe,SK;var xK=S(()=>{ze();no();Jbe=class Jbe{static[J]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new SK(e,this.columns,this.name)}};SK=class SK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[J]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Bt.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Fn(e){if(ae(e,Bt))return[`${e[we.Symbol.BaseName]}`];if(ae(e,wt))return e._.usedTables??[];if(ae(e,Te))return e.usedTables??[];return[]}var tu=S(()=>{ze();lr();Mn();vr();no()});var Lb;var wK=S(()=>{ze();ro();La();no();vr();Dr();tu();Lb=class Lb extends Lr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[J]="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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=vn(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:Fn(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 Vbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Wbe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function Gbe(e){return e}var dC;var vK=S(()=>{ze();vr();dC=class dC{static[J]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Vbe:e==="camelCase"?Wbe:Gbe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var ru,oo,fC;var Bb=S(()=>{ze();ru=class ru extends Error{static[J]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};oo=class oo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
398
398
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,oo),r)this.cause=r}};fC=class fC extends ru{static[J]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var _K=()=>{};var kK=()=>{};var EK=S(()=>{_K();kK()});var pC=S(()=>{Q$();EK();lr()});var mC=S(()=>{iC();Ss();oC();sC();aC();cC();lC()});var so;var mp=S(()=>{ze();lr();so=class so extends wn{static[J]="SQLiteViewBase"}});var nu,hC,gC;var jb=S(()=>{fp();vK();Zn();ze();Bb();lp();pC();lr();mC();no();Mn();vr();Dr();eo();mp();nu=class nu{static[J]="SQLiteDialect";casing;constructor(e){this.casing=new dC(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=[U`with `];for(let[r,i]of e.entries())if(t.push(U`${U.identifier(i._.alias)} as (${i._.sql})`),r<e.length-1)t.push(U`, `);return t.push(U` `),U.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:i,limit:n,orderBy:o}){let s=this.buildWithCTE(i),a=r?U` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?U` where ${t}`:void 0,l=this.buildOrderBy(o),u=this.buildLimit(n);return U`${s}delete from ${e}${c}${a}${l}${u}`}buildUpdateSet(e,t){let r=e[we.Symbol.Columns],i=Object.keys(r).filter((o)=>t[o]!==void 0||r[o]?.onUpdateFn!==void 0),n=i.length;return U.join(i.flatMap((o,s)=>{let a=r[o],c=a.onUpdateFn?.(),l=t[o]??(ae(c,Te)?c:U.param(c,a)),u=U`${U.identifier(this.casing.getColumnCasing(a))} = ${l}`;if(s<n-1)return[u,U.raw(", ")];return[u]}))}buildUpdateQuery({table:e,set:t,where:r,returning:i,withList:n,joins:o,from:s,limit:a,orderBy:c}){let l=this.buildWithCTE(n),u=this.buildUpdateSet(e,t),f=s&&U.join([U.raw(" from "),this.buildFromTable(s)]),p=this.buildJoins(o),m=i?U` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,y=r?U` where ${r}`:void 0,g=this.buildOrderBy(c),b=this.buildLimit(a);return U`${l}update ${e} set ${u}${f}${p}${y}${m}${g}${b}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,i=e.flatMap(({field:n},o)=>{let s=[];if(ae(n,Te.Aliased)&&n.isSelectionField)s.push(U.identifier(n.fieldAlias));else if(ae(n,Te.Aliased)||ae(n,Te)){let a=ae(n,Te.Aliased)?n.sql:n;if(t)s.push(new Te(a.queryChunks.map((c)=>{if(ae(c,nt))return U.identifier(this.casing.getColumnCasing(c));return c})));else s.push(a);if(ae(n,Te.Aliased))s.push(U` as ${U.identifier(n.fieldAlias)}`)}else if(ae(n,nt)){let a=n.table[we.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(U`cast(${U.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(U`cast(${U.identifier(a)}.${U.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(U.identifier(this.casing.getColumnCasing(n)));else s.push(U`${U.identifier(a)}.${U.identifier(this.casing.getColumnCasing(n))}`)}else if(ae(n,wt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let c=a[0][1],l=ae(c,Te)?c.decoder:ae(c,nt)?{mapFromDriverValue:(u)=>c.mapFromDriverValue(u)}:c.sql.decoder;if(l)n._.sql.decoder=l}s.push(n)}if(o<r-1)s.push(U`, `);return s});return U.join(i)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,i]of e.entries()){if(r===0)t.push(U` `);let n=i.table,o=i.on?U` on ${i.on}`:void 0;if(ae(n,Bt)){let s=n[Bt.Symbol.Name],a=n[Bt.Symbol.Schema],c=n[Bt.Symbol.OriginalName],l=s===c?void 0:i.alias;t.push(U`${U.raw(i.joinType)} join ${a?U`${U.identifier(a)}.`:void 0}${U.identifier(c)}${l&&U` ${U.identifier(l)}`}${o}`)}else t.push(U`${U.raw(i.joinType)} join ${n}${o}`);if(r<e.length-1)t.push(U` `)}return U.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?U` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,i]of e.entries())if(t.push(i),r<e.length-1)t.push(U`, `)}return t.length>0?U` order by ${U.join(t)}`:void 0}buildFromTable(e){if(ae(e,we)&&e[we.Symbol.IsAlias])return U`${U`${U.identifier(e[we.Symbol.Schema]??"")}.`.if(e[we.Symbol.Schema])}${U.identifier(e[we.Symbol.OriginalName])} ${U.identifier(e[we.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:i,having:n,table:o,joins:s,orderBy:a,groupBy:c,limit:l,offset:u,distinct:f,setOperators:p}){let m=r??vn(t);for(let P of m)if(ae(P.field,nt)&&hs(P.field.table)!==(ae(o,wt)?o._.alias:ae(o,so)?o[vt].name:ae(o,Te)?void 0:hs(o))&&!((N)=>s?.some(({alias:I})=>I===(N[we.Symbol.IsAlias]?hs(N):N[we.Symbol.BaseName])))(P.field.table)){let N=hs(P.field.table);throw Error(`Your "${P.path.join("->")}" field references a column "${N}"."${P.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}let y=!s||s.length===0,g=this.buildWithCTE(e),b=f?U` distinct`:void 0,_=this.buildSelection(m,{isSingleTable:y}),T=this.buildFromTable(o),A=this.buildJoins(s),z=i?U` where ${i}`:void 0,j=n?U` having ${n}`:void 0,E=[];if(c){for(let[P,N]of c.entries())if(E.push(N),P<c.length-1)E.push(U`, `)}let F=E.length>0?U` group by ${U.join(E)}`:void 0,D=this.buildOrderBy(a),H=this.buildLimit(l),X=u?U` offset ${u}`:void 0,Z=U`${g}select${b} ${_} from ${T}${A}${z}${F}${j}${D}${H}${X}`;if(p.length>0)return this.buildSetOperations(Z,p);return Z}buildSetOperations(e,t){let[r,...i]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(i.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),i)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:n,orderBy:o,offset:s}}){let a=U`${e.getSQL()} `,c=U`${i.getSQL()}`,l;if(o&&o.length>0){let m=[];for(let y of o)if(ae(y,It))m.push(U.identifier(y.name));else if(ae(y,Te)){for(let g=0;g<y.queryChunks.length;g++){let b=y.queryChunks[g];if(ae(b,It))y.queryChunks[g]=U.identifier(this.casing.getColumnCasing(b))}m.push(U`${y}`)}else m.push(U`${y}`);l=U` order by ${U.join(m,U`, `)}`}let u=typeof n==="object"||typeof n==="number"&&n>=0?U` limit ${n}`:void 0,f=U.raw(`${t} ${r?"all ":""}`),p=s?U` offset ${s}`:void 0;return U`${a}${f}${c}${l}${u}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:n,select:o}){let s=[],a=e[we.Symbol.Columns],c=Object.entries(a).filter(([y,g])=>!g.shouldDisableInsert()),l=c.map(([,y])=>U.identifier(this.casing.getColumnCasing(y)));if(o){let y=t;if(ae(y,Te))s.push(y);else s.push(y.getSQL())}else{let y=t;s.push(U.raw("values "));for(let[g,b]of y.entries()){let _=[];for(let[T,A]of c){let z=b[T];if(z===void 0||ae(z,an)&&z.value===void 0){let j;if(A.default!==null&&A.default!==void 0)j=ae(A.default,Te)?A.default:U.param(A.default,A);else if(A.defaultFn!==void 0){let E=A.defaultFn();j=ae(E,Te)?E:U.param(E,A)}else if(!A.default&&A.onUpdateFn!==void 0){let E=A.onUpdateFn();j=ae(E,Te)?E:U.param(E,A)}else j=U`null`;_.push(j)}else _.push(z)}if(s.push(_),g<y.length-1)s.push(U`, `)}}let u=this.buildWithCTE(n),f=U.join(s),p=i?U` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,m=r?.length?U.join(r):void 0;return U`${u}insert into ${e} ${l} ${f}${m}${p}`}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:i,tableConfig:n,queryConfig:o,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let l=[],u,f,p=[],m,y=[];if(o===!0)l=Object.entries(n.columns).map(([_,T])=>({dbKey:T.name,tsKey:_,field:xi(T,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(n.columns).map(([E,F])=>[E,xi(F,s)]));if(o.where){let E=typeof o.where==="function"?o.where(b,TH()):o.where;m=E&&dp(E,s)}let _=[],T=[];if(o.columns){let E=!1;for(let[F,D]of Object.entries(o.columns)){if(D===void 0)continue;if(F in n.columns){if(!E&&D===!0)E=!0;T.push(F)}}if(T.length>0)T=E?T.filter((F)=>o.columns?.[F]===!0):Object.keys(n.columns).filter((F)=>!T.includes(F))}else T=Object.keys(n.columns);for(let E of T){let F=n.columns[E];_.push({tsKey:E,value:F})}let A=[];if(o.with)A=Object.entries(o.with).filter((E)=>!!E[1]).map(([E,F])=>({tsKey:E,queryConfig:F,relation:n.relations[E]}));let z;if(o.extras){z=typeof o.extras==="function"?o.extras(b,{sql:U}):o.extras;for(let[E,F]of Object.entries(z))_.push({tsKey:E,value:X$(F,s)})}for(let{tsKey:E,value:F}of _)l.push({dbKey:ae(F,Te.Aliased)?F.fieldAlias:n.columns[E].name,tsKey:E,field:ae(F,nt)?xi(F,s):F,relationTableTsKey:void 0,isJson:!1,selection:[]});let j=typeof o.orderBy==="function"?o.orderBy(b,AH()):o.orderBy??[];if(!Array.isArray(j))j=[j];p=j.map((E)=>{if(ae(E,nt))return xi(E,s);return dp(E,s)}),u=o.limit,f=o.offset;for(let{tsKey:E,queryConfig:F,relation:D}of A){let H=CH(t,r,D),X=za(D.referencedTable),Z=r[X],P=`${s}_${E}`,N=Et(...H.fields.map((R,M)=>Qe(xi(H.references[M],P),xi(R,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[Z],tableConfig:t[Z],queryConfig:ae(D,bs)?F===!0?{limit:1}:{...F,limit:1}:F,tableAlias:P,joinOn:N,nestedQueryRelation:D}),O=U`(${I.sql})`.as(E);l.push({dbKey:E,tsKey:E,field:O,relationTableTsKey:Z,isJson:!0,selection:I.selection})}}if(l.length===0)throw new ru({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 g;if(m=Et(c,m),a){let b=U`json_array(${U.join(l.map(({field:A})=>ae(A,It)?U.identifier(this.casing.getColumnCasing(A)):ae(A,Te.Aliased)?A.sql:A),U`, `)})`;if(ae(a,cp))b=U`coalesce(json_group_array(${b}), json_array())`;let _=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:l}];if(u!==void 0||f!==void 0||p.length>0)g=this.buildSelectQuery({table:up(i,s),fields:{},fieldsFlat:[{path:[],field:U.raw("*")}],where:m,limit:u,offset:f,orderBy:p,setOperators:[]}),m=void 0,u=void 0,f=void 0,p=void 0;else g=up(i,s);g=this.buildSelectQuery({table:ae(g,Bt)?g:new wt(g,{},s),fields:{},fieldsFlat:_.map(({field:A})=>({path:[],field:ae(A,nt)?xi(A,s):A})),joins:y,where:m,limit:u,offset:f,orderBy:p,setOperators:[]})}else g=this.buildSelectQuery({table:up(i,s),fields:{},fieldsFlat:l.map(({field:b})=>({path:[],field:ae(b,nt)?xi(b,s):b})),joins:y,where:m,limit:u,offset:f,orderBy:p,setOperators:[]});return{tableTsKey:n.tsName,sql:g,selection:l}}};hC=class hC extends nu{static[J]="SQLiteSyncDialect";migrate(e,t,r){let i=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=U`
|
|
399
399
|
CREATE TABLE IF NOT EXISTS ${U.identifier(i)} (
|
|
400
400
|
id SERIAL PRIMARY KEY,
|
|
@@ -407,7 +407,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
407
407
|
hash text NOT NULL,
|
|
408
408
|
created_at numeric
|
|
409
409
|
)
|
|
410
|
-
`;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.identifier(i)} 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 l of c.sql)await a.run(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var yC;var IK=S(()=>{ze();yC=class yC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ub(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!ip(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(o)}}var Hn,TK,bC,Qbe=()=>({union:Ybe,unionAll:Xbe,intersect:eSe,except:tSe}),Ybe,Xbe,eSe,tSe;var SC=S(()=>{ze();IK();ro();La();lr();Mn();vr();Dr();eo();tu();mp();Hn=class Hn{static[J]="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(ae(e,wt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,so))r=e[vt].selectedFields;else if(ae(e,Te))r={};else r=Cb(e);return new bC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};TK=class TK extends yC{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=op(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=op(t);for(let o of Fn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ae(t,Te)){let o=ae(t,wt)?t._.selectedFields:ae(t,wn)?t[vt].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(([o])=>[o,!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(([o])=>[o,!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 i=typeof r==="function"?r(Qbe()):r;if(!ip(this.getSelectedFields(),i.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:i}),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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new wt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};bC=class bC extends TK{static[J]="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=vn(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()}};oH(bC,[Lr]);Ybe=Ub("union",!1),Xbe=Ub("union",!0),eSe=Ub("intersect",!1),tSe=Ub("except",!1)});var Ba;var qb=S(()=>{ze();La();jb();Mn();SC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,nu)?e:void 0,this.dialectConfig=ae(e,nu)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new tp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new hC(this.dialectConfig);return this.dialect}}});var Zb,xC;var AK=S(()=>{ze();ro();lr();no();vr();Dr();tu();qb();Zb=class Zb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="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 i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ae(s,Te)?s:new an(s,n[o])}return i});return new xC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!ip(this.table[Tb],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 xC(this.table,t,this.session,this.dialect,this.withList,!0)}};xC=class xC extends Lr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Bt.Symbol.Columns]){return this.config.returning=vn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` 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?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,$b(this.config.table,e.set));return this.config.onConflict.push(U` on conflict ${n}${r} do update set ${o}${t}${i}`),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:Fn(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 Mb,$K;var CK=S(()=>{ze();ro();La();no();Mn();vr();Dr();eo();tu();mp();Mb=class Mb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new $K(this.table,$b(this.table,e),this.session,this.dialect,this.withList)}};$K=class $K extends Lr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=op(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,wt)?t._.selectedFields:ae(t,so)?t[vt].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=vn(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:Fn(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 wC=S(()=>{wK();AK();qb();SC();CK()});var hp;var RK=S(()=>{ze();lr();hp=class hp extends Te{constructor(e){super(hp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=hp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.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 _C,Fb,vC;var OK=S(()=>{ze();ro();lp();_C=class _C{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new vC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Fb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new vC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Fb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Fb=class Fb extends Lr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="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,(i,n)=>{let o=i.map((s)=>zb(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}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()}};vC=class vC extends Fb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var iu;var PK=S(()=>{ze();ro();iu=class iu extends Lr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="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 gp;var Hb=S(()=>{ze();La();lr();wC();Mn();RK();OK();PK();gp=class gp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new _C(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ba(r.dialect));return new Proxy(new tp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new hp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Mb(a,t.session,t.dialect,e)}function o(a){return new Zb(a,t.session,t.dialect,e)}function s(a){return new Lb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Mb(e,this.session,this.dialect)}$cache;insert(e){return new Zb(e,this.session,this.dialect)}delete(e){return new Lb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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 kC(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var zK,yp;var EC=S(()=>{ze();zK=class zK{static[J]="Cache"};yp=class yp extends zK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var NK=S(()=>{EC()});function DK(e,t){return new Proxy(e,new Da(t,!1))}var LK=S(()=>{fp()});var BK,IC,TC,AC;var $C=S(()=>{EC();ze();Bb();ro();Hb();BK=class BK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};IC=class IC{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ae(this.cache,yp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new oo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new oo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await kC(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new oo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await kC(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new oo(e,t,i)}}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 BK(()=>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)}}};TC=class TC{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new ru({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")}};AC=class AC extends gp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new fC}}});var CC,rSe,nSe,Kb;var jK=S(()=>{ze();La();Dr();qb();no();mp();CC=class CC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};rSe=class rSe extends CC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Kb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};nSe=class nSe extends CC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Cb(pp(e,t))}existing(){return new Proxy(new Kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Kb=class Kb extends so{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var Jb=S(()=>{LK();mK();mC();Hb();jb();tC();bK();xK();wC();$C();no();nC();tu();jK()});function UK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Vb(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 Wb,RC,qK;var OC=S(()=>{NK();ze();Rb();lr();Jb();$C();Dr();Wb=class Wb extends TC{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new V$,this.cache=i.cache??new yp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new qK(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new Wb(this.client,this.dialect,this.schema,this.options,r),n=new RC("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};RC=class RC extends AC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new RC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};qK=class qK extends IC{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=np(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:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=np(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}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)=>UK(r));if(this.customResultMapper)return this.customResultMapper(e,Vb);return e.map((r)=>H$(this.fields,Array.prototype.slice.call(r).map((i)=>Vb(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=np(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}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 UK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Vb);return H$(this.fields,Array.prototype.slice.call(r).map((i)=>Vb(i)),this.joinsNotNullableMap)}async values(e){let t=np(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:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function ou(e,t={}){let r=new gC({casing:t.casing}),i;if(t.logger===!0)i=new J$;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=$H(t.schema,RH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new Wb(e,r,n,{logger:i,cache:t.cache},void 0),s=new ZK("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var ZK;var MK=S(()=>{ze();Rb();lp();Hb();jb();OC();ZK=class ZK extends gp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Gb(...e){if(typeof e[0]==="string"){let t=Gl({url:e[0]});return ou(t,e[1])}if(sH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return ou(r,i);let n=typeof t==="string"?Gl({url:t}):Gl(t);return ou(n,i)}return ou(e[0],e[1])}var FK=S(()=>{z$();Dr();MK();((e)=>{function t(r){return ou({},r)}e.mock=t})(Gb||(Gb={}))});var HK=S(()=>{FK();OC()});function iSe(){return new Promise((e)=>setTimeout(e,0))}function sSe(){if(PC)return;PC=!0,setTimeout(()=>{PC=!1,zC=performance.now()},0)}async function bp(e=oSe){if(sSe(),performance.now()-zC<e)return;await iSe(),zC=performance.now()}var oSe=50,zC,PC=!1;var KK=S(()=>{zC=performance.now()});function JK(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function uSe(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Qb(e,t){let r=Date.now()+(t.budgetMs??aSe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!uSe(o))throw o;await t.afterRefusal?.();let s=Math.min(cSe*2**(n-1),lSe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function NC(e,t={}){let r=Gl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function u(f,p){return await bp(),Qb(()=>typeof f==="string"?s(f,p):s(f),l)}r.execute=u,r.batch=async(f,p)=>(await bp(),Qb(()=>a(f,p),l)),r.migrate=async(f)=>(await bp(),Qb(()=>c(f),l)),r.transaction=async(f)=>(await bp(),Qb(()=>i(f),l))}return r}function Yb(e){let{url:t,schema:r}=e,i=JK(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?NC({url:t,authToken:i},n):NC({url:t},n);return{db:Gb(o,{schema:r}),client:o,url:t}}async function Xb(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var aSe=5000,cSe=5,lSe=40;var DC=S(()=>{z$();HK();KK()});var VK=S(()=>{WA();DC()});var LC=S(()=>{DC();VK()});var BC=S(()=>{fp();kb();Zn();ze();Bb();Rb();ro();lp();pC();Mn();vr();Dr();eo()});var ne,pt;var jC=S(()=>{Jb();BC();$f();ne=pp("job_queue",{id:ur("id").primaryKey().$defaultFn(()=>Wi()),type:ur("type").notNull(),data:ur("data").notNull(),result:ur("result",{mode:"json"}),progress:ur("progress",{mode:"json"}).$type(),source:ur("source"),metadata:ur("metadata",{mode:"json"}).$type().notNull(),status:ur("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:ur("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:ur("attemptId"),workerSlotId:ur("workerSlotId"),workerSessionId:ur("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:io("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:io("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:io("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:io("idx_job_queue_source").on(e.source),rootJobIdx:io("idx_job_queue_root_job").on(U`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:io("idx_job_queue_deduplication").on(e.type,U`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),pt=pp("job_worker_sessions",{slotId:ur("slotId").primaryKey(),sessionId:ur("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:io("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:io("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function WK(e){return Yb({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var GK=S(()=>{LC();jC()});class UC{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 qC{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class ZC{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ue.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=dSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var dSe;var QK=S(()=>{Ae();os();dSe=d.looseObject({deduplicationKey:d.string().optional()})});class MC{db;transactionClient;databaseUrl;logger;deduplicator=new ZC;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??fSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return gSe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type,o),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((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 p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ue.FAILED,"Replaced by newer job",p,p,f.id,Ue.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.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,Ue.PENDING,Ue.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ue.PENDING,Ue.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ue.PENDING&&r!==Ue.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata: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`\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]})).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,i,n){let o=Math.min(pSe*2**(i-1),mSe),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=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: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.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):"",i=at(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=is){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=is){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(Et(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(Et(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(ne).set({status:Ue.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(ne).set({status:s?Ue.PENDING:Ue.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(Et(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.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 i=(await this.write("retire unowned job",async()=>this.db.update(ne).set({status:Ue.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(Et(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),Si(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),_n(ne.attemptId),_n(ne.workerSlotId),_n(ne.workerSessionId),_n(ne.leaseExpiresAt),_n(ne.attemptHeartbeatAt),_n(ne.progress),_n(ne.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(to(ne.createdAt),to(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(Na(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ue.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ue.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,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=hSe.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(to(ne.runtimeUpdatedAt),to(ne.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(ne).where(Et(Si(Qe(ne.status,Ue.COMPLETED),Qe(ne.status,Ue.FAILED)),Xl(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=Si(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),r=e&&e.length>0?Et(t,ys(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?ys(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ue.FAILED),r=e&&e.length>0?Et(t,ys(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(Et(Qe(pt.slotId,i),Qe(pt.sessionId,n),sp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(Et(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=Et(Qe(ne.status,Ue.PROCESSING),Si(_n(ne.attemptId),ap(l),Xl(ne.leaseExpiresAt,t))),f=DK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(Et(Qe(f.type,ne.type),Qe(f.status,Ue.PROCESSING),sp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:Si(Ob(ne.type,[...a]),ap(p)),y=U`${ne.status} = ${Ue.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(Et(ys(ne.type,s),m,Si(Et(Qe(ne.status,Ue.PENDING),Xl(ne.scheduledFor,t)),u))).orderBy(to(ne.priority),to(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ue.FAILED} ELSE ${Ue.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(Et(ys(ne.id,g),Pb(c))).returning()))[0];if(!_)return null;if(_.status===Ue.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?Et(Qe(ne.id,e),Qe(ne.status,Ue.PROCESSING),Qe(ne.attemptId,t)):Et(Qe(ne.id,e),_n(ne.attemptId),Si(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)))}}var fSe=2000,pSe=5,mSe=40,hSe,gSe;var YK=S(()=>{BC();Jb();jC();Ae();os();Rf();QK();hSe=d.number().int().min(0).max(1000),gSe=new qC});import{AsyncLocalStorage as ySe}from"async_hooks";class Sp{storage=new ySe;static createFresh(){return new Sp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Go.parse(e),n=bSe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function bSe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var FC=S(()=>{pi()});class xp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Wi()}`;directWorkerSessionId=Wi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new xp(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=WK(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Sp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new UC(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new MC(i,n,o,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 Xb(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:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Wi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ue.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:at(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return Go.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Wi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ue.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=is){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=is){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(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.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),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,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)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 XK=S(()=>{$f();WA();Rf();os();LC();GK();YK();pi();FC()});var HC=()=>{};var eJ=S(()=>{$f();os();Rf();os();HC();FC()});var tJ=S(()=>{os();HC()});var tWe;var rJ=S(()=>{pi();Ae();Cf();tWe=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var iWe;var nJ=S(()=>{Ae();iWe=d.record(d.string(),d.unknown())});var iJ=S(()=>{pi();$f()});var oJ=S(()=>{XK();eJ();tJ();rJ();nJ();Rf();os();Cf();iJ()});var KC={};Ht(KC,{LEGACY_PROJECTION_JOB_TYPES:()=>aJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>lJ,legacyProjectionJobTypeSchema:()=>cJ,retireLegacyProjectionJob:()=>ASe});import{existsSync as ESe}from"fs";import{resolve as ISe}from"path";function sJ(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 TSe(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 ASe(e){let t=ISe(e.databasePath);if(!ESe(t))throw Error(`Job database does not exist: ${t}`);let r=cJ.parse(e.jobType),i=xp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(TSe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:sJ(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:lJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:sJ(s),retired:!0}}finally{i.close()}}var aJ,cJ,lJ="Retired legacy projection job superseded by scheduler-owned projections";var JC=S(()=>{oJ();Ae();aJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],cJ=d.enum(aJ)});function Qt(e,t,r,i,n){return dJ.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function hJ(e){return rS.parse(structuredClone(PSe[e]))}function nS(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 WC(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),VC.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return VC.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:NSe(c)})}finally{clearTimeout(a)}}async function gJ(e,t){let r=rS.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${eS(c)}`}if(!n)for(let c of r.phases)try{let l=fJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=eS(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=pJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=eS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=mJ.parse(await t.stopMonitoring())}catch(c){let l=eS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=zSe(a,r.maximumExternalAiCalls??0),OSe.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function zSe(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} 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 NSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function eS(e){return at(e)}var tS,uJ,dJ,rS,$Se,VC,CSe,fJ,pJ,RSe,mJ,OSe,PSe;var GC=S(()=>{Ae();tS=d.enum(["regression","load","stress"]),uJ=d.enum(["add","update","rename","delete"]),dJ=d.object({id:d.string().min(1),operation:uJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),rS=d.object({profile:tS,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(dJ).min(1)}),$Se=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),VC=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),CSe=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),fJ=d.object({id:d.string().min(1),operation:uJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),pJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),RSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),mJ=d.object({health:d.array(VC),runtime:d.array(CSe),externalAiCalls:d.number().int().nonnegative().optional(),container:RSe.optional()}),OSe=d.object({profile:tS,success:d.boolean(),baseline:$Se,phases:d.array(fJ),cleanup:pJ,metrics:mJ,failure:d.string().optional()}),PSe={regression:{profile:"regression",maximumProbeCount:20,phases:[Qt("add20","add",20,20,0),Qt("update20","update",20,20,30000),Qt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Qt("add50","add",50,50,0),Qt("add150","add",100,150,0),Qt("add350","add",200,350,0),Qt("update350a","update",350,350,45000),Qt("rename100","rename",100,350,45000),Qt("update350b","update",350,350,45000),Qt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Qt("add50","add",50,50,0),Qt("add150","add",100,150,0),Qt("add350","add",200,350,0),Qt("add700","add",350,700,0),Qt("update700a","update",700,700,45000),Qt("rename200","rename",200,700,45000),Qt("update700b","update",700,700,45000),Qt("delete700","delete",700,0,150000)]}}});import{spawn as DSe}from"child_process";async function yJ(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw wi(t,r,n);return n}function wi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var ao=async(e,t,r={})=>new Promise((i,n)=>{let o=DSe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var wp=()=>{};class su{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new su(e,r,i);return await yJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${bJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",bJ]),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 wi("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 bJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var SJ=S(()=>{wp()});function vp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class QC{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#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 WC(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return LSe.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||vp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await WC(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var LSe;var xJ=S(()=>{Ae();GC();LSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var iS={};Ht(iS,{applyDirectorySyncStressPhase:()=>kJ,cleanupDirectorySyncStress:()=>JSe,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>EJ,removeProbeFiles:()=>iR,runDeployedDirectorySyncStress:()=>HSe,runStressCommand:()=>ao,verifyDirectorySyncStressAccess:()=>KSe});import{chmod as BSe,mkdir as XC,mkdtemp as eR,readFile as jSe,readdir as USe,rename as qSe,rm as kp,writeFile as Kn}from"fs/promises";import{tmpdir as tR}from"os";import{join as St,resolve as rR}from"path";async function HSe(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=oR(r),n=rR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await XC(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);nS({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=tS.parse(e.profile),c=e.plan?rS.parse(e.plan):hJ(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)_J(s);let l=ZSe.parse(e.env??process.env),u=new vJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??ao,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await gJ(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await GSe(p),p}async function KSe(e){let r=(e.now??(()=>new Date))().toISOString(),i=oR(r),n=rR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await XC(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);nS({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),_J(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await eR(St(tR(),"brains-ops-directory-sync-access-check-"));try{let l=await su.clone(e.commandRunner??ao,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
410
|
+
`;await t.run(n);let s=(await t.values(U`SELECT id, hash, created_at FROM ${U.identifier(i)} 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 l of c.sql)await a.run(U.raw(l));await a.run(U`INSERT INTO ${U.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var yC;var IK=S(()=>{ze();yC=class yC{static[J]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Ub(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!ip(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(o)}}var Hn,TK,bC,Qbe=()=>({union:Ybe,unionAll:Xbe,intersect:eSe,except:tSe}),Ybe,Xbe,eSe,tSe;var SC=S(()=>{ze();IK();ro();La();lr();Mn();vr();Dr();eo();tu();mp();Hn=class Hn{static[J]="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(ae(e,wt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ae(e,so))r=e[vt].selectedFields;else if(ae(e,Te))r={};else r=Cb(e);return new bC({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};TK=class TK extends yC{static[J]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=op(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Fn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=op(t);for(let o of Fn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ae(t,Te)){let o=ae(t,wt)?t._.selectedFields:ae(t,wn)?t[vt].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(([o])=>[o,!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(([o])=>[o,!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 i=typeof r==="function"?r(Qbe()):r;if(!ip(this.getSelectedFields(),i.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:i}),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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Fn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Fn(r.table));return new Proxy(new wt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};bC=class bC extends TK{static[J]="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=vn(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()}};oH(bC,[Lr]);Ybe=Ub("union",!1),Xbe=Ub("union",!0),eSe=Ub("intersect",!1),tSe=Ub("except",!1)});var Ba;var qb=S(()=>{ze();La();jb();Mn();SC();Ba=class Ba{static[J]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ae(e,nu)?e:void 0,this.dialectConfig=ae(e,nu)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new tp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Hn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Hn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new hC(this.dialectConfig);return this.dialect}}});var Zb,xC;var AK=S(()=>{ze();ro();lr();no();vr();Dr();tu();qb();Zb=class Zb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="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 i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ae(s,Te)?s:new an(s,n[o])}return i});return new xC(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ba):e;if(!ae(t,Te)&&!ip(this.table[Tb],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 xC(this.table,t,this.session,this.dialect,this.withList,!0)}};xC=class xC extends Lr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[J]="SQLiteInsert";config;returning(e=this.config.table[Bt.Symbol.Columns]){return this.config.returning=vn(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(U` on conflict do nothing`);else{let t=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,r=e.where?U` where ${e.where}`:U``;this.config.onConflict.push(U` 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?U` where ${e.where}`:void 0,r=e.targetWhere?U` where ${e.targetWhere}`:void 0,i=e.setWhere?U` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?U`${e.target}`:U`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,$b(this.config.table,e.set));return this.config.onConflict.push(U` on conflict ${n}${r} do update set ${o}${t}${i}`),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:Fn(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 Mb,$K;var CK=S(()=>{ze();ro();La();no();Mn();vr();Dr();eo();tu();mp();Mb=class Mb{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[J]="SQLiteUpdateBuilder";set(e){return new $K(this.table,$b(this.table,e),this.session,this.dialect,this.withList)}};$K=class $K extends Lr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[J]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=op(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ae(t,Bt)?t[we.Symbol.Columns]:ae(t,wt)?t._.selectedFields:ae(t,so)?t[vt].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),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[we.Symbol.Columns],new bt({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[Bt.Symbol.Columns]){return this.config.returning=vn(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:Fn(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 wC=S(()=>{wK();AK();qb();SC();CK()});var hp;var RK=S(()=>{ze();lr();hp=class hp extends Te{constructor(e){super(hp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=hp.buildCount(e.source,e.filters)}sql;static[J]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return U`(select count(*) from ${e}${U.raw(" where ").if(t)}${t})`}static buildCount(e,t){return U`select count(*) from ${e}${U.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 _C,Fb,vC;var OK=S(()=>{ze();ro();lp();_C=class _C{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[J]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new vC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Fb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new vC(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Fb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Fb=class Fb extends Lr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[J]="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,(i,n)=>{let o=i.map((s)=>zb(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}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()}};vC=class vC extends Fb{static[J]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var iu;var PK=S(()=>{ze();ro();iu=class iu extends Lr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[J]="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 gp;var Hb=S(()=>{ze();La();lr();wC();Mn();RK();OK();PK();gp=class gp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new _C(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[J]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ba(r.dialect));return new Proxy(new tp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new hp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Hn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new Mb(a,t.session,t.dialect,e)}function o(a){return new Zb(a,t.session,t.dialect,e)}function s(a){return new Lb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Hn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Mb(e,this.session,this.dialect)}$cache;insert(e){return new Zb(e,this.session,this.dialect)}delete(e){return new Lb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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"?U.raw(e):e.getSQL();if(this.resultKind==="async")return new iu(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 kC(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var zK,yp;var EC=S(()=>{ze();zK=class zK{static[J]="Cache"};yp=class yp extends zK{strategy(){return"all"}static[J]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var NK=S(()=>{EC()});function DK(e,t){return new Proxy(e,new Da(t,!1))}var LK=S(()=>{fp()});var BK,IC,TC,AC;var $C=S(()=>{EC();ze();Bb();ro();Hb();BK=class BK extends Lr{constructor(e){super();this.resultCb=e}static[J]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};IC=class IC{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[J]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ae(this.cache,yp)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new oo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new oo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new oo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await kC(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new oo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await kC(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new oo(e,t,i)}}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 BK(()=>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)}}};TC=class TC{constructor(e){this.dialect=e}static[J]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new ru({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")}};AC=class AC extends gp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[J]="SQLiteTransaction";rollback(){throw new fC}}});var CC,rSe,nSe,Kb;var jK=S(()=>{ze();La();Dr();qb();no();mp();CC=class CC{constructor(e){this.name=e}static[J]="SQLiteViewBuilderCore";config={}};rSe=class rSe extends CC{static[J]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ba);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Kb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};nSe=class nSe extends CC{static[J]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=Cb(pp(e,t))}existing(){return new Proxy(new Kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Kb=class Kb extends so{static[J]="SQLiteView";constructor({config:e}){super(e)}}});var Jb=S(()=>{LK();mK();mC();Hb();jb();tC();bK();xK();wC();$C();no();nC();tu();jK()});function UK(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Vb(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 Wb,RC,qK;var OC=S(()=>{NK();ze();Rb();lr();Jb();$C();Dr();Wb=class Wb extends TC{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new V$,this.cache=i.cache??new yp}static[J]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new qK(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new Wb(this.client,this.dialect,this.schema,this.options,r),n=new RC("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};RC=class RC extends AC{static[J]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new RC("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(U.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(U.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(U.raw(`rollback to savepoint ${t}`)),i}}};qK=class qK extends IC{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[J]="LibSQLPreparedQuery";async run(e){let t=np(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:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=np(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}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)=>UK(r));if(this.customResultMapper)return this.customResultMapper(e,Vb);return e.map((r)=>H$(this.fields,Array.prototype.slice.call(r).map((i)=>Vb(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=np(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}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 UK(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Vb);return H$(this.fields,Array.prototype.slice.call(r).map((i)=>Vb(i)),this.joinsNotNullableMap)}async values(e){let t=np(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:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function ou(e,t={}){let r=new gC({casing:t.casing}),i;if(t.logger===!0)i=new J$;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=$H(t.schema,RH);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new Wb(e,r,n,{logger:i,cache:t.cache},void 0),s=new ZK("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var ZK;var MK=S(()=>{ze();Rb();lp();Hb();jb();OC();ZK=class ZK extends gp{static[J]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Gb(...e){if(typeof e[0]==="string"){let t=Gl({url:e[0]});return ou(t,e[1])}if(sH(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return ou(r,i);let n=typeof t==="string"?Gl({url:t}):Gl(t);return ou(n,i)}return ou(e[0],e[1])}var FK=S(()=>{z$();Dr();MK();((e)=>{function t(r){return ou({},r)}e.mock=t})(Gb||(Gb={}))});var HK=S(()=>{FK();OC()});function iSe(){return new Promise((e)=>setTimeout(e,0))}function sSe(){if(PC)return;PC=!0,setTimeout(()=>{PC=!1,zC=performance.now()},0)}async function bp(e=oSe){if(sSe(),performance.now()-zC<e)return;await iSe(),zC=performance.now()}var oSe=50,zC,PC=!1;var KK=S(()=>{zC=performance.now()});function JK(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function uSe(e){return e instanceof Be&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Qb(e,t){let r=Date.now()+(t.budgetMs??aSe),i=async(n)=>{if(t.isClosed())throw new Be("The client is closed","CLIENT_CLOSED");try{return await e()}catch(o){if(t.isClosed()||!uSe(o))throw o;await t.afterRefusal?.();let s=Math.min(cSe*2**(n-1),lSe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw o;if(await new Promise((c)=>setTimeout(c,a)),t.isClosed()||Date.now()>=r)throw o;return i(n+1)}};return i(1)}function NC(e,t={}){let r=Gl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let i=r.transaction.bind(r),n=()=>r.closed,o=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),c=r.migrate.bind(r),l={isClosed:n,budgetMs:o,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function u(f,p){return await bp(),Qb(()=>typeof f==="string"?s(f,p):s(f),l)}r.execute=u,r.batch=async(f,p)=>(await bp(),Qb(()=>a(f,p),l)),r.migrate=async(f)=>(await bp(),Qb(()=>c(f),l)),r.transaction=async(f)=>(await bp(),Qb(()=>i(f),l))}return r}function Yb(e){let{url:t,schema:r}=e,i=JK(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},o=i?NC({url:t,authToken:i},n):NC({url:t},n);return{db:Gb(o,{schema:r}),client:o,url:t}}async function Xb(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var aSe=5000,cSe=5,lSe=40;var DC=S(()=>{z$();HK();KK()});var VK=S(()=>{WA();DC()});var LC=S(()=>{DC();VK()});var BC=S(()=>{fp();kb();Zn();ze();Bb();Rb();ro();lp();pC();Mn();vr();Dr();eo()});var ne,pt;var jC=S(()=>{Jb();BC();$f();ne=pp("job_queue",{id:ur("id").primaryKey().$defaultFn(()=>Wi()),type:ur("type").notNull(),data:ur("data").notNull(),result:ur("result",{mode:"json"}),progress:ur("progress",{mode:"json"}).$type(),source:ur("source"),metadata:ur("metadata",{mode:"json"}).$type().notNull(),status:ur("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:_r("priority").notNull().default(0),retryCount:_r("retryCount").notNull().default(0),maxRetries:_r("maxRetries").notNull().default(3),lastError:ur("lastError"),createdAt:_r("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:_r("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:_r("startedAt"),completedAt:_r("completedAt"),attemptId:ur("attemptId"),workerSlotId:ur("workerSlotId"),workerSessionId:ur("workerSessionId"),leaseExpiresAt:_r("leaseExpiresAt"),attemptHeartbeatAt:_r("attemptHeartbeatAt"),runtimeUpdatedAt:_r("runtimeUpdatedAt")},(e)=>({queueReadyIdx:io("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:io("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:io("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:io("idx_job_queue_source").on(e.source),rootJobIdx:io("idx_job_queue_root_job").on(U`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:io("idx_job_queue_deduplication").on(e.type,U`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),pt=pp("job_worker_sessions",{slotId:ur("slotId").primaryKey(),sessionId:ur("sessionId").notNull().unique(),startedAt:_r("startedAt").notNull(),heartbeatAt:_r("heartbeatAt").notNull(),expiresAt:_r("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:io("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:io("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function WK(e){return Yb({url:e.url,schema:{jobQueue:ne,jobWorkerSessions:pt},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var GK=S(()=>{LC();jC()});class UC{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 qC{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class ZC{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===Ue.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=dSe.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var dSe;var QK=S(()=>{Ae();os();dSe=d.looseObject({deduplicationKey:d.string().optional()})});class MC{db;transactionClient;databaseUrl;logger;deduplicator=new ZC;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??fSe}async insert(e){await this.write("insert",async()=>this.db.insert(ne).values(e))}async enqueueAtomic(e){return gSe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let i=await this.runEnqueueTransaction(e,t,r);if(i.retry)return this.attemptEnqueue(e,t,r+1);return i.decision}async runEnqueueTransaction(e,t,r){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type,o),f=this.deduplicator.findDuplicate(u,a,o);if(!f)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:f.id};if(a==="coalesce"){if((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 p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Ue.FAILED,"Replaced by newer job",p,p,f.id,Ue.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${f.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.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,Ue.PENDING,Ue.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ue.PENDING,Ue.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==Ue.PENDING&&r!==Ue.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata: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`\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]})).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,i,n){let o=Math.min(pSe*2**(i-1),mSe),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:i});let n=t.strategy??"none",o=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: ${o})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let i=new Set;for(let n=r;n!==void 0&&!i.has(n);){if(i.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):"",i=at(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=is){let n=r+i;await this.write("start worker session",async()=>this.db.insert(pt).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:pt.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}}))}async heartbeatWorkerSession(e,t,r=Date.now(),i=is){return(await this.write("heartbeat worker session",async()=>this.db.update(pt).set({heartbeatAt:r,expiresAt:r+i}).where(Et(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(pt).where(Et(Qe(pt.slotId,e),Qe(pt.sessionId,t))).returning({slotId:pt.slotId}))).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.write("complete",async()=>this.db.update(ne).set({status:Ue.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(ne).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:ne.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ne).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async renewAttemptLease(e,t,r,i){return(await this.write("renew attempt lease",async()=>this.db.update(ne).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:ne.id}))).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:ne.retryCount,maxRetries:ne.maxRetries,type:ne.type,scheduledFor:ne.scheduledFor,startedAt:ne.startedAt,runtimeUpdatedAt:ne.runtimeUpdatedAt}).from(ne).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.write("fail",async()=>this.db.update(ne).set({status:s?Ue.PENDING:Ue.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(Et(this.attemptWriteGuard(e,r),Qe(ne.retryCount,o.retryCount))).returning({id:ne.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.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 i=(await this.write("retire unowned job",async()=>this.db.update(ne).set({status:Ue.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(Et(Qe(ne.id,e.jobId),Qe(ne.type,e.expectedType),Si(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),_n(ne.attemptId),_n(ne.workerSlotId),_n(ne.workerSessionId),_n(ne.leaseExpiresAt),_n(ne.attemptHeartbeatAt),_n(ne.progress),_n(ne.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ne).where(Qe(ne.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ne).where(U`json_extract(${ne.metadata}, '$.rootJobId') = ${e}`).orderBy(to(ne.createdAt),to(ne.id))}async getStatusByEntityId(e){return(await this.db.select().from(ne).where(U`json_extract(${ne.data}, '$.id') = ${e}`).orderBy(Na(ne.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:ne.type,status:ne.status,count:U`count(*)`}).from(ne).groupBy(ne.type,ne.status),this.db.select({oldestPendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} then ${ne.createdAt} end)`,duePending:U`coalesce(sum(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:U`min(case when ${ne.status} = ${Ue.PENDING} and ${ne.scheduledFor} <= ${e} then ${ne.scheduledFor} end)`,latestClaimAt:U`max(${ne.startedAt})`,oldestProcessingAt:U`min(case when ${ne.status} = ${Ue.PROCESSING} then ${ne.startedAt} end)`,staleLeaseCount:U`coalesce(sum(case when ${ne.status} = ${Ue.PROCESSING} and ${ne.leaseExpiresAt} is not null and ${ne.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ne),this.db.select({total:U`count(*)`,active:U`coalesce(sum(case when ${pt.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:U`coalesce(sum(case when ${pt.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:U`max(${pt.heartbeatAt})`}).from(pt)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,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=hSe.parse(t);if(r===0)return[];return(await this.db.select().from(ne).where(U`(${ne.runtimeUpdatedAt}, ${ne.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(to(ne.runtimeUpdatedAt),to(ne.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(ne).where(Et(Si(Qe(ne.status,Ue.COMPLETED),Qe(ne.status,Ue.FAILED)),Xl(ne.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=Si(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)),r=e&&e.length>0?Et(t,ys(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?ys(ne.type,e):void 0;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(ne.status,Ue.FAILED),r=e&&e.length>0?Et(t,ys(ne.type,e)):t;return this.db.select().from(ne).where(r).orderBy(Na(ne.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s,exclusiveTypes:a=[]}=e,c=this.db.select({slotId:pt.slotId}).from(pt).where(Et(Qe(pt.slotId,i),Qe(pt.sessionId,n),sp(pt.expiresAt,t))),l=this.db.select({slotId:pt.slotId}).from(pt).where(Et(Qe(pt.slotId,ne.workerSlotId),Qe(pt.sessionId,ne.workerSessionId))),u=Et(Qe(ne.status,Ue.PROCESSING),Si(_n(ne.attemptId),ap(l),Xl(ne.leaseExpiresAt,t))),f=DK(ne,"running"),p=this.db.select({id:f.id}).from(f).where(Et(Qe(f.type,ne.type),Qe(f.status,Ue.PROCESSING),sp(f.leaseExpiresAt,t),U`${f.id} <> ${ne.id}`)),m=a.length===0?void 0:Si(Ob(ne.type,[...a]),ap(p)),y=U`${ne.status} = ${Ue.PROCESSING} AND ${ne.retryCount} + 1 > ${ne.maxRetries}`,g=this.db.select({id:ne.id}).from(ne).where(Et(ys(ne.type,s),m,Si(Et(Qe(ne.status,Ue.PENDING),Xl(ne.scheduledFor,t)),u))).orderBy(to(ne.priority),to(ne.createdAt)).limit(1),_=(await this.write("claim",async()=>this.db.update(ne).set({status:U`CASE WHEN ${y} THEN ${Ue.FAILED} ELSE ${Ue.PROCESSING} END`,retryCount:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN ${ne.retryCount} + 1 ELSE ${ne.retryCount} END`,lastError:U`CASE WHEN ${ne.status} = ${Ue.PROCESSING} THEN 'Attempt lease expired' ELSE ${ne.lastError} END`,startedAt:U`CASE WHEN ${y} THEN ${ne.startedAt} ELSE ${t} END`,completedAt:U`CASE WHEN ${y} THEN ${t} ELSE NULL END`,attemptId:U`CASE WHEN ${y} THEN ${ne.attemptId} ELSE ${r} END`,workerSlotId:U`CASE WHEN ${y} THEN ${ne.workerSlotId} ELSE ${i} END`,workerSessionId:U`CASE WHEN ${y} THEN ${ne.workerSessionId} ELSE ${n} END`,leaseExpiresAt:U`CASE WHEN ${y} THEN ${ne.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:U`CASE WHEN ${y} THEN ${ne.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:U`CASE WHEN ${y} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ne.runtimeUpdatedAt} END`}).where(Et(ys(ne.id,g),Pb(c))).returning()))[0];if(!_)return null;if(_.status===Ue.FAILED)return _;return this.logger.debug("Job claimed",{jobId:_.id,attemptId:_.attemptId,workerSlotId:i,workerSessionId:n}),_}nextRuntimeUpdatedAt(e){return U`max(${e}, coalesce((select max(${ne.runtimeUpdatedAt}) from ${ne}), 0) + 1)`}attemptWriteGuard(e,t){return t?Et(Qe(ne.id,e),Qe(ne.status,Ue.PROCESSING),Qe(ne.attemptId,t)):Et(Qe(ne.id,e),_n(ne.attemptId),Si(Qe(ne.status,Ue.PENDING),Qe(ne.status,Ue.PROCESSING)))}}var fSe=2000,pSe=5,mSe=40,hSe,gSe;var YK=S(()=>{BC();Jb();jC();Ae();os();Rf();QK();hSe=d.number().int().min(0).max(1000),gSe=new qC});import{AsyncLocalStorage as ySe}from"async_hooks";class Sp{storage=new ySe;static createFresh(){return new Sp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Go.parse(e),n=bSe(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function bSe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var FC=S(()=>{pi()});class xp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Wi()}`;directWorkerSessionId=Wi();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new xp(e,t??on.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=WK(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Sp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new UC(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new MC(i,n,o,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 Xb(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:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Wi(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:f,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:Ue.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:at(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return Go.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...i}=e??await this.getDirectClaimOptions(),n=Date.now(),o=await this.repository.claimNextReady({...i,now:n,attemptId:Wi(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!o)return null;if(o.status===Ue.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:o.id,type:o.type,retryCount:o.retryCount}),await r?.(o),null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,r=is){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=is){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(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.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),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,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)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 XK=S(()=>{$f();WA();Rf();os();LC();GK();YK();pi();FC()});var HC=()=>{};var eJ=S(()=>{$f();os();Rf();os();HC();FC()});var tJ=S(()=>{os();HC()});var rWe;var rJ=S(()=>{pi();Ae();Cf();rWe=d.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},d.record(d.string(),d.unknown()))});var oWe;var nJ=S(()=>{Ae();oWe=d.record(d.string(),d.unknown())});var iJ=S(()=>{pi();$f()});var oJ=S(()=>{XK();eJ();tJ();rJ();nJ();Rf();os();Cf();iJ()});var KC={};Ht(KC,{LEGACY_PROJECTION_JOB_TYPES:()=>aJ,LEGACY_PROJECTION_RETIREMENT_REASON:()=>lJ,legacyProjectionJobTypeSchema:()=>cJ,retireLegacyProjectionJob:()=>ASe});import{existsSync as ESe}from"fs";import{resolve as ISe}from"path";function sJ(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 TSe(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 ASe(e){let t=ISe(e.databasePath);if(!ESe(t))throw Error(`Job database does not exist: ${t}`);let r=cJ.parse(e.jobType),i=xp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(TSe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:sJ(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:lJ,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:sJ(s),retired:!0}}finally{i.close()}}var aJ,cJ,lJ="Retired legacy projection job superseded by scheduler-owned projections";var JC=S(()=>{oJ();Ae();aJ=["conversation-memory:project","skill:project","swot:derive","topic:project"],cJ=d.enum(aJ)});function Qt(e,t,r,i,n){return dJ.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function hJ(e){return rS.parse(structuredClone(PSe[e]))}function nS(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 WC(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),VC.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return VC.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:NSe(c)})}finally{clearTimeout(a)}}async function gJ(e,t){let r=rS.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${eS(c)}`}if(!n)for(let c of r.phases)try{let l=fJ.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=eS(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=pJ.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=eS(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=mJ.parse(await t.stopMonitoring())}catch(c){let l=eS(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=zSe(a,r.maximumExternalAiCalls??0),OSe.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function zSe(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} 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 NSe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function eS(e){return at(e)}var tS,uJ,dJ,rS,$Se,VC,CSe,fJ,pJ,RSe,mJ,OSe,PSe;var GC=S(()=>{Ae();tS=d.enum(["regression","load","stress"]),uJ=d.enum(["add","update","rename","delete"]),dJ=d.object({id:d.string().min(1),operation:uJ,count:d.number().int().positive().max(700),targetProbeCount:d.number().int().min(0).max(700),settleMs:d.number().int().nonnegative().max(300000)}),rS=d.object({profile:tS,maximumProbeCount:d.number().int().positive().max(700),maximumExternalAiCalls:d.number().int().nonnegative().max(1e4).optional(),phases:d.array(dJ).min(1)}),$Se=d.object({entities:d.number().int().nonnegative(),notes:d.number().int().nonnegative(),version:d.string().min(1)}),VC=d.object({timestamp:d.iso.datetime(),endpoint:d.string().startsWith("/"),status:d.number().int().nonnegative(),durationMs:d.number().nonnegative(),ok:d.boolean(),error:d.string().optional()}),CSe=d.object({timestamp:d.iso.datetime(),cpuPercent:d.number().nonnegative(),memoryPercent:d.number().nonnegative(),pids:d.number().int().nonnegative()}),fJ=d.object({id:d.string().min(1),operation:uJ,count:d.number().int().positive(),success:d.boolean(),commitLatencyMs:d.number().nonnegative().optional(),persistenceLatencyMs:d.number().nonnegative().optional(),error:d.string().optional()}),pJ=d.object({success:d.boolean(),probesRemaining:d.number().int().nonnegative(),finalEntities:d.number().int().nonnegative().optional(),finalNotes:d.number().int().nonnegative().optional(),contentTreeRestored:d.boolean().optional(),error:d.string().optional()}),RSe=d.object({status:d.string(),restartCount:d.number().int().nonnegative(),oomKilled:d.boolean()}),mJ=d.object({health:d.array(VC),runtime:d.array(CSe),externalAiCalls:d.number().int().nonnegative().optional(),container:RSe.optional()}),OSe=d.object({profile:tS,success:d.boolean(),baseline:$Se,phases:d.array(fJ),cleanup:pJ,metrics:mJ,failure:d.string().optional()}),PSe={regression:{profile:"regression",maximumProbeCount:20,phases:[Qt("add20","add",20,20,0),Qt("update20","update",20,20,30000),Qt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Qt("add50","add",50,50,0),Qt("add150","add",100,150,0),Qt("add350","add",200,350,0),Qt("update350a","update",350,350,45000),Qt("rename100","rename",100,350,45000),Qt("update350b","update",350,350,45000),Qt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Qt("add50","add",50,50,0),Qt("add150","add",100,150,0),Qt("add350","add",200,350,0),Qt("add700","add",350,700,0),Qt("update700a","update",700,700,45000),Qt("rename200","rename",200,700,45000),Qt("update700b","update",700,700,45000),Qt("delete700","delete",700,0,150000)]}}});import{spawn as DSe}from"child_process";async function yJ(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw wi(t,r,n);return n}function wi(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var ao=async(e,t,r={})=>new Promise((i,n)=>{let o=DSe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var wp=()=>{};class su{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new su(e,r,i);return await yJ(e,"git",["-c","credential.helper=","-c",`credential.helper=${bJ}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",bJ]),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 wi("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 bJ='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var SJ=S(()=>{wp()});function vp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class QC{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#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 WC(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return LSe.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||vp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await WC(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var LSe;var xJ=S(()=>{Ae();GC();LSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),app:d.object({version:d.string(),entities:d.number().int().nonnegative(),entityCounts:d.array(d.object({entityType:d.string(),count:d.number().int().nonnegative()})).default([])})})});var iS={};Ht(iS,{applyDirectorySyncStressPhase:()=>kJ,cleanupDirectorySyncStress:()=>JSe,listProbeFiles:()=>ja,parseStressRuntimeSample:()=>EJ,removeProbeFiles:()=>iR,runDeployedDirectorySyncStress:()=>HSe,runStressCommand:()=>ao,verifyDirectorySyncStressAccess:()=>KSe});import{chmod as BSe,mkdir as XC,mkdtemp as eR,readFile as jSe,readdir as USe,rename as qSe,rm as kp,writeFile as Kn}from"fs/promises";import{tmpdir as tR}from"os";import{join as St,resolve as rR}from"path";async function HSe(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=oR(r),n=rR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",i));await XC(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);nS({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=tS.parse(e.profile),c=e.plan?rS.parse(e.plan):hJ(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)_J(s);let l=ZSe.parse(e.env??process.env),u=new vJ({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??ao,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),f;try{f=await gJ(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:f};return await GSe(p),p}async function KSe(e){let r=(e.now??(()=>new Date))().toISOString(),i=oR(r),n=rR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`access-check-${i}`));await XC(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);nS({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),_J(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await eR(St(tR(),"brains-ops-directory-sync-access-check-"));try{let l=await su.clone(e.commandRunner??ao,`${o.githubOrg}/${s.contentRepo}`,St(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let f={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Kn(St(n,"access-check.json"),`${JSON.stringify(f,null,2)}
|
|
411
411
|
`),f}finally{await kp(c,{recursive:!0,force:!0})}}async function JSe(e){let t=e.now??(()=>new Date),r=rR(e.artifactsDir??St(e.rootDir,".brains-ops","stress",`cleanup-${oR(t().toISOString())}`));await XC(r,{recursive:!0});let{pilot:i,user:n}=await nR(e.rootDir,e.handle);nS({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let o=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!o)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??ao,a=e.logger??console.info,c=await eR(St(tR(),"brains-ops-directory-sync-cleanup-")),l=St(c,"content");try{let u=await su.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),f=await iR(u.dir),p;if(f>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${f} directory-sync stress probes`);let m=(await ja(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:f,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Kn(St(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
|
|
412
412
|
`),g}finally{await kp(c,{recursive:!0,force:!0})}}class vJ{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new QC({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await eR(St(tR(),"brains-ops-directory-sync-stress-"));let t=St(this.#r,"content");this.#i=St(this.#r,"id_ed25519"),this.#o=St(this.#r,"known_hosts"),this.#a=await this.#m(),await Kn(this.#i,WSe(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await BSe(this.#i,384);let r=await this.#b("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 Kn(this.#o,r.stdout,{mode:384});let i=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=i.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 su.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await ja(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let o=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 Kn(St(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:o,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:vp(s),version:s.version}},null,2)}
|
|
413
413
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:vp(s),version:s.version}}async startMonitoring(){this.#S(),this.#t.start()}async executePhase(e,t){this.#S();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let i=this.#t.healthSamples.length,n=this.#e.now().getTime(),o=await this.#g();if(o?.pending!==0||o.processing!==0)return au(e,"health did not provide a drained queue before the phase");await kJ(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 au(e,"runtime did not pull the phase commit");let l;if(e.operation==="rename"){let m=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let y=await this.#t.waitForStableEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-s,!y)return au(e,`health did not stabilize at ${m} notes`,c,l)}else if(e.operation==="add"||e.operation==="delete"){let m=t.notes+e.targetProbeCount,y=this.#e.now().getTime(),g=await this.#t.waitForEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-y,!g)return au(e,`health did not reach ${m} notes`,c,l)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let u=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(o.completedImports+u,1200000))return au(e,`health did not observe ${u} completed import job(s) with a drained queue`,c,l);let p=this.#t.healthSamples.slice(i).find((m)=>!m.ok);if(p)return au(e,`${p.endpoint} unavailable (${p.status===0?p.error??"unknown":p.status})`,c,l);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,...l===void 0?{}:{persistenceLatencyMs:l}}}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 iR(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(await ja(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=i===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:i,...n?{finalEntities:n.entities,finalNotes:vp(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 ja(t.dir)).length,error:at(r)}}}async stopMonitoring(){await this.#t.stop(),await Kn(St(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
@@ -421,7 +421,7 @@ Update marker: ${t.id}.
|
|
|
421
421
|
`}function oR(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function GSe(e){await Kn(St(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
|
|
422
422
|
`),await Kn(St(e.artifactsDir,"report.md"),QSe(e))}function QSe(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,i=t.map((a)=>a.cpuPercent).sort((a,c)=>a-c),n=t.map((a)=>a.memoryPercent),o=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"}`} | ${wJ(a.commitLatencyMs)} | ${wJ(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${_p(YC(i,0.5))} / ${_p(YC(i,0.95))} / ${_p(YC(i,0.99))} / ${_p(i.at(-1))}`,`- Memory max: ${_p(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: ${o.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(`
|
|
423
423
|
`)}
|
|
424
|
-
`}function YC(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function _p(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function wJ(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var ZSe,MSe,FSe;var oS=S(()=>{Ae();GC();zn();wp();SJ();xJ();wp();ZSe=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1),CONTENT_REPO_ADMIN_TOKEN:d.string().min(1)}),MSe=d.object({servers:d.array(d.object({id:d.number().int(),status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))}),FSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),resources:d.object({queue:d.object({totals:d.object({pending:d.number().int().nonnegative(),processing:d.number().int().nonnegative()}),byType:d.array(d.object({type:d.string(),status:d.string(),count:d.number().int().nonnegative()}))})})})});var IJ=S(()=>{Hs()});var YSe="/usr/local/sbin/brains-health-watchdog",XSe="ai.rizom.brain.watchdog",exe="true",sR,TJ,
|
|
424
|
+
`}function YC(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function _p(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function wJ(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var ZSe,MSe,FSe;var oS=S(()=>{Ae();GC();zn();wp();SJ();xJ();wp();ZSe=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1),CONTENT_REPO_ADMIN_TOKEN:d.string().min(1)}),MSe=d.object({servers:d.array(d.object({id:d.number().int(),status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))}),FSe=d.object({status:d.literal("ready"),operationalStatus:d.literal("operational"),resources:d.object({queue:d.object({totals:d.object({pending:d.number().int().nonnegative(),processing:d.number().int().nonnegative()}),byType:d.array(d.object({type:d.string(),status:d.string(),count:d.number().int().nonnegative()}))})})})});var IJ=S(()=>{Hs()});var YSe="/usr/local/sbin/brains-health-watchdog",XSe="ai.rizom.brain.watchdog",exe="true",sR,TJ,tGe;var AJ=S(async()=>{IJ();sR=`${XSe}=${exe}`,TJ=`#!/usr/bin/env bash
|
|
425
425
|
set -euo pipefail
|
|
426
426
|
umask 077
|
|
427
427
|
|
|
@@ -480,7 +480,7 @@ while read -r container_id; do
|
|
|
480
480
|
logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
|
|
481
481
|
docker restart "$container_id"
|
|
482
482
|
done < <(docker ps --filter health=unhealthy --filter label=${sR} --format '{{.ID}}')
|
|
483
|
-
`,
|
|
483
|
+
`,tGe=`[Unit]
|
|
484
484
|
Description=Restart persistently unhealthy Brain containers
|
|
485
485
|
After=docker.service
|
|
486
486
|
Requires=docker.service
|
|
@@ -721,7 +721,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
721
721
|
`).replace(/\\n/g,`
|
|
722
722
|
`).trimEnd()}
|
|
723
723
|
`}var PJ,sxe;var dR=S(async()=>{Ae();$J();zn();wp();await AJ();PJ=d.object({HCLOUD_TOKEN:d.string().min(1),KAMAL_SSH_PRIVATE_KEY:d.string().min(1)}),sxe=d.object({servers:d.array(d.object({status:d.string(),public_net:d.object({ipv4:d.object({ip:d.string().min(1)})})}))})});import{parseArgs as x9}from"util";function ht(e){return e}class Ip extends Error{constructor(e){super(e);this.name="CliUsageError"}}function w9(e,t){let r={...t};for(let i of e)for(let[n,o]of Object.entries(i.flags??{})){let s=r[n];if(s===void 0){r[n]=o;continue}if(s.type!==o.type||s.short!==o.short||s.default!==o.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function v9(e){let t={};for(let[r,i]of Object.entries(e))t[r]={type:i.type,...i.short!==void 0?{short:i.short}:{},...i.default!==void 0?{default:i.default}:{}};return t}function _9(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 mR(e,t){let r=w9(t.commands,t.globalFlags??{}),i,n;try{({values:i,positionals:n}=x9({args:e,options:v9(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(_9(s))throw new Ip(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&i.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&i.version===!0)return{command:"version",args:[],flags:{version:!0}};let o={};for(let[s,a]of Object.entries(r)){let c=i[s];if(typeof c==="string"&&a.type==="string")o[s]=c;else if(typeof c==="boolean"&&a.type==="boolean")o[s]=c}return{command:n[0]??"help",args:n.slice(1),flags:o}}function hR(e){let t=e.reduce((r,i)=>Math.max(r,i.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function k9(e){return hR(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function E9(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",i=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${i}`}function gR(e){return hR(Object.entries(e).map(([t,r])=>({label:E9(t,r),description:r.description})))}function yR(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function I9(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 T9(e){let t=[],r=new Map;for(let n of e){let o=n.flags??{};if(Object.keys(o).length===0)continue;let s=I9(o),a=r.get(s);if(a){a.names.push(n.name);continue}let c={names:[n.name],flags:o};r.set(s,c),t.push(c)}let i=[];for(let n of t)i.push("",`${n.names.join(" / ")} options:`),i.push(...gR(n.flags));return i}function bR(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...k9(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...gR(e.globalFlags));return t.push(...T9(e.commands)),t.join(`
|
|
724
|
-
`)}function SR(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 ft(e,t){let r=e[t];return typeof r==="string"?r:void 0}function vs(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var Tp={name:"@rizom/ops",version:"0.2.0-alpha.590",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/auth-service":"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 rW,mkdirSync as nW,readFileSync as Gx,writeFileSync as Qx}from"fs";import{dirname as iW,join as Az}from"path";function uS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function At(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 Yt(e,t,r=""){let i=uS(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=i?`length=${n}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;if(!i)throw TypeError(l);throw RangeError(l)}return e}function ki(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(At(e.outputLen),At(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 Ap(e,t){Yt(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function $p(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function kr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Fa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function En(e,t){return e<<32-t|e>>>t}function Xe(e,t){return e<<t|e>>>32-t>>>0}var $9=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function C9(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function R9(e){for(let t=0;t<e.length;t++)e[t]=C9(e[t]);return e}var dS=$9?(e)=>e:R9,wR=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),O9=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Cp(e){if(Yt(e),wR)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=O9[e[r]];return t}var _i={_0:48,_9:57,A:65,F:70,a:97,f:102};function xR(e){if(e>=_i._0&&e<=_i._9)return e-_i._0;if(e>=_i.A&&e<=_i.F)return e-(_i.A-10);if(e>=_i.a&&e<=_i.f)return e-(_i.a-10);return}function mu(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(wR)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 i=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){let s=xR(e.charCodeAt(o)),a=xR(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}i[n]=s*16+a}return i}function P9(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function fS(e,t=""){if(typeof e==="string")return P9(e);return Yt(e,void 0,t)}function pS(...e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];Yt(n),t+=n.length}let r=new Uint8Array(t);for(let i=0,n=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function Rp(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 mS(e,t={}){let r=(n,o)=>e(o).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.canXOF=i.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Ei(e=32){At(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 hS=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});class gS{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ki(e),Yt(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,i=new Uint8Array(r);i.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<i.length;n++)i[n]^=54;this.iHash.update(i),this.oHash=e.create();for(let n=0;n<i.length;n++)i[n]^=106;this.oHash.update(i),kr(i)}update(e){return Ma(this),this.iHash.update(e),this}digestInto(e){Ma(this),Ap(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:i,destroyed:n,blockLen:o,outputLen:s}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,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 Vn=(()=>{let e=(t,r,i)=>new gS(t,r).update(i).digest();return e.create=(t,r)=>new gS(t,r),e})();function hu(e,t,r){if(ki(e),r===void 0)r=new Uint8Array(e.outputLen);return Vn(e,r,t)}var yS=Uint8Array.of(0),vR=Uint8Array.of();function bS(e,t,r,i=32){ki(e),At(i,"length"),Yt(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(i>255*n)throw Error("Length must be <= 255*HashLen");let o=Math.ceil(i/n);if(r===void 0)r=vR;else Yt(r,void 0,"info");let s=new Uint8Array(o*n),a=Vn.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)yS[0]=u+1,c.update(u===0?vR:l).update(r).update(yS).digestInto(l),s.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),kr(l,yS),s.slice(0,i)}var lo=(e,t,r,i,n)=>bS(e,hu(e,t,r),i,n);function _R(e,t,r){return e&t^~e&r}function kR(e,t,r){return e&t^e&r^t&r}class Op{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Fa(this.buffer)}update(e){Ma(this),Yt(e);let{view:t,buffer:r,blockLen:i}=this,n=e.length;for(let o=0;o<n;){let s=Math.min(i-this.pos,n-o);if(s===i){let a=Fa(e);for(;i<=n-o;o+=i)this.process(a,o);continue}if(r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ma(this),Ap(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:o}=this;if(t[o++]=128,kr(this.buffer.subarray(o)),this.padOffset>i-o)this.process(r,0),o=0;for(let u=o;u<i;u++)t[u]=0;r.setBigUint64(i-8,BigInt(this.length*8),n),this.process(r,0);let s=Fa(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)s.setUint32(4*u,l[u],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:i,finished:n,destroyed:o,pos:s}=this;if(e.destroyed=o,e.finished=n,e.length=i,e.pos=s,i%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var Ii=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Pp=BigInt(4294967295),ER=BigInt(32);function z9(e,t=!1){if(t)return{h:Number(e&Pp),l:Number(e>>ER&Pp)};return{h:Number(e>>ER&Pp)|0,l:Number(e&Pp)|0}}function IR(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=z9(e[o],t);[i[o],n[o]]=[s,a]}return[i,n]}var SS=(e,t,r)=>e>>>r,xS=(e,t,r)=>e<<32-r|t>>>r,_s=(e,t,r)=>e>>>r|t<<32-r,ks=(e,t,r)=>e<<32-r|t>>>r,gu=(e,t,r)=>e<<64-r|t>>>r-32,yu=(e,t,r)=>e>>>r-32|t<<64-r;function Wn(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var TR=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),AR=(e,t,r,i)=>t+r+i+(e/4294967296|0)|0,$R=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),CR=(e,t,r,i,n)=>t+r+i+n+(e/4294967296|0)|0,RR=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),OR=(e,t,r,i,n,o)=>t+r+i+n+o+(e/4294967296|0)|0;var D9=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]),uo=new Uint32Array(64);class PR extends Op{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:i,E:n,F:o,G:s,H:a}=this;return[e,t,r,i,n,o,s,a]}set(e,t,r,i,n,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)uo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let f=uo[u-15],p=uo[u-2],m=En(f,7)^En(f,18)^f>>>3,y=En(p,17)^En(p,19)^p>>>10;uo[u]=y+uo[u-7]+m+uo[u-16]|0}let{A:r,B:i,C:n,D:o,E:s,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let f=En(s,6)^En(s,11)^En(s,25),p=l+f+_R(s,a,c)+D9[u]+uo[u]|0,y=(En(r,2)^En(r,13)^En(r,22))+kR(r,i,n)|0;l=c,c=a,a=s,s=o+p|0,o=n,n=i,i=r,r=p+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,i,n,o,s,a,c,l)}roundClean(){kr(uo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}}class zR extends PR{A=Ii[0]|0;B=Ii[1]|0;C=Ii[2]|0;D=Ii[3]|0;E=Ii[4]|0;F=Ii[5]|0;G=Ii[6]|0;H=Ii[7]|0;constructor(){super(32)}}var NR=(()=>IR(["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))))(),L9=(()=>NR[0])(),B9=(()=>NR[1])(),fo=new Uint32Array(80),po=new Uint32Array(80);class DR extends Op{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:f,Gh:p,Gl:m,Hh:y,Hl:g}=this;return[e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g]}set(e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=i|0,this.Ch=n|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let T=0;T<16;T++,t+=4)fo[T]=e.getUint32(t),po[T]=e.getUint32(t+=4);for(let T=16;T<80;T++){let A=fo[T-15]|0,z=po[T-15]|0,j=_s(A,z,1)^_s(A,z,8)^SS(A,z,7),E=ks(A,z,1)^ks(A,z,8)^xS(A,z,7),F=fo[T-2]|0,D=po[T-2]|0,H=_s(F,D,19)^gu(F,D,61)^SS(F,D,6),X=ks(F,D,19)^yu(F,D,61)^xS(F,D,6),Z=$R(E,X,po[T-7],po[T-16]),P=CR(Z,j,H,fo[T-7],fo[T-16]);fo[T]=P|0,po[T]=Z|0}let{Ah:r,Al:i,Bh:n,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:f,Fh:p,Fl:m,Gh:y,Gl:g,Hh:b,Hl:_}=this;for(let T=0;T<80;T++){let A=_s(u,f,14)^_s(u,f,18)^gu(u,f,41),z=ks(u,f,14)^ks(u,f,18)^yu(u,f,41),j=u&p^~u&y,E=f&m^~f&g,F=RR(_,z,E,B9[T],po[T]),D=OR(F,b,A,j,L9[T],fo[T]),H=F|0,X=_s(r,i,28)^gu(r,i,34)^gu(r,i,39),Z=ks(r,i,28)^yu(r,i,34)^yu(r,i,39),P=r&n^r&s^n&s,N=i&o^i&a^o&a;b=y|0,_=g|0,y=p|0,g=m|0,p=u|0,m=f|0,{h:u,l:f}=Wn(c|0,l|0,D|0,H|0),c=s|0,l=a|0,s=n|0,a=o|0,n=r|0,o=i|0;let I=TR(H,Z,N);r=AR(I,D,X,P),i=I|0}({h:r,l:i}=Wn(this.Ah|0,this.Al|0,r|0,i|0)),{h:n,l:o}=Wn(this.Bh|0,this.Bl|0,n|0,o|0),{h:s,l:a}=Wn(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l}=Wn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:f}=Wn(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:m}=Wn(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:g}=Wn(this.Gh|0,this.Gl|0,y|0,g|0),{h:b,l:_}=Wn(this.Hh|0,this.Hl|0,b|0,_|0),this.set(r,i,n,o,s,a,c,l,u,f,p,m,y,g,b,_)}roundClean(){kr(fo,po)}destroy(){this.destroyed=!0,kr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class LR extends DR{Ah=Xt[0]|0;Al=Xt[1]|0;Bh=Xt[2]|0;Bl=Xt[3]|0;Ch=Xt[4]|0;Cl=Xt[5]|0;Dh=Xt[6]|0;Dl=Xt[7]|0;Eh=Xt[8]|0;El=Xt[9]|0;Fh=Xt[10]|0;Fl=Xt[11]|0;Gh=Xt[12]|0;Gl=Xt[13]|0;Hh=Xt[14]|0;Hl=Xt[15]|0;constructor(){super(64)}}var $t=mS(()=>new zR,hS(1));var zp=mS(()=>new LR,hS(3));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function jp(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function _S(e){if(!jp(e))throw TypeError("Uint8Array expected")}function ZR(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 MR(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function mo(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function Su(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function Dp(e){if(!Array.isArray(e))throw TypeError("array expected")}function Lp(e,t){if(!ZR(!0,t))throw TypeError(`${e}: array of strings expected`)}function kS(e,t){if(!ZR(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Vr(...e){let t=(o)=>o,r=(o,s)=>(a)=>o(s(a)),i=e.map((o)=>o.encode).reduceRight(r,t),n=e.map((o)=>o.decode).reduce(r,t);return{encode:i,decode:n}}function Wr(e){let t=typeof e==="string"?e.split(""):e,r=t.length;Lp("alphabet",t);let i=new Map(t.map((n,o)=>[n,o]));return{encode:(n)=>(Dp(n),n.map((o)=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${e}`);return t[o]})),decode:(n)=>(Dp(n),n.map((o)=>{mo("alphabet.decode",o);let s=i.get(o);if(s===void 0)throw Error(`Unknown letter: "${o}". Allowed: ${e}`);return s}))}}function Gr(e=""){return mo("join",e),{encode:(t)=>(Lp("join.decode",t),t.join(e)),decode:(t)=>(mo("join.decode",t),t.split(e))}}function Up(e,t="="){return Su(e),mo("padding",t),{encode(r){Lp("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){Lp("padding.decode",r);let i=r.length;if(i*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;i>0&&r[i-1]===t;i--)if((i-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,i)}}}function FR(e){return MR(e),{encode:(t)=>t,decode:(t)=>e(t)}}function BR(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(Dp(e),!e.length)return[];let i=0,n=[],o=Array.from(e,(a)=>{if(Su(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=o.length;while(!0){let a=0,c=!0;for(let l=i;l<s;l++){let u=o[l],f=t*a,p=f+u;if(!Number.isSafeInteger(p)||f/t!==a||p-u!==f)throw Error("convertRadix: carry overflow");let m=p/r;a=p%r;let y=Math.floor(m);if(o[l]=y,!Number.isSafeInteger(y)||y*r+a!==p)throw Error("convertRadix: carry overflow");if(!c)continue;else if(!y)i=l;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 HR=(e,t)=>t===0?e:HR(t,e%t),Bp=(e,t)=>e+(t-HR(e,t)),Np=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function wS(e,t,r,i){if(Dp(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if(Bp(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${Bp(t,r)}`);let n=0,o=0,s=Np[t],a=Np[r]-1,c=[];for(let l of e){if(Su(l),l>=s)throw Error(`convertRadix2: invalid data word=${l} from=${t}`);if(n=n<<t|l,o+t>32)throw Error(`convertRadix2: carry overflow pos=${o} from=${t}`);o+=t;for(;o>=r;o-=r)c.push((n>>o-r&a)>>>0);let u=Np[o];if(u===void 0)throw Error("invalid carry");n&=u-1}if(n=n<<r-o&a,!i&&o>=t)throw Error("Excess padding");if(!i&&n>0)throw Error(`Non-zero padding: ${n}`);if(i&&o>0)c.push(n>>>0);return c}function j9(e){Su(e);let t=256;return{encode:(r)=>{if(!jp(r))throw TypeError("radix.encode input should be Uint8Array");return BR(Array.from(r),t,e)},decode:(r)=>(kS("radix.decode",r),Uint8Array.from(BR(r,e,t)))}}function cn(e,t=!1){if(Su(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if(Bp(8,e)>32||Bp(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!jp(r))throw TypeError("radix2.encode input should be Uint8Array");return wS(Array.from(r),8,e,!t)},decode:(r)=>(kS("radix2.decode",r),Uint8Array.from(wS(r,e,8,t)))}}function jR(e){return MR(e),function(...t){try{return e.apply(null,t)}catch(r){}}}var Pxe=Object.freeze(Vr(cn(4),Wr("0123456789ABCDEF"),Gr(""))),zxe=Object.freeze(Vr(cn(5),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Up(5),Gr(""))),Nxe=Object.freeze(Vr(cn(5),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Gr(""))),Dxe=Object.freeze(Vr(cn(5),Wr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Up(5),Gr(""))),Lxe=Object.freeze(Vr(cn(5),Wr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Gr(""))),Bxe=Object.freeze(Vr(cn(5),Wr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Gr(""),FR((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),KR=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),U9=/[\t\n\f\r ]/,JR=(e,t)=>{mo("base64",e);let r=t?"base64url":"base64";if(e.length>0&&U9.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},ES=Object.freeze(KR?{encode(e){return _S(e),e.toBase64()},decode(e){return JR(e,!1)}}:Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Up(6),Gr(""))),pr=Object.freeze(Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Gr(""))),jxe=Object.freeze(KR?{encode(e){return _S(e),e.toBase64({alphabet:"base64url"})},decode(e){return JR(e,!0)}}:Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Up(6),Gr(""))),Uxe=Object.freeze(Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Gr(""))),IS=(e)=>Vr(j9(58),Wr(e),Gr("")),qxe=Object.freeze(IS("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Zxe=Object.freeze(IS("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),Mxe=Object.freeze(IS("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"));var vS=Vr(Wr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Gr("")),UR=[996825010,642813549,513874426,1027748829,705979059];function bu(e){let t=e>>25,r=(e&33554431)<<5;for(let i=0;i<UR.length;i++)if((t>>i&1)===1)r^=UR[i];return r}function qR(e,t,r=1){let i=e.length,n=1;for(let o=0;o<i;o++){let s=e.charCodeAt(o);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=bu(n)^s>>5}n=bu(n);for(let o=0;o<i;o++)n=bu(n)^e.charCodeAt(o)&31;for(let o of t)n=bu(n)^o;for(let o=0;o<6;o++)n=bu(n);return n^=r,vS.encode(wS([n%Np[30]],30,5,!1))}function VR(e){let t=e==="bech32"?1:734539939,r=cn(5),i=r.decode,n=r.encode,o=jR(i);function s(f,p,m=90){if(mo("bech32.encode prefix",f),jp(p))p=Array.from(p);kS("bech32.encode",p);let y=f.length;if(y===0)throw TypeError(`Invalid prefix length ${y}`);let g=y+7+p.length;if(m!==!1&&g>m)throw TypeError(`Length ${g} exceeds limit ${m}`);let b=f.toLowerCase(),_=qR(b,p,t);return`${b}1${vS.encode(p)}${_}`}function a(f,p=90){mo("bech32.decode input",f);let m=f.length;if(m<8||p!==!1&&m>p)throw TypeError(`invalid string length: ${m} (${f}). Expected (8..${p})`);let y=f.toLowerCase();if(f!==y&&f!==f.toUpperCase())throw Error("String must be lowercase or uppercase");let g=y.lastIndexOf("1");if(g===0||g===-1)throw Error('Letter "1" must be present between prefix and data only');let b=y.slice(0,g),_=y.slice(g+1);if(_.length<6)throw Error("Data must be at least 6 characters long");let T=vS.decode(_).slice(0,-6),A=qR(b,T,t);if(!_.endsWith(A))throw Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:b,words:T}}let c=jR(a);function l(f){let{prefix:p,words:m}=a(f,!1);return{prefix:p,words:m,bytes:i(m)}}function u(f,p){return s(f,n(p))}return{encode:s,decode:a,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:i,fromWordsUnsafe:o,toWords:n}}var Qr=Object.freeze(VR("bech32")),Fxe=Object.freeze(VR("bech32m"));var q9=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Z9={encode(e){return _S(e),e.toHex()},decode(e){return mo("hex",e),Uint8Array.fromHex(e)}},Hxe=Object.freeze(q9?Z9:Vr(cn(4),Wr("0123456789abcdef"),Gr(""),FR((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 F9(e,t,r,i){ki(e);let n=Rp({dkLen:32,asyncTick:10},i),{c:o,dkLen:s,asyncTick:a}=n;if(At(o,"c"),At(s,"dkLen"),At(a,"asyncTick"),o<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=fS(t,"password"),l=fS(r,"salt"),u=new Uint8Array(s),f=Vn.create(e,c),p=f._cloneInto().update(l);return{c:o,dkLen:s,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function H9(e,t,r,i,n){if(e.destroy(),t.destroy(),i)i.destroy();return kr(n),r}function TS(e,t,r,i){let{c:n,dkLen:o,DK:s,PRF:a,PRFSalt:c}=F9(e,t,r,i),l,u=new Uint8Array(4),f=Fa(u),p=new Uint8Array(a.outputLen);for(let m=1,y=0;y<o;m++,y+=a.outputLen){let g=s.subarray(y,y+a.outputLen);f.setInt32(0,m,!1),(l=c._cloneInto(l)).update(u).digestInto(p),g.set(p.subarray(0,g.length));for(let b=1;b<n;b++){a._cloneInto(l).update(p).digestInto(p);for(let _=0;_<g.length;_++)g[_]^=p[_]}}return H9(a,c,s,l,p)}function WR(e,t,r,i,n,o){let s=e[t++]^r[i++],a=e[t++]^r[i++],c=e[t++]^r[i++],l=e[t++]^r[i++],u=e[t++]^r[i++],f=e[t++]^r[i++],p=e[t++]^r[i++],m=e[t++]^r[i++],y=e[t++]^r[i++],g=e[t++]^r[i++],b=e[t++]^r[i++],_=e[t++]^r[i++],T=e[t++]^r[i++],A=e[t++]^r[i++],z=e[t++]^r[i++],j=e[t++]^r[i++],E=s,F=a,D=c,H=l,X=u,Z=f,P=p,N=m,I=y,O=g,R=b,M=_,L=T,V=A,k=z,te=j;for(let ue=0;ue<8;ue+=2)X^=Xe(E+L|0,7),I^=Xe(X+E|0,9),L^=Xe(I+X|0,13),E^=Xe(L+I|0,18),O^=Xe(Z+F|0,7),V^=Xe(O+Z|0,9),F^=Xe(V+O|0,13),Z^=Xe(F+V|0,18),k^=Xe(R+P|0,7),D^=Xe(k+R|0,9),P^=Xe(D+k|0,13),R^=Xe(P+D|0,18),H^=Xe(te+M|0,7),N^=Xe(H+te|0,9),M^=Xe(N+H|0,13),te^=Xe(M+N|0,18),F^=Xe(E+H|0,7),D^=Xe(F+E|0,9),H^=Xe(D+F|0,13),E^=Xe(H+D|0,18),P^=Xe(Z+X|0,7),N^=Xe(P+Z|0,9),X^=Xe(N+P|0,13),Z^=Xe(X+N|0,18),M^=Xe(R+O|0,7),I^=Xe(M+R|0,9),O^=Xe(I+M|0,13),R^=Xe(O+I|0,18),L^=Xe(te+k|0,7),V^=Xe(L+te|0,9),k^=Xe(V+L|0,13),te^=Xe(k+V|0,18);n[o++]=s+E|0,n[o++]=a+F|0,n[o++]=c+D|0,n[o++]=l+H|0,n[o++]=u+X|0,n[o++]=f+Z|0,n[o++]=p+P|0,n[o++]=m+N|0,n[o++]=y+I|0,n[o++]=g+O|0,n[o++]=b+R|0,n[o++]=_+M|0,n[o++]=T+L|0,n[o++]=A+V|0,n[o++]=z+k|0,n[o++]=j+te|0}function AS(e,t,r,i,n){let o=i+0,s=i+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++,o+=16,t+=16){if(WR(r,s,e,t,r,o),a>0)s+=16;WR(r,o,e,t+=16,r,s)}}function K9(e,t,r){let i=Rp({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:o,p:s,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=i;if(At(n,"N"),At(o,"r"),At(s,"p"),At(a,"dkLen"),At(c,"asyncTick"),At(l,"maxmem"),u!==void 0&&typeof u!=="function")throw Error("progressCb must be a function");let f=128*o,p=f/4,m=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>m)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(m-1)*32/f)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(m-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let y=f*(n+s+1);if(y>l)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+y+", maxmem="+l);let g=TS($t,e,t,{c:1,dkLen:f*s}),b=$p(g),_=$p(new Uint8Array(f*n)),T=$p(new Uint8Array(f)),A=()=>{};if(u){let z=2*n*s,j=Math.max(Math.floor(z/1e4),1),E=0;A=()=>{if(E++,u&&(!(E%j)||E===z))u(E/z)}}return{N:n,r:o,p:s,dkLen:a,blockSize32:p,V:_,B32:b,B:g,tmp:T,blockMixCb:A,asyncTick:c}}function J9(e,t,r,i,n){let o=TS($t,e,r,{c:1,dkLen:t});return kr(r,i,n),o}function $S(e,t,r){let{N:i,r:n,p:o,dkLen:s,blockSize32:a,V:c,B32:l,B:u,tmp:f,blockMixCb:p}=K9(e,t,r);dS(l);for(let m=0;m<o;m++){let y=a*m;for(let g=0;g<a;g++)c[g]=l[y+g];for(let g=0,b=0;g<i-1;g++)AS(c,b,c,b+=a,n),p();AS(c,(i-1)*a,l,y,n),p();for(let g=0;g<i;g++){let b=(l[y+a-16]&i-1)>>>0;for(let _=0;_<a;_++)f[_]=l[y+_]^c[b*a+_];AS(f,0,l,y,n),p()}}return dS(l),J9(e,s,u,c,f)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function V9(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function qp(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function Ha(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 jt(e,t,r=""){let i=V9(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=i?`length=${n}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;if(!i)throw TypeError(l);throw RangeError(l)}return e}function CS(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 GR(e,t,r=!1){jt(e,void 0,"output");let i=t.outputLen;if(e.length<i)throw RangeError("digestInto() expects output buffer of length at least "+i);if(r&&!Ka(e))throw Error("invalid output, must be aligned")}function Gn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function In(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function W9(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Es=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),G9=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;var Q9=(e)=>{for(let t=0;t<e.length;t++)e[t]=G9(e[t]);return e},Ti=Es?(e)=>e:Q9;function QR(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function YR(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function XR(e,t,r){let i=t,n=r||(()=>[]),o=(a,c)=>i(c,...n(a)).update(a).digest(),s=i(new Uint8Array(e),...n(new Uint8Array(0)));return o.outputLen=s.outputLen,o.blockLen=s.blockLen,o.create=(a,...c)=>i(a,...c),o}var eO=(e,t)=>{function r(i,...n){if(jt(i,void 0,"key"),e.nonceLength!==void 0){let u=n[0];jt(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let o=e.tagLength;if(o&&n[1]!==void 0)jt(n[1],void 0,"AAD");let s=t(i,...n),a=(u,f)=>{if(f!==void 0){if(u!==2)throw Error("cipher output not supported");jt(f,void 0,"output")}},c=!1;return{encrypt(u,f){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,jt(u),a(s.encrypt.length,f),s.encrypt(u,f)},decrypt(u,f){if(jt(u),o&&u.length<o)throw Error('"ciphertext" expected length bigger than tagLength='+o);return a(s.decrypt.length,f),s.decrypt(u,f)}}}return Object.assign(r,e),r};function xu(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(jt(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Ka(t))throw Error("invalid output, must be aligned");return t}function tO(e,t,r){Ha(e),Ha(t),qp(r);let i=new Uint8Array(16),n=W9(i);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),i}function Ka(e){return e.byteOffset%4===0}function Ja(e){return Uint8Array.from(jt(e))}var nO=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),Y9=(()=>Ti(Gn(nO("expand 16-byte k"))))(),X9=(()=>Ti(Gn(nO("expand 32-byte k"))))();function et(e,t){return e<<t|e>>>32-t}var wu=64,eV=16,RS=(()=>4294967295)(),rO=Uint32Array.of();function tV(e,t,r,i,n,o,s,a){let c=n.length,l=new Uint8Array(wu),u=Gn(l),f=Es&&Ka(n)&&Ka(o),p=f?Gn(n):rO,m=f?Gn(o):rO;if(!Es){for(let y=0;y<c;s++){if(e(t,r,i,u,s,a),Ti(u),s>=RS)throw Error("arx: counter overflow");let g=Math.min(wu,c-y);for(let b=0,_;b<g;b++)_=y+b,o[_]=n[_]^l[b];y+=g}return}for(let y=0;y<c;s++){if(e(t,r,i,u,s,a),s>=RS)throw Error("arx: counter overflow");let g=Math.min(wu,c-y);if(f&&g===wu){let b=y/4;if(y%4!==0)throw Error("arx: invalid block position");for(let _=0,T;_<eV;_++)T=b+_,m[T]=p[T]^u[_];y+=wu;continue}for(let b=0,_;b<g;b++)_=y+b,o[_]=n[_]^l[b];y+=g}}function iO(e,t){let{allowShortKeys:r,extendNonceFn:i,counterLength:n,counterRight:o,rounds:s}=QR({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return Ha(n),Ha(s),qp(o),qp(r),(a,c,l,u,f=0)=>{jt(a,void 0,"key"),jt(c,void 0,"nonce"),jt(l,void 0,"data");let p=l.length;if(u=xu(p,u,!1),Ha(f),f<0||f>=RS)throw Error("arx: counter overflow");let m=[],y=a.length,g,b;if(y===32)m.push(g=Ja(a)),b=X9;else if(y===16&&r)g=new Uint8Array(32),g.set(a),g.set(a,16),b=Y9,m.push(g);else throw jt(a,32,"arx key"),Error("invalid key size");if(!Es||!Ka(c))m.push(c=Ja(c));let _=Gn(g);if(i){if(c.length!==24)throw Error("arx: extended nonce must be 24 bytes");let z=c.subarray(0,16);if(Es)i(b,_,Gn(z),_);else{let j=Ti(Uint32Array.from(b));i(j,_,Gn(z),_),In(j),Ti(_)}c=c.subarray(16)}else if(!Es)Ti(_);let T=16-n;if(T!==c.length)throw Error(`arx: nonce must be ${T} or 16 bytes`);if(T!==12){let z=new Uint8Array(12);z.set(c,o?0:12-c.length),c=z,m.push(c)}let A=Ti(Gn(c));try{return tV(e,b,_,A,l,u,f,s),u}finally{In(...m)}}}function er(e,t){return e[t++]&255|(e[t++]&255)<<8}class oO{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=Ja(jt(e,32,"key"));let t=er(e,0),r=er(e,2),i=er(e,4),n=er(e,6),o=er(e,8),s=er(e,10),a=er(e,12),c=er(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>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 l=0;l<8;l++)this.pad[l]=er(e,16+2*l)}process(e,t,r=!1){let i=r?0:2048,{h:n,r:o}=this,s=o[0],a=o[1],c=o[2],l=o[3],u=o[4],f=o[5],p=o[6],m=o[7],y=o[8],g=o[9],b=er(e,t+0),_=er(e,t+2),T=er(e,t+4),A=er(e,t+6),z=er(e,t+8),j=er(e,t+10),E=er(e,t+12),F=er(e,t+14),D=n[0]+(b&8191),H=n[1]+((b>>>13|_<<3)&8191),X=n[2]+((_>>>10|T<<6)&8191),Z=n[3]+((T>>>7|A<<9)&8191),P=n[4]+((A>>>4|z<<12)&8191),N=n[5]+(z>>>1&8191),I=n[6]+((z>>>14|j<<2)&8191),O=n[7]+((j>>>11|E<<5)&8191),R=n[8]+((E>>>8|F<<8)&8191),M=n[9]+(F>>>5|i),L=0,V=L+D*s+H*(5*g)+X*(5*y)+Z*(5*m)+P*(5*p);L=V>>>13,V&=8191,V+=N*(5*f)+I*(5*u)+O*(5*l)+R*(5*c)+M*(5*a),L+=V>>>13,V&=8191;let k=L+D*a+H*s+X*(5*g)+Z*(5*y)+P*(5*m);L=k>>>13,k&=8191,k+=N*(5*p)+I*(5*f)+O*(5*u)+R*(5*l)+M*(5*c),L+=k>>>13,k&=8191;let te=L+D*c+H*a+X*s+Z*(5*g)+P*(5*y);L=te>>>13,te&=8191,te+=N*(5*m)+I*(5*p)+O*(5*f)+R*(5*u)+M*(5*l),L+=te>>>13,te&=8191;let ue=L+D*l+H*c+X*a+Z*s+P*(5*g);L=ue>>>13,ue&=8191,ue+=N*(5*y)+I*(5*m)+O*(5*p)+R*(5*f)+M*(5*u),L+=ue>>>13,ue&=8191;let C=L+D*u+H*l+X*c+Z*a+P*s;L=C>>>13,C&=8191,C+=N*(5*g)+I*(5*y)+O*(5*m)+R*(5*p)+M*(5*f),L+=C>>>13,C&=8191;let be=L+D*f+H*u+X*l+Z*c+P*a;L=be>>>13,be&=8191,be+=N*s+I*(5*g)+O*(5*y)+R*(5*m)+M*(5*p),L+=be>>>13,be&=8191;let Ee=L+D*p+H*f+X*u+Z*l+P*c;L=Ee>>>13,Ee&=8191,Ee+=N*a+I*s+O*(5*g)+R*(5*y)+M*(5*m),L+=Ee>>>13,Ee&=8191;let Ce=L+D*m+H*p+X*f+Z*u+P*l;L=Ce>>>13,Ce&=8191,Ce+=N*c+I*a+O*s+R*(5*g)+M*(5*y),L+=Ce>>>13,Ce&=8191;let Re=L+D*y+H*m+X*p+Z*f+P*u;L=Re>>>13,Re&=8191,Re+=N*l+I*c+O*a+R*s+M*(5*g),L+=Re>>>13,Re&=8191;let _e=L+D*g+H*y+X*m+Z*p+P*f;L=_e>>>13,_e&=8191,_e+=N*u+I*l+O*c+R*a+M*s,L+=_e>>>13,_e&=8191,L=(L<<2)+L|0,L=L+V|0,V=L&8191,L=L>>>13,k+=L,n[0]=V,n[1]=k,n[2]=te,n[3]=ue,n[4]=C,n[5]=be,n[6]=Ee,n[7]=Ce,n[8]=Re,n[9]=_e}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=i,i=e[s]>>>13,e[s]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+i,i=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(i^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 o=e[0]+t[0];e[0]=o&65535;for(let s=1;s<8;s++)o=(e[s]+t[s]|0)+(o>>>16)|0,e[s]=o&65535;In(r)}update(e){CS(this),jt(e),e=Ja(e);let{buffer:t,blockLen:r}=this,i=e.length;for(let n=0;n<i;){let o=Math.min(r-this.pos,i-n);if(o===r){for(;r<=i-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,In(this.h,this.r,this.buffer,this.pad)}digestInto(e){CS(this),GR(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:i}=this;if(i){t[i++]=1;for(;i<16;i++)t[i]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var sO=XR(32,(e)=>new oO(e));function rV(e,t,r,i,n,o=20){let s=e[0],a=e[1],c=e[2],l=e[3],u=t[0],f=t[1],p=t[2],m=t[3],y=t[4],g=t[5],b=t[6],_=t[7],T=n,A=r[0],z=r[1],j=r[2],E=s,F=a,D=c,H=l,X=u,Z=f,P=p,N=m,I=y,O=g,R=b,M=_,L=T,V=A,k=z,te=j;for(let C=0;C<o;C+=2)E=E+X|0,L=et(L^E,16),I=I+L|0,X=et(X^I,12),E=E+X|0,L=et(L^E,8),I=I+L|0,X=et(X^I,7),F=F+Z|0,V=et(V^F,16),O=O+V|0,Z=et(Z^O,12),F=F+Z|0,V=et(V^F,8),O=O+V|0,Z=et(Z^O,7),D=D+P|0,k=et(k^D,16),R=R+k|0,P=et(P^R,12),D=D+P|0,k=et(k^D,8),R=R+k|0,P=et(P^R,7),H=H+N|0,te=et(te^H,16),M=M+te|0,N=et(N^M,12),H=H+N|0,te=et(te^H,8),M=M+te|0,N=et(N^M,7),E=E+Z|0,te=et(te^E,16),R=R+te|0,Z=et(Z^R,12),E=E+Z|0,te=et(te^E,8),R=R+te|0,Z=et(Z^R,7),F=F+P|0,L=et(L^F,16),M=M+L|0,P=et(P^M,12),F=F+P|0,L=et(L^F,8),M=M+L|0,P=et(P^M,7),D=D+N|0,V=et(V^D,16),I=I+V|0,N=et(N^I,12),D=D+N|0,V=et(V^D,8),I=I+V|0,N=et(N^I,7),H=H+X|0,k=et(k^H,16),O=O+k|0,X=et(X^O,12),H=H+X|0,k=et(k^H,8),O=O+k|0,X=et(X^O,7);let ue=0;i[ue++]=s+E|0,i[ue++]=a+F|0,i[ue++]=c+D|0,i[ue++]=l+H|0,i[ue++]=u+X|0,i[ue++]=f+Z|0,i[ue++]=p+P|0,i[ue++]=m+N|0,i[ue++]=y+I|0,i[ue++]=g+O|0,i[ue++]=b+R|0,i[ue++]=_+M|0,i[ue++]=T+L|0,i[ue++]=A+V|0,i[ue++]=z+k|0,i[ue++]=j+te|0}var nV=iO(rV,{counterRight:!1,counterLength:4,allowShortKeys:!1});var iV=new Uint8Array(16),aO=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(iV.subarray(r))},oV=new Uint8Array(32);function cO(e,t,r,i,n){if(n!==void 0)jt(n,void 0,"AAD");let o=e(t,r,oV),s=tO(i.length,n?n.length:0,!0),a=sO.create(o);if(n)aO(a,n);aO(a,i),a.update(s);let c=a.digest();return In(o,s),c}var sV=(e)=>(t,r,i)=>({encrypt(o,s){let a=o.length;s=xu(a+16,s,!1),s.set(o);let c=s.subarray(0,-16);e(t,r,c,c,1);let l=cO(e,t,r,c,i);return s.set(l,a),In(l),s},decrypt(o,s){s=xu(o.length-16,s,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=cO(e,t,r,a,i);if(!YR(c,l))throw In(l),Error("invalid tag");return s.set(o.subarray(0,-16)),e(t,r,s,s,1),In(l),s}}),ln=eO({blockSize:64,nonceLength:12,tagLength:16},sV(nV));/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Va(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Kt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Pe(e,t,r=""){let i=Va(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=i?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+c)}return e}function un(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Kt(e.outputLen),Kt(e.blockLen)}function $i(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 Zp(e,t){Pe(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function Mp(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Fp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Tn(e,t){return e<<32-t|e>>>t}var aV=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function cV(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function lV(e){for(let t=0;t<e.length;t++)e[t]=cV(e[t]);return e}var OS=aV?(e)=>e:lV,uO=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),uV=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Is(e){if(Pe(e),uO)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=uV[e[r]];return t}var Ai={_0:48,_9:57,A:65,F:70,a:97,f:102};function lO(e){if(e>=Ai._0&&e<=Ai._9)return e-Ai._0;if(e>=Ai.A&&e<=Ai.F)return e-(Ai.A-10);if(e>=Ai.a&&e<=Ai.f)return e-(Ai.a-10);return}function Ts(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(uO)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 i=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){let s=lO(e.charCodeAt(o)),a=lO(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw Error('hex string expected, got non-hex character "'+c+'" at index '+o)}i[n]=s*16+a}return i}function Nt(...e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];Pe(n),t+=n.length}let r=new Uint8Array(t);for(let i=0,n=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function Wa(e,t={}){let r=(n,o)=>e(o).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function ho(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 zS=BigInt(0),PS=BigInt(1);function vu(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function dO(e){if(typeof e==="bigint"){if(!Hp(e))throw Error("positive bigint expected, got "+e)}else Kt(e);return e}function _u(e){let t=dO(e).toString(16);return t.length&1?"0"+t:t}function fO(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?zS:BigInt("0x"+e)}function yo(e){return fO(Is(e))}function bo(e){return fO(Is(Kp(Pe(e)).reverse()))}function Ga(e,t){Kt(t),e=dO(e);let r=Ts(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function ku(e,t){return Ga(e,t).reverse()}function Kp(e){return Uint8Array.from(e)}function So(e){return Uint8Array.from(e,(t,r)=>{let i=t.charCodeAt(0);if(t.length!==1||i>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${i} at position ${r}`);return i})}var Hp=(e)=>typeof e==="bigint"&&zS<=e;function dV(e,t,r){return Hp(e)&&Hp(t)&&Hp(r)&&t<=e&&e<r}function Eu(e,t,r,i){if(!dV(t,r,i))throw Error("expected valid "+e+": "+r+" <= n < "+i+", got "+t)}function NS(e){let t;for(t=0;e>zS;e>>=PS,t+=1);return t}var Iu=(e)=>(PS<<BigInt(e))-PS;function pO(e,t,r){if(Kt(e,"hashLen"),Kt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let i=(b)=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=i(e),l=i(e),u=0,f=()=>{c.fill(1),l.fill(0),u=0},p=(...b)=>r(l,Nt(c,...b)),m=(b=n)=>{if(l=p(o,b),c=p(),b.length===0)return;l=p(s,b),c=p()},y=()=>{if(u++>=a)throw Error("drbg: tried max amount of iterations");let b=0,_=[];while(b<t){c=p();let T=c.slice();_.push(T),b+=c.length}return Nt(..._)};return(b,_)=>{f(),m(b);let T=void 0;while(!(T=_(y())))m();return f(),T}}function As(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function i(o,s,a){let c=e[o];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw Error(`param "${o}" is invalid: expected ${s}, got ${l}`)}let n=(o,s)=>Object.entries(o).forEach(([a,c])=>i(a,c,s));n(t,!1),n(r,!0)}function DS(e){let t=new WeakMap;return(r,...i)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r,...i);return t.set(r,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ir=BigInt(0),mr=BigInt(1),$s=BigInt(2),gO=BigInt(3),yO=BigInt(4),bO=BigInt(5),fV=BigInt(7),SO=BigInt(8),pV=BigInt(9),xO=BigInt(16);function Er(e,t){let r=e%t;return r>=Ir?r:t+r}function dn(e,t,r){let i=e;while(t-- >Ir)i*=i,i%=r;return i}function mO(e,t){if(e===Ir)throw Error("invert: expected non-zero number");if(t<=Ir)throw Error("invert: expected positive modulus, got "+t);let r=Er(e,t),i=t,n=Ir,o=mr,s=mr,a=Ir;while(r!==Ir){let l=i/r,u=i%r,f=n-s*l,p=o-a*l;i=r,r=u,n=s,o=a,s=f,a=p}if(i!==mr)throw Error("invert: does not exist");return Er(n,t)}function LS(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function wO(e,t){let r=(e.ORDER+mr)/yO,i=e.pow(t,r);return LS(e,i,t),i}function mV(e,t){let r=(e.ORDER-bO)/SO,i=e.mul(t,$s),n=e.pow(i,r),o=e.mul(t,n),s=e.mul(e.mul(o,$s),n),a=e.mul(o,e.sub(s,e.ONE));return LS(e,a,t),a}function hV(e){let t=Jp(e),r=vO(e),i=r(t,t.neg(t.ONE)),n=r(t,i),o=r(t,t.neg(i)),s=(e+fV)/xO;return(a,c)=>{let l=a.pow(c,s),u=a.mul(l,i),f=a.mul(l,n),p=a.mul(l,o),m=a.eql(a.sqr(u),c),y=a.eql(a.sqr(f),c);l=a.cmov(l,u,m),u=a.cmov(p,f,y);let g=a.eql(a.sqr(u),c),b=a.cmov(l,u,g);return LS(a,b,c),b}}function vO(e){if(e<gO)throw Error("sqrt is not defined for small field");let t=e-mr,r=0;while(t%$s===Ir)t/=$s,r++;let i=$s,n=Jp(e);while(hO(n,i)===1)if(i++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return wO;let o=n.pow(i,t),s=(t+mr)/$s;return function(c,l){if(c.is0(l))return l;if(hO(c,l)!==1)throw Error("Cannot find square root");let u=r,f=c.mul(c.ONE,o),p=c.pow(l,t),m=c.pow(l,s);while(!c.eql(p,c.ONE)){if(c.is0(p))return c.ZERO;let y=1,g=c.sqr(p);while(!c.eql(g,c.ONE))if(y++,g=c.sqr(g),y===u)throw Error("Cannot find square root");let b=mr<<BigInt(u-y-1),_=c.pow(f,b);u=y,f=c.sqr(_),p=c.mul(p,f),m=c.mul(m,_)}return m}}function gV(e){if(e%yO===gO)return wO;if(e%SO===bO)return mV;if(e%xO===pV)return hV(e);return vO(e)}var yV=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function BS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=yV.reduce((i,n)=>(i[n]="function",i),t);return As(e,r),e}function bV(e,t,r){if(r<Ir)throw Error("invalid exponent, negatives unsupported");if(r===Ir)return e.ONE;if(r===mr)return t;let i=e.ONE,n=t;while(r>Ir){if(r&mr)i=e.mul(i,n);n=e.sqr(n),r>>=mr}return i}function Tu(e,t,r=!1){let i=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,c)=>{if(e.is0(a))return s;return i[c]=s,e.mul(s,a)},e.ONE),o=e.inv(n);return t.reduceRight((s,a,c)=>{if(e.is0(a))return s;return i[c]=e.mul(s,i[c]),e.mul(s,a)},o),i}function hO(e,t){let r=(e.ORDER-mr)/$s,i=e.pow(t,r),n=e.eql(i,e.ONE),o=e.eql(i,e.ZERO),s=e.eql(i,e.neg(e.ONE));if(!n&&!o&&!s)throw Error("invalid Legendre symbol result");return n?1:o?0:-1}function SV(e,t){if(t!==void 0)Kt(t);let r=t!==void 0?t:e.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}class _O{ORDER;BITS;BYTES;isLE;ZERO=Ir;ONE=mr;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Ir)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:i,nByteLength:n}=SV(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Er(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return Ir<=e&&e<this.ORDER}is0(e){return e===Ir}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&mr)===mr}neg(e){return Er(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Er(e*e,this.ORDER)}add(e,t){return Er(e+t,this.ORDER)}sub(e,t){return Er(e-t,this.ORDER)}mul(e,t){return Er(e*t,this.ORDER)}pow(e,t){return bV(this,e,t)}div(e,t){return Er(e*mO(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 mO(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=gV(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?ku(e,this.BYTES):Ga(e,this.BYTES)}fromBytes(e,t=!1){Pe(e);let{_lengths:r,BYTES:i,isLE:n,ORDER:o,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>i)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(i);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==i)throw Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=n?bo(e):yo(e);if(s)a=Er(a,o);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Tu(this,e)}cmov(e,t,r){return r?t:e}}function Jp(e,t={}){return new _O(e,t)}function kO(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function jS(e){let t=kO(e);return t+Math.ceil(t/2)}function EO(e,t,r=!1){Pe(e);let i=e.length,n=kO(t),o=jS(t);if(i<16||i<o||i>1024)throw Error("expected "+o+"-1024 bytes of input, got "+i);let s=r?bo(e):yo(e),a=Er(s,t-mr)+mr;return r?ku(a,n):Ga(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Qa=BigInt(0),Cs=BigInt(1);function Au(e,t){let r=t.negate();return e?r:t}function MS(e,t){let r=Tu(e.Fp,t.map((i)=>i.Z));return t.map((i,n)=>e.fromAffine(i.toAffine(r[n])))}function $O(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function US(e,t){$O(e,t);let r=Math.ceil(t/e)+1,i=2**(e-1),n=2**e,o=Iu(e),s=BigInt(e);return{windows:r,windowSize:i,mask:o,maxNumber:n,shiftBy:s}}function IO(e,t,r){let{windowSize:i,mask:n,maxNumber:o,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>i)a-=o,c+=Cs;let l=t*i,u=l+Math.abs(a)-1,f=a===0,p=a<0,m=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:m,offsetF:l}}var qS=new WeakMap,CO=new WeakMap;function ZS(e){return CO.get(e)||1}function TO(e){if(e!==Qa)throw Error("invalid wNAF")}class FS{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 i=e;while(t>Qa){if(t&Cs)r=r.add(i);i=i.double(),t>>=Cs}return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=US(t,this.bits),n=[],o=e,s=o;for(let a=0;a<r;a++){s=o,n.push(s);for(let c=1;c<i;c++)s=s.add(o),n.push(s);o=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let i=this.ZERO,n=this.BASE,o=US(e,this.bits);for(let s=0;s<o.windows;s++){let{nextN:a,offset:c,isZero:l,isNeg:u,isNegF:f,offsetF:p}=IO(r,s,o);if(r=a,l)n=n.add(Au(f,t[p]));else i=i.add(Au(u,t[c]))}return TO(r),{p:i,f:n}}wNAFUnsafe(e,t,r,i=this.ZERO){let n=US(e,this.bits);for(let o=0;o<n.windows;o++){if(r===Qa)break;let{nextN:s,offset:a,isZero:c,isNeg:l}=IO(r,o,n);if(r=s,c)continue;else{let u=t[a];i=i.add(l?u.negate():u)}}return TO(r),i}getPrecomputes(e,t,r){let i=qS.get(t);if(!i){if(i=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")i=r(i);qS.set(t,i)}}return i}cached(e,t,r){let i=ZS(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let n=ZS(e);if(n===1)return this._unsafeLadder(e,t,i);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,i)}createCache(e,t){$O(t,this.bits),CO.set(e,t),qS.delete(e)}hasCache(e){return ZS(e)!==1}}function RO(e,t,r,i){let n=t,o=e.ZERO,s=e.ZERO;while(r>Qa||i>Qa){if(r&Cs)o=o.add(n);if(i&Cs)s=s.add(n);n=n.double(),r>>=Cs,i>>=Cs}return{p1:o,p2:s}}function AO(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return BS(t),t}else return Jp(e,{isLE:r})}function OO(e,t,r={},i){if(i===void 0)i=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l==="bigint"&&l>Qa))throw Error(`CURVE.${c} must be positive bigint`)}let n=AO(t.p,r.Fp,i),o=AO(t.n,r.Fn,i),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:o}}function Vp(e,t){return function(i){let n=e(i);return{secretKey:n,publicKey:t(n)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $u=BigInt(0),Ya=BigInt(1),Wp=BigInt(2);function xV(e){return As(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function PO(e){let t=xV(e),{P:r,type:i,adjustScalarBytes:n,powPminus2:o,randomBytes:s}=t,a=i==="x25519";if(!a&&i!=="x448")throw Error("invalid type");let c=s||ho,l=a?255:448,u=a?32:56,f=a?BigInt(9):BigInt(5),p=a?BigInt(121665):BigInt(39081),m=a?Wp**BigInt(254):Wp**BigInt(447),y=a?BigInt(8)*Wp**BigInt(251)-Ya:BigInt(4)*Wp**BigInt(445)-Ya,g=m+y+Ya,b=(I)=>Er(I,r),_=T(f);function T(I){return ku(b(I),u)}function A(I){let O=Kp(Pe(I,u,"uCoordinate"));if(a)O[31]&=127;return b(bo(O))}function z(I){return bo(n(Kp(Pe(I,u,"scalar"))))}function j(I,O){let R=X(A(O),z(I));if(R===$u)throw Error("invalid private or public key received");return T(R)}function E(I){return j(I,_)}let F=E,D=j;function H(I,O,R){let M=b(I*(O-R));return O=b(O-M),R=b(R+M),{x_2:O,x_3:R}}function X(I,O){Eu("u",I,$u,r),Eu("scalar",O,m,g);let R=O,M=I,L=Ya,V=$u,k=I,te=Ya,ue=$u;for(let be=BigInt(l-1);be>=$u;be--){let Ee=R>>be&Ya;ue^=Ee,{x_2:L,x_3:k}=H(ue,L,k),{x_2:V,x_3:te}=H(ue,V,te),ue=Ee;let Ce=L+V,Re=b(Ce*Ce),_e=L-V,Je=b(_e*_e),Ne=Re-Je,Ye=k+te,mt=k-te,zt=b(mt*Ce),dr=b(Ye*_e),Kr=zt+dr,Jr=zt-dr;k=b(Kr*Kr),te=b(M*b(Jr*Jr)),L=b(Re*Je),V=b(Ne*(Re+b(p*Ne)))}({x_2:L,x_3:k}=H(ue,L,k)),{x_2:V,x_3:te}=H(ue,V,te);let C=o(V);return b(L*C)}let Z={secretKey:u,publicKey:u,seed:u},P=(I=c(u))=>(Pe(I,Z.seed,"seed"),I),N={randomSecretKey:P};return Object.freeze({keygen:Vp(P,F),getSharedSecret:D,getPublicKey:F,scalarMult:j,scalarMultBase:E,utils:N,GuBytes:_.slice(),lengths:Z})}class HS{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(un(e),Pe(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,i=new Uint8Array(r);i.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<i.length;n++)i[n]^=54;this.iHash.update(i),this.oHash=e.create();for(let n=0;n<i.length;n++)i[n]^=106;this.oHash.update(i),Br(i)}update(e){return $i(this),this.iHash.update(e),this}digestInto(e){$i(this),Pe(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:i,destroyed:n,blockLen:o,outputLen:s}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,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 Xa=(e,t,r)=>new HS(e,t).update(r).digest();Xa.create=(e,t)=>new HS(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zO=(e,t)=>(e+(e>=0?t:-t)/DO)/t;function wV(e,t,r){let[[i,n],[o,s]]=t,a=zO(s*e,r),c=zO(-n*e,r),l=e-a*i-c*o,u=-a*n-c*s,f=l<Ci,p=u<Ci;if(f)l=-l;if(p)u=-u;let m=Iu(Math.ceil(NS(r)/2))+ec;if(l<Ci||l>=m||u<Ci||u>=m)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:l,k2neg:p,k2:u}}function JS(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function KS(e,t){let r={};for(let i of Object.keys(t))r[i]=e[i]===void 0?t[i]:e[i];if(vu(r.lowS,"lowS"),vu(r.prehash,"prehash"),r.format!==void 0)JS(r.format);return r}class NO extends Error{constructor(e=""){super(e)}}var xo={Err:NO,_tlv:{encode:(e,t)=>{let{Err:r}=xo;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let i=t.length/2,n=_u(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let o=i>127?_u(n.length/2|128):"";return _u(e)+o+n+t},decode(e,t){let{Err:r}=xo,i=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[i++],o=!!(n&128),s=0;if(!o)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 l=t.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(i+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(i,i+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(i+s)}}},_int:{encode(e){let{Err:t}=xo;if(e<Ci)throw new t("integer: negative integers are not allowed");let r=_u(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}=xo;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 yo(e)}},toSig(e){let{Err:t,_int:r,_tlv:i}=xo,n=Pe(e,void 0,"signature"),{v:o,l:s}=i.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=i.decode(2,o),{v:l,l:u}=i.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=xo,i=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),o=i+n;return t.encode(48,o)}},Ci=BigInt(0),ec=BigInt(1),DO=BigInt(2),Gp=BigInt(3),vV=BigInt(4);function VS(e,t={}){let r=OO("weierstrass",e,t),{Fp:i,Fn:n}=r,o=r.CURVE,{h:s,n:a}=o;As(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c){if(!i.is0(o.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let l=BO(i,n);function u(){if(!i.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function f(P,N,I){let{x:O,y:R}=N.toAffine(),M=i.toBytes(O);if(vu(I,"isCompressed"),I){u();let L=!i.isOdd(R);return Nt(LO(L),M)}else return Nt(Uint8Array.of(4),M,i.toBytes(R))}function p(P){Pe(P,void 0,"Point");let{publicKey:N,publicKeyUncompressed:I}=l,O=P.length,R=P[0],M=P.subarray(1);if(O===N&&(R===2||R===3)){let L=i.fromBytes(M);if(!i.isValid(L))throw Error("bad point: is not on curve, wrong x");let V=g(L),k;try{k=i.sqrt(V)}catch(C){let be=C instanceof Error?": "+C.message:"";throw Error("bad point: is not on curve, sqrt error"+be)}u();let te=i.isOdd(k);if((R&1)===1!==te)k=i.neg(k);return{x:L,y:k}}else if(O===I&&R===4){let L=i.BYTES,V=i.fromBytes(M.subarray(0,L)),k=i.fromBytes(M.subarray(L,L*2));if(!b(V,k))throw Error("bad point: is not on curve");return{x:V,y:k}}else throw Error(`bad point: got length ${O}, expected compressed=${N} or uncompressed=${I}`)}let m=t.toBytes||f,y=t.fromBytes||p;function g(P){let N=i.sqr(P),I=i.mul(N,P);return i.add(i.add(I,i.mul(P,o.a)),o.b)}function b(P,N){let I=i.sqr(N),O=g(P);return i.eql(I,O)}if(!b(o.Gx,o.Gy))throw Error("bad curve params: generator point");let _=i.mul(i.pow(o.a,Gp),vV),T=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(_,T)))throw Error("bad curve params: a or b");function A(P,N,I=!1){if(!i.isValid(N)||I&&i.is0(N))throw Error(`bad point coordinate ${P}`);return N}function z(P){if(!(P instanceof H))throw Error("Weierstrass Point expected")}function j(P){if(!c||!c.basises)throw Error("no endo");return wV(P,c.basises,n.ORDER)}let E=DS((P,N)=>{let{X:I,Y:O,Z:R}=P;if(i.eql(R,i.ONE))return{x:I,y:O};let M=P.is0();if(N==null)N=M?i.ONE:i.inv(R);let L=i.mul(I,N),V=i.mul(O,N),k=i.mul(R,N);if(M)return{x:i.ZERO,y:i.ZERO};if(!i.eql(k,i.ONE))throw Error("invZ was invalid");return{x:L,y:V}}),F=DS((P)=>{if(P.is0()){if(t.allowInfinityPoint&&!i.is0(P.Y))return;throw Error("bad point: ZERO")}let{x:N,y:I}=P.toAffine();if(!i.isValid(N)||!i.isValid(I))throw Error("bad point: x or y not field elements");if(!b(N,I))throw Error("bad point: equation left != right");if(!P.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function D(P,N,I,O,R){return I=new H(i.mul(I.X,P),I.Y,I.Z),N=Au(O,N),I=Au(R,I),N.add(I)}class H{static BASE=new H(o.Gx,o.Gy,i.ONE);static ZERO=new H(i.ZERO,i.ONE,i.ZERO);static Fp=i;static Fn=n;X;Y;Z;constructor(P,N,I){this.X=A("x",P),this.Y=A("y",N,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return o}static fromAffine(P){let{x:N,y:I}=P||{};if(!P||!i.isValid(N)||!i.isValid(I))throw Error("invalid affine point");if(P instanceof H)throw Error("projective point not allowed");if(i.is0(N)&&i.is0(I))return H.ZERO;return new H(N,I,i.ONE)}static fromBytes(P){let N=H.fromAffine(y(Pe(P,void 0,"point")));return N.assertValidity(),N}static fromHex(P){return H.fromBytes(Ts(P))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(P=8,N=!0){if(Z.createCache(this,P),!N)this.multiply(Gp);return this}assertValidity(){F(this)}hasEvenY(){let{y:P}=this.toAffine();if(!i.isOdd)throw Error("Field doesn't support isOdd");return!i.isOdd(P)}equals(P){z(P);let{X:N,Y:I,Z:O}=this,{X:R,Y:M,Z:L}=P,V=i.eql(i.mul(N,L),i.mul(R,O)),k=i.eql(i.mul(I,L),i.mul(M,O));return V&&k}negate(){return new H(this.X,i.neg(this.Y),this.Z)}double(){let{a:P,b:N}=o,I=i.mul(N,Gp),{X:O,Y:R,Z:M}=this,L=i.ZERO,V=i.ZERO,k=i.ZERO,te=i.mul(O,O),ue=i.mul(R,R),C=i.mul(M,M),be=i.mul(O,R);return be=i.add(be,be),k=i.mul(O,M),k=i.add(k,k),L=i.mul(P,k),V=i.mul(I,C),V=i.add(L,V),L=i.sub(ue,V),V=i.add(ue,V),V=i.mul(L,V),L=i.mul(be,L),k=i.mul(I,k),C=i.mul(P,C),be=i.sub(te,C),be=i.mul(P,be),be=i.add(be,k),k=i.add(te,te),te=i.add(k,te),te=i.add(te,C),te=i.mul(te,be),V=i.add(V,te),C=i.mul(R,M),C=i.add(C,C),te=i.mul(C,be),L=i.sub(L,te),k=i.mul(C,ue),k=i.add(k,k),k=i.add(k,k),new H(L,V,k)}add(P){z(P);let{X:N,Y:I,Z:O}=this,{X:R,Y:M,Z:L}=P,V=i.ZERO,k=i.ZERO,te=i.ZERO,ue=o.a,C=i.mul(o.b,Gp),be=i.mul(N,R),Ee=i.mul(I,M),Ce=i.mul(O,L),Re=i.add(N,I),_e=i.add(R,M);Re=i.mul(Re,_e),_e=i.add(be,Ee),Re=i.sub(Re,_e),_e=i.add(N,O);let Je=i.add(R,L);return _e=i.mul(_e,Je),Je=i.add(be,Ce),_e=i.sub(_e,Je),Je=i.add(I,O),V=i.add(M,L),Je=i.mul(Je,V),V=i.add(Ee,Ce),Je=i.sub(Je,V),te=i.mul(ue,_e),V=i.mul(C,Ce),te=i.add(V,te),V=i.sub(Ee,te),te=i.add(Ee,te),k=i.mul(V,te),Ee=i.add(be,be),Ee=i.add(Ee,be),Ce=i.mul(ue,Ce),_e=i.mul(C,_e),Ee=i.add(Ee,Ce),Ce=i.sub(be,Ce),Ce=i.mul(ue,Ce),_e=i.add(_e,Ce),be=i.mul(Ee,_e),k=i.add(k,be),be=i.mul(Je,_e),V=i.mul(Re,V),V=i.sub(V,be),be=i.mul(Re,Ee),te=i.mul(Je,te),te=i.add(te,be),new H(V,k,te)}subtract(P){return this.add(P.negate())}is0(){return this.equals(H.ZERO)}multiply(P){let{endo:N}=t;if(!n.isValidNot0(P))throw Error("invalid scalar: out of range");let I,O,R=(M)=>Z.cached(this,M,(L)=>MS(H,L));if(N){let{k1neg:M,k1:L,k2neg:V,k2:k}=j(P),{p:te,f:ue}=R(L),{p:C,f:be}=R(k);O=ue.add(be),I=D(N.beta,te,C,M,V)}else{let{p:M,f:L}=R(P);I=M,O=L}return MS(H,[I,O])[0]}multiplyUnsafe(P){let{endo:N}=t,I=this;if(!n.isValid(P))throw Error("invalid scalar: out of range");if(P===Ci||I.is0())return H.ZERO;if(P===ec)return I;if(Z.hasCache(this))return this.multiply(P);if(N){let{k1neg:O,k1:R,k2neg:M,k2:L}=j(P),{p1:V,p2:k}=RO(H,I,R,L);return D(N.beta,V,k,O,M)}else return Z.unsafe(I,P)}toAffine(P){return E(this,P)}isTorsionFree(){let{isTorsionFree:P}=t;if(s===ec)return!0;if(P)return P(H,this);return Z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:P}=t;if(s===ec)return this;if(P)return P(H,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(P=!0){return vu(P,"isCompressed"),this.assertValidity(),m(H,this,P)}toHex(P=!0){return Is(this.toBytes(P))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=n.BITS,Z=new FS(H,t.endo?Math.ceil(X/2):X);return H.BASE.precompute(8),H}function LO(e){return Uint8Array.of(e?2:3)}function BO(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function _V(e,t={}){let{Fn:r}=e,i=t.randomBytes||ho,n=Object.assign(BO(e.Fp,r),{seed:jS(r.ORDER)});function o(m){try{let y=r.fromBytes(m);return r.isValidNot0(y)}catch(y){return!1}}function s(m,y){let{publicKey:g,publicKeyUncompressed:b}=n;try{let _=m.length;if(y===!0&&_!==g)return!1;if(y===!1&&_!==b)return!1;return!!e.fromBytes(m)}catch(_){return!1}}function a(m=i(n.seed)){return EO(Pe(m,n.seed,"seed"),r.ORDER)}function c(m,y=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(y)}function l(m){let{secretKey:y,publicKey:g,publicKeyUncompressed:b}=n;if(!Va(m))return;if("_lengths"in r&&r._lengths||y===g)return;let _=Pe(m,void 0,"key").length;return _===g||_===b}function u(m,y,g=!0){if(l(m)===!0)throw Error("first arg must be private key");if(l(y)===!1)throw Error("second arg must be public key");let b=r.fromBytes(m);return e.fromBytes(y).multiply(b).toBytes(g)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a},p=Vp(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:f,lengths:n})}function WS(e,t,r={}){un(t),As(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let i=r.randomBytes||ho,n=r.hmac||((I,O)=>Xa(t,I,O)),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:p,lengths:m}=_V(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},g=a*DO<o.ORDER;function b(I){let O=a>>ec;return I>O}function _(I,O){if(!s.isValidNot0(O))throw Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return O}function T(){if(g)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(I,O){JS(O);let R=m.signature,M=O==="compact"?R:O==="recovered"?R+1:void 0;return Pe(I,M)}class z{r;s;recovery;constructor(I,O,R){if(this.r=_("r",I),this.s=_("s",O),R!=null){if(T(),![0,1,2,3].includes(R))throw Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(I,O=y.format){A(I,O);let R;if(O==="der"){let{r:k,s:te}=xo.toSig(Pe(I));return new z(k,te)}if(O==="recovered")R=I[0],O="compact",I=I.subarray(1);let M=m.signature/2,L=I.subarray(0,M),V=I.subarray(M,M*2);return new z(s.fromBytes(L),s.fromBytes(V),R)}static fromHex(I,O){return this.fromBytes(Ts(I),O)}assertRecovery(){let{recovery:I}=this;if(I==null)throw Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new z(this.r,this.s,I)}recoverPublicKey(I){let{r:O,s:R}=this,M=this.assertRecovery(),L=M===2||M===3?O+a:O;if(!o.isValid(L))throw Error("invalid recovery id: sig.r+curve.n != R.x");let V=o.toBytes(L),k=e.fromBytes(Nt(LO((M&1)===0),V)),te=s.inv(L),ue=E(Pe(I,void 0,"msgHash")),C=s.create(-ue*te),be=s.create(R*te),Ee=e.BASE.multiplyUnsafe(C).add(k.multiplyUnsafe(be));if(Ee.is0())throw Error("invalid recovery: point at infinify");return Ee.assertValidity(),Ee}hasHighS(){return b(this.s)}toBytes(I=y.format){if(JS(I),I==="der")return Ts(xo.hexFromSig(this));let{r:O,s:R}=this,M=s.toBytes(O),L=s.toBytes(R);if(I==="recovered")return T(),Nt(Uint8Array.of(this.assertRecovery()),M,L);return Nt(M,L)}toHex(I){return Is(this.toBytes(I))}}let j=r.bits2int||function(O){if(O.length>8192)throw Error("input is too large");let R=yo(O),M=O.length*8-c;return M>0?R>>BigInt(M):R},E=r.bits2int_modN||function(O){return s.create(j(O))},F=Iu(c);function D(I){return Eu("num < 2^"+c,I,Ci,F),s.toBytes(I)}function H(I,O){return Pe(I,void 0,"message"),O?Pe(t(I),void 0,"prehashed message"):I}function X(I,O,R){let{lowS:M,prehash:L,extraEntropy:V}=KS(R,y);I=H(I,L);let k=E(I),te=s.fromBytes(O);if(!s.isValidNot0(te))throw Error("invalid private key");let ue=[D(te),D(k)];if(V!=null&&V!==!1){let Ce=V===!0?i(m.secretKey):V;ue.push(Pe(Ce,void 0,"extraEntropy"))}let C=Nt(...ue),be=k;function Ee(Ce){let Re=j(Ce);if(!s.isValidNot0(Re))return;let _e=s.inv(Re),Je=e.BASE.multiply(Re).toAffine(),Ne=s.create(Je.x);if(Ne===Ci)return;let Ye=s.create(_e*s.create(be+Ne*te));if(Ye===Ci)return;let mt=(Je.x===Ne?0:2)|Number(Je.y&ec),zt=Ye;if(M&&b(Ye))zt=s.neg(Ye),mt^=1;return new z(Ne,zt,g?void 0:mt)}return{seed:C,k2sig:Ee}}function Z(I,O,R={}){let{seed:M,k2sig:L}=X(I,O,R);return pO(t.outputLen,s.BYTES,n)(M,L).toBytes(R.format)}function P(I,O,R,M={}){let{lowS:L,prehash:V,format:k}=KS(M,y);if(R=Pe(R,void 0,"publicKey"),O=H(O,V),!Va(I)){let te=I instanceof z?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+te)}A(I,k);try{let te=z.fromBytes(I,k),ue=e.fromBytes(R);if(L&&te.hasHighS())return!1;let{r:C,s:be}=te,Ee=E(O),Ce=s.inv(be),Re=s.create(Ee*Ce),_e=s.create(C*Ce),Je=e.BASE.multiplyUnsafe(Re).add(ue.multiplyUnsafe(_e));if(Je.is0())return!1;return s.create(Je.x)===C}catch(te){return!1}}function N(I,O,R={}){let{prehash:M}=KS(R,y);return O=H(O,M),z.fromBytes(I,"recovered").recoverPublicKey(O).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:p,lengths:m,Point:e,sign:Z,verify:P,recoverPublicKey:N,Signature:z,hash:t})}function jO(e,t,r){return e&t^~e&r}function UO(e,t,r){return e&t^e&r^t&r}class Qp{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Fp(this.buffer)}update(e){$i(this),Pe(e);let{view:t,buffer:r,blockLen:i}=this,n=e.length;for(let o=0;o<n;){let s=Math.min(i-this.pos,n-o);if(s===i){let a=Fp(e);for(;i<=n-o;o+=i)this.process(a,o);continue}if(r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){$i(this),Zp(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:o}=this;if(t[o++]=128,Br(this.buffer.subarray(o)),this.padOffset>i-o)this.process(r,0),o=0;for(let u=o;u<i;u++)t[u]=0;r.setBigUint64(i-8,BigInt(this.length*8),n),this.process(r,0);let s=Fp(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)s.setUint32(4*u,l[u],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:i,finished:n,destroyed:o,pos:s}=this;if(e.destroyed=o,e.finished=n,e.length=i,e.pos=s,i%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var Ri=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var tr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);var Yp=BigInt(4294967295),qO=BigInt(32);function kV(e,t=!1){if(t)return{h:Number(e&Yp),l:Number(e>>qO&Yp)};return{h:Number(e>>qO&Yp)|0,l:Number(e&Yp)|0}}function Xp(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=kV(e[o],t);[i[o],n[o]]=[s,a]}return[i,n]}var GS=(e,t,r)=>e>>>r,QS=(e,t,r)=>e<<32-r|t>>>r,Rs=(e,t,r)=>e>>>r|t<<32-r,Os=(e,t,r)=>e<<32-r|t>>>r,Cu=(e,t,r)=>e<<64-r|t>>>r-32,Ru=(e,t,r)=>e>>>r-32|t<<64-r;var ZO=(e,t,r)=>e<<r|t>>>32-r,MO=(e,t,r)=>t<<r|e>>>32-r,FO=(e,t,r)=>t<<r-32|e>>>64-r,HO=(e,t,r)=>e<<r-32|t>>>64-r;function Qn(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var KO=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),JO=(e,t,r,i)=>t+r+i+(e/4294967296|0)|0,VO=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),WO=(e,t,r,i,n)=>t+r+i+n+(e/4294967296|0)|0,GO=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),QO=(e,t,r,i,n,o)=>t+r+i+n+o+(e/4294967296|0)|0;var IV=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]),wo=new Uint32Array(64);class YO extends Qp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:i,E:n,F:o,G:s,H:a}=this;return[e,t,r,i,n,o,s,a]}set(e,t,r,i,n,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)wo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let f=wo[u-15],p=wo[u-2],m=Tn(f,7)^Tn(f,18)^f>>>3,y=Tn(p,17)^Tn(p,19)^p>>>10;wo[u]=y+wo[u-7]+m+wo[u-16]|0}let{A:r,B:i,C:n,D:o,E:s,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let f=Tn(s,6)^Tn(s,11)^Tn(s,25),p=l+f+jO(s,a,c)+IV[u]+wo[u]|0,y=(Tn(r,2)^Tn(r,13)^Tn(r,22))+UO(r,i,n)|0;l=c,c=a,a=s,s=o+p|0,o=n,n=i,i=r,r=p+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,i,n,o,s,a,c,l)}roundClean(){Br(wo)}destroy(){this.set(0,0,0,0,0,0,0,0),Br(this.buffer)}}class XO extends YO{A=Ri[0]|0;B=Ri[1]|0;C=Ri[2]|0;D=Ri[3]|0;E=Ri[4]|0;F=Ri[5]|0;G=Ri[6]|0;H=Ri[7]|0;constructor(){super(32)}}var eP=(()=>Xp(["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))))(),TV=(()=>eP[0])(),AV=(()=>eP[1])(),vo=new Uint32Array(80),_o=new Uint32Array(80);class tP extends Qp{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:f,Gh:p,Gl:m,Hh:y,Hl:g}=this;return[e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g]}set(e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=i|0,this.Ch=n|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let T=0;T<16;T++,t+=4)vo[T]=e.getUint32(t),_o[T]=e.getUint32(t+=4);for(let T=16;T<80;T++){let A=vo[T-15]|0,z=_o[T-15]|0,j=Rs(A,z,1)^Rs(A,z,8)^GS(A,z,7),E=Os(A,z,1)^Os(A,z,8)^QS(A,z,7),F=vo[T-2]|0,D=_o[T-2]|0,H=Rs(F,D,19)^Cu(F,D,61)^GS(F,D,6),X=Os(F,D,19)^Ru(F,D,61)^QS(F,D,6),Z=VO(E,X,_o[T-7],_o[T-16]),P=WO(Z,j,H,vo[T-7],vo[T-16]);vo[T]=P|0,_o[T]=Z|0}let{Ah:r,Al:i,Bh:n,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:f,Fh:p,Fl:m,Gh:y,Gl:g,Hh:b,Hl:_}=this;for(let T=0;T<80;T++){let A=Rs(u,f,14)^Rs(u,f,18)^Cu(u,f,41),z=Os(u,f,14)^Os(u,f,18)^Ru(u,f,41),j=u&p^~u&y,E=f&m^~f&g,F=GO(_,z,E,AV[T],_o[T]),D=QO(F,b,A,j,TV[T],vo[T]),H=F|0,X=Rs(r,i,28)^Cu(r,i,34)^Cu(r,i,39),Z=Os(r,i,28)^Ru(r,i,34)^Ru(r,i,39),P=r&n^r&s^n&s,N=i&o^i&a^o&a;b=y|0,_=g|0,y=p|0,g=m|0,p=u|0,m=f|0,{h:u,l:f}=Qn(c|0,l|0,D|0,H|0),c=s|0,l=a|0,s=n|0,a=o|0,n=r|0,o=i|0;let I=KO(H,Z,N);r=JO(I,D,X,P),i=I|0}({h:r,l:i}=Qn(this.Ah|0,this.Al|0,r|0,i|0)),{h:n,l:o}=Qn(this.Bh|0,this.Bl|0,n|0,o|0),{h:s,l:a}=Qn(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l}=Qn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:f}=Qn(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:m}=Qn(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:g}=Qn(this.Gh|0,this.Gl|0,y|0,g|0),{h:b,l:_}=Qn(this.Hh|0,this.Hl|0,b|0,_|0),this.set(r,i,n,o,s,a,c,l,u,f,p,m,y,g,b,_)}roundClean(){Br(vo,_o)}destroy(){Br(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class rP extends tP{Ah=tr[0]|0;Al=tr[1]|0;Bh=tr[2]|0;Bl=tr[3]|0;Ch=tr[4]|0;Cl=tr[5]|0;Dh=tr[6]|0;Dl=tr[7]|0;Eh=tr[8]|0;El=tr[9]|0;Fh=tr[10]|0;Fl=tr[11]|0;Gh=tr[12]|0;Gl=tr[13]|0;Hh=tr[14]|0;Hl=tr[15]|0;constructor(){super(48)}}var em=Wa(()=>new XO,go(1));var nP=Wa(()=>new rP,go(2));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $V=BigInt(1),iP=BigInt(2),CV=BigInt(3),RV=BigInt(5),Vwe=BigInt(8),oP=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function OV(e){let t=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),o=oP,a=e*e%o*e%o,c=dn(a,iP,o)*a%o,l=dn(c,$V,o)*e%o,u=dn(l,RV,o)*l%o,f=dn(u,t,o)*u%o,p=dn(f,r,o)*f%o,m=dn(p,i,o)*p%o,y=dn(m,n,o)*m%o,g=dn(y,n,o)*m%o,b=dn(g,t,o)*u%o;return{pow_p_5_8:dn(b,iP,o)*e%o,b2:a}}function PV(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var sP=(()=>{let e=oP;return PO({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:i}=OV(t);return Er(dn(r,CV,e)*i,e)},adjustScalarBytes:PV})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zV=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),NV=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))();var DV=VS(zV),YS=WS(DV,em);var LV=VS(NV),aP=WS(LV,nP);function lP(e,t,r){if(un(e),r===void 0)r=new Uint8Array(e.outputLen);return Xa(e,r,t)}var XS=Uint8Array.of(0),cP=Uint8Array.of();function uP(e,t,r,i=32){un(e),Kt(i,"length");let n=e.outputLen;if(i>255*n)throw Error("Length must be <= 255*HashLen");let o=Math.ceil(i/n);if(r===void 0)r=cP;else Pe(r,void 0,"info");let s=new Uint8Array(o*n),a=Xa.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)XS[0]=u+1,c.update(u===0?cP:l).update(r).update(XS).digestInto(l),s.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),Br(l,XS),s.slice(0,i)}var BV=BigInt(0),Ou=BigInt(1),jV=BigInt(2),UV=BigInt(7),qV=BigInt(256),ZV=BigInt(113),pP=[],mP=[],hP=[];for(let e=0,t=Ou,r=1,i=0;e<24;e++){[r,i]=[i,(2*r+3*i)%5],pP.push(2*(5*i+r)),mP.push((e+1)*(e+2)/2%64);let n=BV;for(let o=0;o<7;o++)if(t=(t<<Ou^(t>>UV)*ZV)%qV,t&jV)n^=Ou<<(Ou<<BigInt(o))-Ou;hP.push(n)}var gP=Xp(hP,!0),MV=gP[0],FV=gP[1],dP=(e,t,r)=>r>32?FO(e,t,r):ZO(e,t,r),fP=(e,t,r)=>r>32?HO(e,t,r):MO(e,t,r);function HV(e,t=24){let r=new Uint32Array(10);for(let i=24-t;i<24;i++){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,l=r[c],u=r[c+1],f=dP(l,u,1)^r[a],p=fP(l,u,1)^r[a+1];for(let m=0;m<50;m+=10)e[s+m]^=f,e[s+m+1]^=p}let n=e[2],o=e[3];for(let s=0;s<24;s++){let a=mP[s],c=dP(n,o,a),l=fP(n,o,a),u=pP[s];n=e[u],o=e[u+1],e[u]=c,e[u+1]=l}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]^=MV[i],e[1]^=FV[i]}Br(r)}class tm{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,i=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=i,this.rounds=n,Kt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Mp(this.state)}clone(){return this._cloneInto()}keccak(){OS(this.state32),HV(this.state32,this.rounds),OS(this.state32),this.posOut=0,this.pos=0}update(e){$i(this),Pe(e);let{blockLen:t,state:r}=this,i=e.length;for(let n=0;n<i;){let o=Math.min(t-this.pos,i-n);for(let s=0;s<o;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:i}=this;if(e[r]^=t,(t&128)!==0&&r===i-1)this.keccak();e[i-1]^=128,this.keccak()}writeInto(e){$i(this,!1),Pe(e),this.finish();let t=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){if(this.posOut>=r)this.keccak();let o=Math.min(r-this.posOut,n-i);e.set(t.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Kt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Zp(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,Br(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||=new tm(t,r,i,o,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=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}var yP=(e,t,r,i={})=>Wa(()=>new tm(t,e,r),i);var Ps=yP(6,136,32,go(8));var bP=yP(6,72,64,go(10));var SP=(e,t,r,i={})=>Wa((n={})=>new tm(t,e,n.dkLen===void 0?r:n.dkLen,!0),i),xP=SP(31,168,16,go(11)),Yn=SP(31,136,32,go(12));function ex(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function vP(e){return ex(e),(e&e-1)===0&&e!==0}function tx(e,t){ex(e);let r=0;for(let i=0;i<t;i++,e>>>=1)r=r<<1|e&1;return r}function _P(e){return ex(e),31-Math.clz32(e)}function wP(e){let t=e.length;if(t<2||!vP(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=_P(t);for(let i=0;i<t;i++){let n=tx(i,r);if(i<n){let o=e[i];e[i]=e[n],e[n]=o}}return e}var rx=(e,t)=>{let{N:r,roots:i,dit:n,invertButterflies:o=!1,skipStages:s=0,brp:a=!0}=t,c=_P(r);if(!vP(r))throw Error("FFT: Polynomial size should be power of two");let l=n!==o;return(u)=>{if(u.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)wP(u);for(let f=0,p=1;f<c-s;f++){let m=n?f+1+s:c-f,y=1<<m,g=y>>1,b=r>>m;for(let _=0;_<r;_+=y)for(let T=0,A=p++;T<g;T++){let z=o?n?r-A:A:T*b,j=_+T,E=_+T+g,F=i[z],D=u[E],H=u[j];if(l){let X=e.mul(D,F);u[j]=e.add(H,X),u[E]=e.sub(H,X)}else if(o)u[j]=e.add(D,H),u[E]=e.mul(e.sub(D,H),F);else u[j]=e.add(H,D),u[E]=e.mul(e.sub(H,D),F)}}if(!n&&a)wP(u);return u}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var Xn=ho;function rm(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function kP(e){return Uint8Array.from(e)}function zs(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,i=t.reduce((n,o)=>n+r(o),0);return{bytesLen:i,encode:(n)=>{let o=new Uint8Array(i);for(let s=0,a=0;s<t.length;s++){let c=t[s],l=r(c),u=typeof c==="number"?n[s]:c.encode(n[s]);if(Pe(u,l,e),o.set(u,a),typeof c!=="number")u.fill(0);a+=l}return o},decode:(n)=>{Pe(n,i,e);let o=[];for(let s of t){let a=r(s),c=n.subarray(0,a);o.push(typeof s==="number"?c:s.decode(c)),n=n.subarray(a)}return o}}}function nm(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(i)=>{if(i.length!==t)throw Error(`vecCoder.encode: wrong length=${i.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let o=0,s=0;o<i.length;o++){let a=e.encode(i[o]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(i)=>{Pe(i,r);let n=[];for(let o=0;o<i.length;o+=e.bytesLen)n.push(e.decode(i.subarray(o,o+e.bytesLen)));return n}}}function Ut(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function nx(e){return(1<<e)-1}var lve=Uint8Array.of();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var EP=(e)=>{let{newPoly:t,N:r,Q:i,F:n,ROOT_OF_UNITY:o,brvBits:s,isKyber:a}=e,c=(T,A=i)=>{let z=T%A|0;return(z>=0?z|0:A+z|0)|0},l=(T,A=i)=>{let z=c(T,A)|0;return(z>A>>1?z-A|0:z)|0};function u(){let T=t(r);for(let A=0;A<r;A++){let z=tx(A,s),j=BigInt(o)**BigInt(z)%BigInt(i);T[A]=Number(j)|0}return T}let f=u(),p={add:(T,A)=>c((T|0)+(A|0))|0,sub:(T,A)=>c((T|0)-(A|0))|0,mul:(T,A)=>c((T|0)*(A|0))|0,inv:(T)=>{throw Error("not implemented")}},m={N:r,roots:f,invertButterflies:!0,skipStages:a?1:0,brp:!1},y=rx(p,{dit:!1,...m}),g=rx(p,{dit:!0,...m});return{mod:c,smod:l,nttZetas:f,NTT:{encode:(T)=>y(T),decode:(T)=>{g(T);for(let A=0;A<T.length;A++)T[A]=c(n*T[A]);return T}},bitsCoder:(T,A)=>{let z=nx(T),j=T*(r/8);return{bytesLen:j,encode:(E)=>{let F=new Uint8Array(j);for(let D=0,H=0,X=0,Z=0;D<E.length;D++){H|=(A.encode(E[D])&z)<<X,X+=T;for(;X>=8;X-=8,H>>=8)F[Z++]=H&nx(X)}return F},decode:(E)=>{let F=t(r);for(let D=0,H=0,X=0,Z=0;D<E.length;D++){H|=E[D]<<X,X+=8;for(;X>=T;X-=T,H>>=T)F[Z++]=A.decode(H&z)}return F}}}}},KV=(e)=>(t,r)=>{if(!r)r=e.blockLen;let i=new Uint8Array(t.length+2);i.set(t);let n=t.length,o=new Uint8Array(r),s=e.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(l,u)=>(i[n+0]=l,i[n+1]=u,s.destroy(),s=e.create({}).update(i),a++,()=>(c++,s.xofInto(o))),clean:()=>{s.destroy(),Ut(o,i)}}},IP=KV(xP);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var hr=256,Oi=3329,JV=3303,VV=17,{mod:Nu,nttZetas:WV,NTT:Ns,bitsCoder:GV}=EP({N:hr,Q:Oi,F:JV,ROOT_OF_UNITY:VV,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0}),ix={512:{N:hr,Q:Oi,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:hr,Q:Oi,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:hr,Q:Oi,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}},QV=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+Oi/2)/Oi,decode:(r)=>r*Oi+t>>>e}},Pu=(e)=>GV(e,QV(e));function Ds(e,t){for(let r=0;r<hr;r++)e[r]=Nu(e[r]+t[r])}function YV(e,t){for(let r=0;r<hr;r++)e[r]=Nu(e[r]-t[r])}function XV(e,t,r,i,n){let o=Nu(t*i*n+e*r),s=Nu(e*i+t*r);return{c0:o,c1:s}}function im(e,t){for(let r=0;r<hr/2;r++){let i=WV[64+(r>>1)];if(r&1)i=-i;let{c0:n,c1:o}=XV(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],i);e[2*r+0]=n,e[2*r+1]=o}return e}function TP(e){let t=new Uint16Array(hr);for(let r=0;r<hr;){let i=e();if(i.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<hr&&n+3<=i.length;n+=3){let o=(i[n+0]>>0|i[n+1]<<8)&4095,s=(i[n+1]>>4|i[n+2]<<4)&4095;if(o<Oi)t[r++]=o;if(r<hr&&s<Oi)t[r++]=s}}return t}function zu(e,t,r,i){let n=e(i*hr/4,t,r),o=new Uint16Array(hr),s=Mp(n),a=0;for(let c=0,l=0,u=0,f=0;c<s.length;c++){let p=s[c];for(let m=0;m<32;m++)if(u+=p&1,p>>=1,a+=1,a===i)f=u,u=0;else if(a===2*i)o[l++]=Nu(f-u),u=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return o}var e7=(e)=>{let{K:t,PRF:r,XOF:i,HASH512:n,ETA1:o,ETA2:s,du:a,dv:c}=e,l=Pu(1),u=Pu(c),f=Pu(a),p=zs("publicKey",nm(Pu(12),t),32),m=nm(Pu(12),t),y=zs("ciphertext",nm(f,t),u),g=zs("seed",32,32);return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:p.bytesLen,cipherText:y.bytesLen},keygen:(b)=>{Pe(b,32,"seed");let _=new Uint8Array(33);_.set(b),_[32]=t;let T=n(_),[A,z]=g.decode(T),j=[],E=[];for(let H=0;H<t;H++)j.push(Ns.encode(zu(r,z,H,o)));let F=i(A);for(let H=0;H<t;H++){let X=Ns.encode(zu(r,z,t+H,o));for(let Z=0;Z<t;Z++){let P=TP(F.get(Z,H));Ds(X,im(P,j[Z]))}E.push(X)}F.clean();let D={publicKey:p.encode([E,A]),secretKey:m.encode(j)};return Ut(A,z,j,E,_,T),D},encrypt:(b,_,T)=>{let[A,z]=p.decode(b),j=[];for(let Z=0;Z<t;Z++)j.push(Ns.encode(zu(r,T,Z,o)));let E=i(z),F=new Uint16Array(hr),D=[];for(let Z=0;Z<t;Z++){let P=zu(r,T,t+Z,s),N=new Uint16Array(hr);for(let I=0;I<t;I++){let O=TP(E.get(Z,I));Ds(N,im(O,j[I]))}Ds(P,Ns.decode(N)),D.push(P),Ds(F,im(A[Z],j[Z])),Ut(N)}E.clean();let H=zu(r,T,2*t,s);Ds(H,Ns.decode(F));let X=l.decode(_);return Ds(X,H),Ut(A,j,F,H),y.encode([D,X])},decrypt:(b,_)=>{let[T,A]=y.decode(b),z=m.decode(_),j=new Uint16Array(hr);for(let E=0;E<t;E++)Ds(j,im(z[E],Ns.encode(T[E])));return YV(A,Ns.decode(j)),Ut(j,z,T),l.encode(A)}}};function ox(e){let t=e7(e),{HASH256:r,HASH512:i,KDF:n}=e,{secretCoder:o,lengths:s}=t,a=zs("secretKey",s.secretKey,s.publicKey,32,32),c=32,l=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(u=Xn(64))=>{Pe(u,64,"seed");let{publicKey:f,secretKey:p}=t.keygen(u.subarray(0,32)),m=r(f),y=a.encode([p,f,m,u.subarray(32)]);return Ut(p,m),{publicKey:f,secretKey:y}},getPublicKey:(u)=>{let[f,p,m,y]=a.decode(u);return Uint8Array.from(p)},encapsulate:(u,f=Xn(32))=>{Pe(u,s.publicKey,"publicKey"),Pe(f,32,"message");let p=u.subarray(0,384*e.K),m=o.encode(o.decode(kP(p)));if(!rm(m,p))throw Ut(m),Error("ML-KEM.encapsulate: wrong publicKey modulus");Ut(m);let y=i.create().update(f).update(r(u)).digest(),g=t.encrypt(u,f,y.subarray(32,64));return Ut(y.subarray(32)),{cipherText:g,sharedSecret:y.subarray(0,32)}},decapsulate:(u,f)=>{Pe(f,a.bytesLen,"secretKey"),Pe(u,s.cipherText,"cipherText");let p=a.bytesLen-96,m=p+32,y=r(f.subarray(p/2,m));if(!rm(y,f.subarray(m,m+32)))throw Error("invalid secretKey: hash check failed");let[g,b,_,T]=a.decode(f),A=t.decrypt(u,g),z=i.create().update(A).update(_).digest(),j=z.subarray(0,32),E=t.encrypt(b,A,z.subarray(32,64)),F=rm(u,E),D=n.create({dkLen:32}).update(T).update(u).digest();return Ut(A,E,!F?j:D),F?j:D}}}function t7(e,t,r){return Yn.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var sx={HASH256:Ps,HASH512:bP,KDF:Yn,XOF:IP,PRF:t7},xve=ox({...sx,...ix[512]}),Du=ox({...sx,...ix[768]}),AP=ox({...sx,...ix[1024]});/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */function r7(e,t=!1){let{lengths:r,keygen:i}=e;if(t){let o=e.Point.Fn;if(!o)throw Error("No Point.Fn");i=(s=Xn(r.seed))=>{Pe(s,r.seed,"seed");let a=o.isLE?bo(s):yo(s),c=o.toBytes(o.create(a));return{secretKey:c,publicKey:e.getPublicKey(c)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:i,getPublicKey:(n)=>e.getPublicKey(n)}}function ax(e,t=!1){let r=r7(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(i,n=Xn(e.lengths.seed)){let o=this.keygen(n).secretKey,s=this.decapsulate(i,o),a=e.getPublicKey(o);return Ut(o),{sharedSecret:s,cipherText:a}},decapsulate(i,n){let o=e.getSharedSecret(n,i);return e.lengths.publicKeyHasPrefix?o.subarray(1):o}}}function Lu(e,t){return zs(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function cx(e){return(t,r)=>e(t,{dkLen:r})}function n7(e,t,...r){let i=Lu(r,"seed"),n=Lu(r,"publicKey");if(e===void 0)e=i.bytesLen;Kt(e);function o(s){Pe(s,e);let a=i.decode(t(s,i.bytesLen)),c=r.map((f,p)=>f.keygen(a[p])),l=c.map((f)=>f.secretKey),u=c.map((f)=>f.publicKey);return{secretKey:l,publicKey:u}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Xn(e)){let{publicKey:a,secretKey:c}=o(s),l=n.encode(a);return Ut(a),Ut(c),{secretKey:s,publicKey:l}},expandDecapsulationKey:o,realSeedLen:e}}function om(e,t,r,i,...n){let o=n7(e,r,...n),s=Lu(n,"cipherText"),a=Lu(n,"publicKey"),c=Lu(n,"msg");if(t===void 0)t=c.bytesLen;return Kt(t),{lengths:{...o.info.lengths,msg:t,msgRand:c.bytesLen,cipherText:s.bytesLen},getPublicKey:o.getPublicKey,keygen:o.keygen,encapsulate(l,u=Xn(c.bytesLen)){let f=a.decode(l),p=c.decode(u),m=n.map((_,T)=>_.encapsulate(f[T],p[T])),y=m.map((_)=>_.sharedSecret),g=m.map((_)=>_.cipherText),b={sharedSecret:i(f,g,y),cipherText:s.encode(g)};return Ut(y,g),b},decapsulate(l,u){let f=s.decode(l),{publicKey:p,secretKey:m}=o.expandDecapsulationKey(u),y=n.map((g,b)=>g.decapsulate(f[b],m[b]));return i(p,f,y)}}}function $P(e,t,r,i,n){return un(i),un(n),om(32,32,cx(i),(o,s,a)=>n(Nt(a[0],a[1],s[1],o[1],So(e))),t,r)}var Rve=$P("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",Du,ax(YS,!0),Yn,Ps),Ove=$P("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",AP,ax(aP,!0),Yn,Ps);function i7(e,t,r,i,n){return un(i),un(n),om(32,32,cx(i),(o,s,a)=>{let c=Nt(a[0],a[1],s[0],o[0],s[1],o[1],So(e)),l=32,u=Nt(So("hybrid_prk"),c),f=lP(n,u),p=Nt(Ga(32,2),So("shared_secret"),So("")),m=uP(n,f,p,32);return Ut(f,p,u,c),m},t,r)}var CP=ax(sP),Pve=i7("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",Du,CP,Yn,em),o7=(()=>om(32,32,cx(Yn),(e,t,r)=>Ps(Nt(r[0],r[1],t[1],e[1],So("\\.//^\\"))),Du,CP))();function s7(e,t,r,i){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function o(s){let a;for(let u=0,f=t;;u=f,f+=t){if(f>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(u,f),!0),n.isValidNot0(a))break}let c=n.toBytes(n.create(a)),l=e.getPublicKey(c,!1);return{secretKey:c,publicKey:l}}return{lengths:{secretKey:t,publicKey:r,seed:i,msg:i,cipherText:r},keygen(s=Xn(i)){return Pe(s,i,"seed"),o(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Xn(i)){Pe(a,i,"rand");let{secretKey:c}=o(a),l=this.decapsulate(s,c),u=e.getPublicKey(c,!1);return Ut(c),{sharedSecret:l,cipherText:u}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function a7(e,t,r,i){let{secretKey:n,publicKeyUncompressed:o}=r.lengths;if(!n||!o)throw Error("wrong curve");let s=s7(r,n,o,i),a=64,c=a+i;return om(32,32,(l)=>{Pe(l,32);let u=Yn(l,{dkLen:c}),f=u.subarray(0,a),p=u.subarray(a,c);return Nt(f,p)},(l,u,f)=>Ps(Nt(f[0],f[1],u[1],l[1],So(e))),t,s)}var c7=(()=>a7("MLKEM768-P256",Du,YS,128))();var sm=o7,RP=c7;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ct=(e,t,r)=>Yt(e,t,r),ux=At,tc=Cp,rr=(...e)=>pS(...e),rc=(e)=>mu(e),nc=uS,ic=(e)=>Ei(e),cm=BigInt(0),lx=BigInt(1);function Pi(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function lm(e){if(typeof e==="bigint"){if(!am(e))throw RangeError("positive bigint expected, got "+e)}else ux(e);return e}function ei(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 Bu(e){let t=lm(e).toString(16);return t.length&1?"0"+t:t}function OP(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?cm:BigInt("0x"+e)}function Ls(e){return OP(Cp(e))}function An(e){return OP(Cp(ko(Yt(e)).reverse()))}function um(e,t){if(At(t),t===0)throw RangeError("zero length");e=lm(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return mu(r.padStart(t*2,"0"))}function ju(e,t){return um(e,t).reverse()}function PP(e,t){if(e=ct(e),t=ct(t),e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function ko(e){return Uint8Array.from(ct(e))}function dm(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let i=t.charCodeAt(0);if(t.length!==1||i>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${i} at position ${r}`);return i})}var am=(e)=>typeof e==="bigint"&&cm<=e;function l7(e,t,r){return am(e)&&am(t)&&am(r)&&t<=e&&e<r}function zi(e,t,r,i){if(!l7(t,r,i))throw RangeError("expected valid "+e+": "+r+" <= n < "+i+", got "+t)}function oc(e){if(e<cm)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>cm;e>>=lx,t+=1);return t}var Uu=(e)=>(lx<<BigInt(e))-lx;function zP(e,t,r){if(At(e,"hashLen"),At(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let i=(b)=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=i(e),l=i(e),u=0,f=()=>{c.fill(1),l.fill(0),u=0},p=(...b)=>r(l,rr(c,...b)),m=(b=n)=>{if(l=p(o,b),c=p(),b.length===0)return;l=p(s,b),c=p()},y=()=>{if(u++>=a)throw Error("drbg: tried max amount of iterations");let b=0,_=[];while(b<t){c=p();let T=c.slice();_.push(T),b+=c.length}return rr(..._)};return(b,_)=>{f(),m(b);let T=void 0;while((T=_(y()))===void 0)m();return f(),T}}function fn(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function i(o,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,o))throw TypeError(`param "${o}" is invalid: expected own property`);let c=e[o];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw TypeError(`param "${o}" is invalid: expected ${s}, got ${l}`)}let n=(o,s)=>Object.entries(o).forEach(([a,c])=>i(a,c,s));n(t,!1),n(r,!0)}var dx=()=>{throw Error("not implemented")};/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var nr=BigInt(0),_t=BigInt(1),Bs=BigInt(2),BP=BigInt(3),jP=BigInt(4),UP=BigInt(5),u7=BigInt(7),qP=BigInt(8),d7=BigInt(9),ZP=BigInt(16);function gt(e,t){if(t<=nr)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=nr?r:t+r}function pn(e,t,r){if(t<nr)throw Error("pow2: expected non-negative exponent, got "+t);let i=e;while(t-- >nr)i*=i,i%=r;return i}function NP(e,t){if(e===nr)throw Error("invert: expected non-zero number");if(t<=nr)throw Error("invert: expected positive modulus, got "+t);let r=gt(e,t),i=t,n=nr,o=_t,s=_t,a=nr;while(r!==nr){let l=i/r,u=i-r*l,f=n-s*l,p=o-a*l;i=r,r=u,n=s,o=a,s=f,a=p}if(i!==_t)throw Error("invert: does not exist");return gt(n,t)}function fx(e,t,r){let i=e;if(!i.eql(i.sqr(t),r))throw Error("Cannot find square root")}function MP(e,t){let r=e,i=(r.ORDER+_t)/jP,n=r.pow(t,i);return fx(r,n,t),n}function f7(e,t){let r=e,i=(r.ORDER-UP)/qP,n=r.mul(t,Bs),o=r.pow(n,i),s=r.mul(t,o),a=r.mul(r.mul(s,Bs),o),c=r.mul(s,r.sub(a,r.ONE));return fx(r,c,t),c}function p7(e){let t=fm(e),r=FP(e),i=r(t,t.neg(t.ONE)),n=r(t,i),o=r(t,t.neg(i)),s=(e+u7)/ZP;return(a,c)=>{let l=a,u=l.pow(c,s),f=l.mul(u,i),p=l.mul(u,n),m=l.mul(u,o),y=l.eql(l.sqr(f),c),g=l.eql(l.sqr(p),c);u=l.cmov(u,f,y),f=l.cmov(m,p,g);let b=l.eql(l.sqr(f),c),_=l.cmov(u,f,b);return fx(l,_,c),_}}function FP(e){if(e<BP)throw Error("sqrt is not defined for small field");let t=e-_t,r=0;while(t%Bs===nr)t/=Bs,r++;let i=Bs,n=fm(e);while(DP(n,i)===1)if(i++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return MP;let o=n.pow(i,t),s=(t+_t)/Bs;return function(c,l){let u=c;if(u.is0(l))return l;if(DP(u,l)!==1)throw Error("Cannot find square root");let f=r,p=u.mul(u.ONE,o),m=u.pow(l,t),y=u.pow(l,s);while(!u.eql(m,u.ONE)){if(u.is0(m))return u.ZERO;let g=1,b=u.sqr(m);while(!u.eql(b,u.ONE))if(g++,b=u.sqr(b),g===f)throw Error("Cannot find square root");let _=_t<<BigInt(f-g-1),T=u.pow(p,_);f=g,p=u.sqr(T),m=u.mul(m,p),y=u.mul(y,T)}return y}}function m7(e){if(e%jP===BP)return MP;if(e%qP===UP)return f7;if(e%ZP===d7)return p7(e);return FP(e)}var Ni=(e,t)=>(gt(e,t)&_t)===_t,h7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function px(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=h7.reduce((i,n)=>(i[n]="function",i),t);if(fn(e,r),ei(e.BYTES,"BYTES"),ei(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=_t)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function g7(e,t,r){let i=e;if(r<nr)throw Error("invalid exponent, negatives unsupported");if(r===nr)return i.ONE;if(r===_t)return t;let n=i.ONE,o=t;while(r>nr){if(r&_t)n=i.mul(n,o);o=i.sqr(o),r>>=_t}return n}function qu(e,t,r=!1){let i=e,n=Array(t.length).fill(r?i.ZERO:void 0),o=t.reduce((a,c,l)=>{if(i.is0(c))return a;return n[l]=a,i.mul(a,c)},i.ONE),s=i.inv(o);return t.reduceRight((a,c,l)=>{if(i.is0(c))return a;return n[l]=i.mul(a,n[l]),i.mul(a,c)},s),n}function DP(e,t){let r=e,i=(r.ORDER-_t)/Bs,n=r.pow(t,i),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!a)throw Error("invalid Legendre symbol result");return o?1:s?0:-1}function y7(e,t){if(t!==void 0)ux(t);if(e<=nr)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=oc(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let i=t!==void 0?t:r,n=Math.ceil(i/8);return{nBitLength:i,nByteLength:n}}var LP=new WeakMap;class mx{ORDER;BITS;BYTES;isLE;ZERO=nr;ONE=_t;_lengths;_mod;constructor(e,t={}){if(e<=_t)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:i,nByteLength:n}=y7(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=n,Object.freeze(this)}create(e){return gt(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return nr<=e&&e<this.ORDER}is0(e){return e===nr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&_t)===_t}neg(e){return gt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return gt(e*e,this.ORDER)}add(e,t){return gt(e+t,this.ORDER)}sub(e,t){return gt(e-t,this.ORDER)}mul(e,t){return gt(e*t,this.ORDER)}pow(e,t){return g7(this,e,t)}div(e,t){return gt(e*NP(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 NP(e,this.ORDER)}sqrt(e){let t=LP.get(this);if(!t)LP.set(this,t=m7(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?ju(e,this.BYTES):um(e,this.BYTES)}fromBytes(e,t=!1){ct(e);let{_lengths:r,BYTES:i,isLE:n,ORDER:o,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>i)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(i);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==i)throw Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=n?An(e):Ls(e);if(s)a=gt(a,o);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return qu(this,e)}cmov(e,t,r){return Pi(r,"condition"),r?t:e}}Object.freeze(mx.prototype);function fm(e,t={}){return new mx(e,t)}function HP(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=_t)throw Error("field order must be greater than 1");let t=oc(e-_t);return Math.ceil(t/8)}function hx(e){let t=HP(e);return t+Math.ceil(t/2)}function KP(e,t,r=!1){ct(e);let i=e.length,n=HP(t),o=Math.max(hx(t),16);if(i<o||i>1024)throw Error("expected "+o+"-1024 bytes of input, got "+i);let s=r?An(e):Ls(e),a=gt(s,t-_t)+_t;return r?ju(a,n):um(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var sc=BigInt(0),js=BigInt(1);function Zu(e,t){let r=t.negate();return e?r:t}function Us(e,t){let r=qu(e.Fp,t.map((i)=>i.Z));return t.map((i,n)=>e.fromAffine(i.toAffine(r[n])))}function GP(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function gx(e,t){GP(e,t);let r=Math.ceil(t/e)+1,i=2**(e-1),n=2**e,o=Uu(e),s=BigInt(e);return{windows:r,windowSize:i,mask:o,maxNumber:n,shiftBy:s}}function JP(e,t,r){let{windowSize:i,mask:n,maxNumber:o,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>i)a-=o,c+=js;let l=t*i,u=l+Math.abs(a)-1,f=a===0,p=a<0,m=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:m,offsetF:l}}var yx=new WeakMap,QP=new WeakMap;function bx(e){return QP.get(e)||1}function VP(e){if(e!==sc)throw Error("invalid wNAF")}class Mu{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 i=e;while(t>sc){if(t&js)r=r.add(i);i=i.double(),t>>=js}return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=gx(t,this.bits),n=[],o=e,s=o;for(let a=0;a<r;a++){s=o,n.push(s);for(let c=1;c<i;c++)s=s.add(o),n.push(s);o=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let i=this.ZERO,n=this.BASE,o=gx(e,this.bits);for(let s=0;s<o.windows;s++){let{nextN:a,offset:c,isZero:l,isNeg:u,isNegF:f,offsetF:p}=JP(r,s,o);if(r=a,l)n=n.add(Zu(f,t[p]));else i=i.add(Zu(u,t[c]))}return VP(r),{p:i,f:n}}wNAFUnsafe(e,t,r,i=this.ZERO){let n=gx(e,this.bits);for(let o=0;o<n.windows;o++){if(r===sc)break;let{nextN:s,offset:a,isZero:c,isNeg:l}=JP(r,o,n);if(r=s,c)continue;else{let u=t[a];i=i.add(l?u.negate():u)}}return VP(r),i}getPrecomputes(e,t,r){let i=yx.get(t);if(!i){if(i=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")i=r(i);yx.set(t,i)}}return i}cached(e,t,r){let i=bx(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let n=bx(e);if(n===1)return this._unsafeLadder(e,t,i);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,i)}createCache(e,t){GP(t,this.bits),QP.set(e,t),yx.delete(e)}hasCache(e){return bx(e)!==1}}function YP(e,t,r,i){let n=t,o=e.ZERO,s=e.ZERO;while(r>sc||i>sc){if(r&js)o=o.add(n);if(i&js)s=s.add(n);n=n.double(),r>>=js,i>>=js}return{p1:o,p2:s}}function WP(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return px(t),t}else return fm(e,{isLE:r})}function pm(e,t,r={},i){if(i===void 0)i=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l==="bigint"&&l>sc))throw Error(`CURVE.${c} must be positive bigint`)}let n=WP(t.p,r.Fp,i),o=WP(t.n,r.Fn,i),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:o}}function Fu(e,t){return function(i){let n=e(i);return{secretKey:n,publicKey:t(n)}}}function Hu(e,t){if(ei(e),ei(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 i=t-1;i>=0;i--)r[i]=e&255,e>>>=8;return new Uint8Array(r)}function b7(e,t){let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}function S7(e){if(!nc(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?dm(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function Sx(e,t,r,i){if(ct(e),ei(r),t=S7(t),t.length>255)t=i(rr(dm("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:o}=i,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=rr(t,Hu(t.length,1)),c=new Uint8Array(o),l=Hu(r,2),u=Array(s),f=i(rr(c,e,l,Hu(0,1),a));u[0]=i(rr(f,Hu(1,1),a));for(let m=1;m<s;m++){let y=[b7(f,u[m-1]),Hu(m+1,1),a];u[m]=i(rr(...y))}return rr(...u).slice(0,r)}var XP="HashToScalar-";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ez=(e,t)=>(e+(e>=0?t:-t)/rz)/t;function x7(e,t,r){zi("scalar",e,ti,r);let[[i,n],[o,s]]=t,a=ez(s*e,r),c=ez(-n*e,r),l=e-a*i-c*o,u=-a*n-c*s,f=l<ti,p=u<ti;if(f)l=-l;if(p)u=-u;let m=Uu(Math.ceil(oc(r)/2))+Eo;if(l<ti||l>=m||u<ti||u>=m)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:p,k2:u}}function wx(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function xx(e,t){fn(e);let r={};for(let i of Object.keys(t))r[i]=e[i]===void 0?t[i]:e[i];if(Pi(r.lowS,"lowS"),Pi(r.prehash,"prehash"),r.format!==void 0)wx(r.format);return r}class tz extends Error{constructor(e=""){super(e)}}var $n={Err:tz,_tlv:{encode:(e,t)=>{let{Err:r}=$n;if(ei(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 i=t.length/2,n=Bu(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let o=i>127?Bu(n.length/2|128):"";return Bu(e)+o+n+t},decode(e,t){let{Err:r}=$n;t=ct(t,void 0,"DER data");let i=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[i++],o=!!(n&128),s=0;if(!o)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 l=t.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(i+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(i,i+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(i+s)}}},_int:{encode(e){let{Err:t}=$n;if(lm(e),e<ti)throw new t("integer: negative integers are not allowed");let r=Bu(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}=$n;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 Ls(e)}},toSig(e){let{Err:t,_int:r,_tlv:i}=$n,n=ct(e,void 0,"signature"),{v:o,l:s}=i.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=i.decode(2,o),{v:l,l:u}=i.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=$n,i=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),o=i+n;return t.encode(48,o)}};Object.freeze($n._tlv);Object.freeze($n._int);Object.freeze($n);var ti=BigInt(0),Eo=BigInt(1),rz=BigInt(2),mm=BigInt(3),w7=BigInt(4);function nz(e,t={}){let r=pm("weierstrass",e,t),i=r.Fp,n=r.Fn,o=r.CURVE,{h:s,n:a}=o;fn(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=t;if(c){if(!i.is0(o.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=oz(i,n);function f(){if(!i.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function p(Z,P,N){if(l&&P.is0())return Uint8Array.of(0);let{x:I,y:O}=P.toAffine(),R=i.toBytes(I);if(Pi(N,"isCompressed"),N){f();let M=!i.isOdd(O);return rr(iz(M),R)}else return rr(Uint8Array.of(4),R,i.toBytes(O))}function m(Z){ct(Z,void 0,"Point");let{publicKey:P,publicKeyUncompressed:N}=u,I=Z.length,O=Z[0],R=Z.subarray(1);if(l&&I===1&&O===0)return{x:i.ZERO,y:i.ZERO};if(I===P&&(O===2||O===3)){let M=i.fromBytes(R);if(!i.isValid(M))throw Error("bad point: is not on curve, wrong x");let L=b(M),V;try{V=i.sqrt(L)}catch(ue){let C=ue instanceof Error?": "+ue.message:"";throw Error("bad point: is not on curve, sqrt error"+C)}f();let k=i.isOdd(V);if((O&1)===1!==k)V=i.neg(V);return{x:M,y:V}}else if(I===N&&O===4){let M=i.BYTES,L=i.fromBytes(R.subarray(0,M)),V=i.fromBytes(R.subarray(M,M*2));if(!_(L,V))throw Error("bad point: is not on curve");return{x:L,y:V}}else throw Error(`bad point: got length ${I}, expected compressed=${P} or uncompressed=${N}`)}let y=t.toBytes===void 0?p:t.toBytes,g=t.fromBytes===void 0?m:t.fromBytes;function b(Z){let P=i.sqr(Z),N=i.mul(P,Z);return i.add(i.add(N,i.mul(Z,o.a)),o.b)}function _(Z,P){let N=i.sqr(P),I=b(Z);return i.eql(N,I)}if(!_(o.Gx,o.Gy))throw Error("bad curve params: generator point");let T=i.mul(i.pow(o.a,mm),w7),A=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(T,A)))throw Error("bad curve params: a or b");function z(Z,P,N=!1){if(!i.isValid(P)||N&&i.is0(P))throw Error(`bad point coordinate ${Z}`);return P}function j(Z){if(!(Z instanceof D))throw Error("Weierstrass Point expected")}function E(Z){if(!c||!c.basises)throw Error("no endo");return x7(Z,c.basises,n.ORDER)}function F(Z,P,N,I,O){return N=new D(i.mul(N.X,Z),N.Y,N.Z),P=Zu(I,P),N=Zu(O,N),P.add(N)}class D{static BASE=new D(o.Gx,o.Gy,i.ONE);static ZERO=new D(i.ZERO,i.ONE,i.ZERO);static Fp=i;static Fn=n;X;Y;Z;constructor(Z,P,N){this.X=z("x",Z),this.Y=z("y",P,!0),this.Z=z("z",N),Object.freeze(this)}static CURVE(){return o}static fromAffine(Z){let{x:P,y:N}=Z||{};if(!Z||!i.isValid(P)||!i.isValid(N))throw Error("invalid affine point");if(Z instanceof D)throw Error("projective point not allowed");if(i.is0(P)&&i.is0(N))return D.ZERO;return new D(P,N,i.ONE)}static fromBytes(Z){let P=D.fromAffine(g(ct(Z,void 0,"point")));return P.assertValidity(),P}static fromHex(Z){return D.fromBytes(rc(Z))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(Z=8,P=!0){if(X.createCache(this,Z),!P)this.multiply(mm);return this}assertValidity(){let Z=this;if(Z.is0()){if(t.allowInfinityPoint&&i.is0(Z.X)&&i.eql(Z.Y,i.ONE)&&i.is0(Z.Z))return;throw Error("bad point: ZERO")}let{x:P,y:N}=Z.toAffine();if(!i.isValid(P)||!i.isValid(N))throw Error("bad point: x or y not field elements");if(!_(P,N))throw Error("bad point: equation left != right");if(!Z.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:Z}=this.toAffine();if(!i.isOdd)throw Error("Field doesn't support isOdd");return!i.isOdd(Z)}equals(Z){j(Z);let{X:P,Y:N,Z:I}=this,{X:O,Y:R,Z:M}=Z,L=i.eql(i.mul(P,M),i.mul(O,I)),V=i.eql(i.mul(N,M),i.mul(R,I));return L&&V}negate(){return new D(this.X,i.neg(this.Y),this.Z)}double(){let{a:Z,b:P}=o,N=i.mul(P,mm),{X:I,Y:O,Z:R}=this,M=i.ZERO,L=i.ZERO,V=i.ZERO,k=i.mul(I,I),te=i.mul(O,O),ue=i.mul(R,R),C=i.mul(I,O);return C=i.add(C,C),V=i.mul(I,R),V=i.add(V,V),M=i.mul(Z,V),L=i.mul(N,ue),L=i.add(M,L),M=i.sub(te,L),L=i.add(te,L),L=i.mul(M,L),M=i.mul(C,M),V=i.mul(N,V),ue=i.mul(Z,ue),C=i.sub(k,ue),C=i.mul(Z,C),C=i.add(C,V),V=i.add(k,k),k=i.add(V,k),k=i.add(k,ue),k=i.mul(k,C),L=i.add(L,k),ue=i.mul(O,R),ue=i.add(ue,ue),k=i.mul(ue,C),M=i.sub(M,k),V=i.mul(ue,te),V=i.add(V,V),V=i.add(V,V),new D(M,L,V)}add(Z){j(Z);let{X:P,Y:N,Z:I}=this,{X:O,Y:R,Z:M}=Z,L=i.ZERO,V=i.ZERO,k=i.ZERO,te=o.a,ue=i.mul(o.b,mm),C=i.mul(P,O),be=i.mul(N,R),Ee=i.mul(I,M),Ce=i.add(P,N),Re=i.add(O,R);Ce=i.mul(Ce,Re),Re=i.add(C,be),Ce=i.sub(Ce,Re),Re=i.add(P,I);let _e=i.add(O,M);return Re=i.mul(Re,_e),_e=i.add(C,Ee),Re=i.sub(Re,_e),_e=i.add(N,I),L=i.add(R,M),_e=i.mul(_e,L),L=i.add(be,Ee),_e=i.sub(_e,L),k=i.mul(te,Re),L=i.mul(ue,Ee),k=i.add(L,k),L=i.sub(be,k),k=i.add(be,k),V=i.mul(L,k),be=i.add(C,C),be=i.add(be,C),Ee=i.mul(te,Ee),Re=i.mul(ue,Re),be=i.add(be,Ee),Ee=i.sub(C,Ee),Ee=i.mul(te,Ee),Re=i.add(Re,Ee),C=i.mul(be,Re),V=i.add(V,C),C=i.mul(_e,Re),L=i.mul(Ce,L),L=i.sub(L,C),C=i.mul(Ce,be),k=i.mul(_e,k),k=i.add(k,C),new D(L,V,k)}subtract(Z){return j(Z),this.add(Z.negate())}is0(){return this.equals(D.ZERO)}multiply(Z){let{endo:P}=t;if(!n.isValidNot0(Z))throw RangeError("invalid scalar: out of range");let N,I,O=(R)=>X.cached(this,R,(M)=>Us(D,M));if(P){let{k1neg:R,k1:M,k2neg:L,k2:V}=E(Z),{p:k,f:te}=O(M),{p:ue,f:C}=O(V);I=te.add(C),N=F(P.beta,k,ue,R,L)}else{let{p:R,f:M}=O(Z);N=R,I=M}return Us(D,[N,I])[0]}multiplyUnsafe(Z){let{endo:P}=t,N=this,I=Z;if(!n.isValid(I))throw RangeError("invalid scalar: out of range");if(I===ti||N.is0())return D.ZERO;if(I===Eo)return N;if(X.hasCache(this))return this.multiply(I);if(P){let{k1neg:O,k1:R,k2neg:M,k2:L}=E(I),{p1:V,p2:k}=YP(D,N,R,L);return F(P.beta,V,k,O,M)}else return X.unsafe(N,I)}toAffine(Z){let P=this,N=Z,{X:I,Y:O,Z:R}=P;if(i.eql(R,i.ONE))return{x:I,y:O};let M=P.is0();if(N==null)N=M?i.ONE:i.inv(R);let L=i.mul(I,N),V=i.mul(O,N),k=i.mul(R,N);if(M)return{x:i.ZERO,y:i.ZERO};if(!i.eql(k,i.ONE))throw Error("invZ was invalid");return{x:L,y:V}}isTorsionFree(){let{isTorsionFree:Z}=t;if(s===Eo)return!0;if(Z)return Z(D,this);return X.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:Z}=t;if(s===Eo)return this;if(Z)return Z(D,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===Eo)return this.is0();return this.clearCofactor().is0()}toBytes(Z=!0){return Pi(Z,"isCompressed"),this.assertValidity(),y(D,this,Z)}toHex(Z=!0){return tc(this.toBytes(Z))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let H=n.BITS,X=new Mu(D,t.endo?Math.ceil(H/2):H);if(H>=8)D.BASE.precompute(8);return Object.freeze(D.prototype),Object.freeze(D),D}function iz(e){return Uint8Array.of(e?2:3)}function oz(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function v7(e,t={}){let{Fn:r}=e,i=t.randomBytes===void 0?ic:t.randomBytes,n=Object.assign(oz(e.Fp,r),{seed:Math.max(hx(r.ORDER),16)});function o(m){try{let y=r.fromBytes(m);return r.isValidNot0(y)}catch(y){return!1}}function s(m,y){let{publicKey:g,publicKeyUncompressed:b}=n;try{let _=m.length;if(y===!0&&_!==g)return!1;if(y===!1&&_!==b)return!1;return!!e.fromBytes(m)}catch(_){return!1}}function a(m){return m=m===void 0?i(n.seed):m,KP(ct(m,n.seed,"seed"),r.ORDER)}function c(m,y=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(y)}function l(m){let{secretKey:y,publicKey:g,publicKeyUncompressed:b}=n,_=r._lengths;if(!nc(m))return;let T=ct(m,void 0,"key").length,A=T===g||T===b,z=T===y||!!_?.includes(T);if(A&&z)return;return A}function u(m,y,g=!0){if(l(m)===!0)throw Error("first arg must be private key");if(l(y)===!1)throw Error("second arg must be public key");let b=r.fromBytes(m);return e.fromBytes(y).multiply(b).toBytes(g)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a},p=Fu(a,c);return Object.freeze(f),Object.freeze(n),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:f,lengths:n})}function sz(e,t,r={}){let i=t;ki(i),fn(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?ic:r.randomBytes,o=r.hmac===void 0?(O,R)=>Vn(i,O,R):r.hmac,{Fp:s,Fn:a}=e,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:p,utils:m,lengths:y}=v7(e,r),g={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},b=c*rz+Eo<s.ORDER;function _(O){let R=c>>Eo;return O>R}function T(O,R){if(!a.isValidNot0(R))throw Error(`invalid signature ${O}: out of range 1..Point.Fn.ORDER`);return R}function A(){if(b)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function z(O,R){wx(R);let M=y.signature,L=R==="compact"?M:R==="recovered"?M+1:void 0;return ct(O,L)}class j{r;s;recovery;constructor(O,R,M){if(this.r=T("r",O),this.s=T("s",R),M!=null){if(A(),![0,1,2,3].includes(M))throw Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(O,R=g.format){z(O,R);let M;if(R==="der"){let{r:te,s:ue}=$n.toSig(ct(O));return new j(te,ue)}if(R==="recovered")M=O[0],R="compact",O=O.subarray(1);let L=y.signature/2,V=O.subarray(0,L),k=O.subarray(L,L*2);return new j(a.fromBytes(V),a.fromBytes(k),M)}static fromHex(O,R){return this.fromBytes(rc(O),R)}assertRecovery(){let{recovery:O}=this;if(O==null)throw Error("invalid recovery id: must be present");return O}addRecoveryBit(O){return new j(this.r,this.s,O)}recoverPublicKey(O){let{r:R,s:M}=this,L=this.assertRecovery(),V=L===2||L===3?R+c:R;if(!s.isValid(V))throw Error("invalid recovery id: sig.r+curve.n != R.x");let k=s.toBytes(V),te=e.fromBytes(rr(iz((L&1)===0),k)),ue=a.inv(V),C=F(ct(O,void 0,"msgHash")),be=a.create(-C*ue),Ee=a.create(M*ue),Ce=e.BASE.multiplyUnsafe(be).add(te.multiplyUnsafe(Ee));if(Ce.is0())throw Error("invalid recovery: point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return _(this.s)}toBytes(O=g.format){if(wx(O),O==="der")return rc($n.hexFromSig(this));let{r:R,s:M}=this,L=a.toBytes(R),V=a.toBytes(M);if(O==="recovered")return A(),rr(Uint8Array.of(this.assertRecovery()),L,V);return rr(L,V)}toHex(O){return tc(this.toBytes(O))}}Object.freeze(j.prototype),Object.freeze(j);let E=r.bits2int===void 0?function(R){if(R.length>8192)throw Error("input is too large");let M=Ls(R),L=R.length*8-l;return L>0?M>>BigInt(L):M}:r.bits2int,F=r.bits2int_modN===void 0?function(R){return a.create(E(R))}:r.bits2int_modN,D=Uu(l);function H(O){return zi("num < 2^"+l,O,ti,D),a.toBytes(O)}function X(O,R){return ct(O,void 0,"message"),R?ct(i(O),void 0,"prehashed message"):O}function Z(O,R,M){let{lowS:L,prehash:V,extraEntropy:k}=xx(M,g);O=X(O,V);let te=F(O),ue=a.fromBytes(R);if(!a.isValidNot0(ue))throw Error("invalid private key");let C=[H(ue),H(te)];if(k!=null&&k!==!1){let Re=k===!0?n(y.secretKey):k;C.push(ct(Re,void 0,"extraEntropy"))}let be=rr(...C),Ee=te;function Ce(Re){let _e=E(Re);if(!a.isValidNot0(_e))return;let Je=a.inv(_e),Ne=e.BASE.multiply(_e).toAffine(),Ye=a.create(Ne.x);if(Ye===ti)return;let mt=a.create(Je*a.create(Ee+Ye*ue));if(mt===ti)return;let zt=(Ne.x===Ye?0:2)|Number(Ne.y&Eo),dr=mt;if(L&&_(mt))dr=a.neg(mt),zt^=1;return new j(Ye,dr,b?void 0:zt)}return{seed:be,k2sig:Ce}}function P(O,R,M={}){let{seed:L,k2sig:V}=Z(O,R,M);return zP(i.outputLen,a.BYTES,o)(L,V).toBytes(M.format)}function N(O,R,M,L={}){let{lowS:V,prehash:k,format:te}=xx(L,g);if(M=ct(M,void 0,"publicKey"),R=X(R,k),!nc(O)){let ue=O instanceof j?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ue)}z(O,te);try{let ue=j.fromBytes(O,te),C=e.fromBytes(M);if(V&&ue.hasHighS())return!1;let{r:be,s:Ee}=ue,Ce=F(R),Re=a.inv(Ee),_e=a.create(Ce*Re),Je=a.create(be*Re),Ne=e.BASE.multiplyUnsafe(_e).add(C.multiplyUnsafe(Je));if(Ne.is0())return!1;return a.create(Ne.x)===be}catch(ue){return!1}}function I(O,R,M={}){let{prehash:L}=xx(M,g);return R=X(R,L),j.fromBytes(O,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:p,utils:m,lengths:y,Point:e,sign:P,verify:N,recoverPublicKey:I,Signature:j,hash:i})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _7=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))();var k7=nz(_7),ac=sz(k7,$t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Io=BigInt(0),jr=BigInt(1),vx=BigInt(2),E7=BigInt(8);function I7(e,t,r,i){let n=e.sqr(r),o=e.sqr(i),s=e.add(e.mul(t.a,n),o),a=e.add(e.ONE,e.mul(t.d,e.mul(n,o)));return e.eql(s,a)}function az(e,t={}){let r=t,i=pm("edwards",e,r,r.FpFnLE),{Fp:n,Fn:o}=i,s=i.CURVE,{h:a}=s;fn(r,{},{uvRatio:"function"});let c=vx<<BigInt(o.BYTES*8)-jr,l=(g)=>n.create(g),u=r.uvRatio===void 0?(g,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,b))}}catch(_){return{isValid:!1,value:Io}}}:r.uvRatio;if(!I7(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function f(g,b,_=!1){let T=_?jr:Io;return zi("coordinate "+g,b,T,c),b}function p(g){if(!(g instanceof m))throw Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,jr,l(s.Gx*s.Gy));static ZERO=new m(Io,jr,jr,Io);static Fp=n;static Fn=o;X;Y;Z;T;constructor(g,b,_,T){this.X=f("x",g),this.Y=f("y",b),this.Z=f("z",_,!0),this.T=f("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw Error("extended point not allowed");let{x:b,y:_}=g||{};return f("x",b),f("y",_),new m(b,_,jr,l(b*_))}static fromBytes(g,b=!1){let _=n.BYTES,{a:T,d:A}=s;g=ko(ct(g,_,"point")),Pi(b,"zip215");let z=ko(g),j=g[_-1];z[_-1]=j&-129;let E=An(z),F=b?c:n.ORDER;zi("point.y",E,Io,F);let D=l(E*E),H=l(D-jr),X=l(A*D-T),{isValid:Z,value:P}=u(H,X);if(!Z)throw Error("bad point: invalid y coordinate");let N=(P&jr)===jr,I=(j&128)!==0;if(!b&&P===Io&&I)throw Error("bad point: x=0 and x_0=1");if(I!==N)P=l(-P);return m.fromAffine({x:P,y:E})}static fromHex(g,b=!1){return m.fromBytes(rc(g),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){if(y.createCache(this,g),!b)this.multiply(vx);return this}assertValidity(){let g=this,{a:b,d:_}=s;if(g.is0())throw Error("bad point: ZERO");let{X:T,Y:A,Z:z,T:j}=g,E=l(T*T),F=l(A*A),D=l(z*z),H=l(D*D),X=l(E*b),Z=l(D*l(X+F)),P=l(H+l(_*l(E*F)));if(Z!==P)throw Error("bad point: equation left != right (1)");let N=l(T*A),I=l(z*j);if(N!==I)throw Error("bad point: equation left != right (2)")}equals(g){p(g);let{X:b,Y:_,Z:T}=this,{X:A,Y:z,Z:j}=g,E=l(b*j),F=l(A*T),D=l(_*j),H=l(z*T);return E===F&&D===H}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:g}=s,{X:b,Y:_,Z:T}=this,A=l(b*b),z=l(_*_),j=l(vx*l(T*T)),E=l(g*A),F=b+_,D=l(l(F*F)-A-z),H=E+z,X=H-j,Z=E-z,P=l(D*X),N=l(H*Z),I=l(D*Z),O=l(X*H);return new m(P,N,O,I)}add(g){p(g);let{a:b,d:_}=s,{X:T,Y:A,Z:z,T:j}=this,{X:E,Y:F,Z:D,T:H}=g,X=l(T*E),Z=l(A*F),P=l(j*_*H),N=l(z*D),I=l((T+A)*(E+F)-X-Z),O=N-P,R=N+P,M=l(Z-b*X),L=l(I*O),V=l(R*M),k=l(I*M),te=l(O*R);return new m(L,V,te,k)}subtract(g){return p(g),this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:_}=y.cached(this,g,(T)=>Us(m,T));return Us(m,[b,_])[0]}multiplyUnsafe(g){if(!o.isValid(g))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(g===Io)return m.ZERO;if(this.is0()||g===jr)return this;return y.unsafe(this,g,(b)=>Us(m,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.unsafe(this,s.n).is0()}toAffine(g){let b=this,_=g,{X:T,Y:A,Z:z}=b,j=b.is0();if(_==null)_=j?E7:n.inv(z);let E=l(T*_),F=l(A*_),D=n.mul(z,_);if(j)return{x:Io,y:jr};if(D!==jr)throw Error("invZ was invalid");return{x:E,y:F}}clearCofactor(){if(a===jr)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:g,y:b}=this.toAffine(),_=n.toBytes(b);return _[_.length-1]|=g&jr?128:0,_}toHex(){return tc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new Mu(m,o.BITS);if(o.BITS>=8)m.BASE.precompute(8);return Object.freeze(m.prototype),Object.freeze(m),m}class _x{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){dx()}static fromHex(e){dx()}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 tc(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 Ku=BigInt(0),cc=BigInt(1),hm=BigInt(2);function T7(e){return fn(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function cz(e){let t=T7(e),{P:r,type:i,adjustScalarBytes:n,powPminus2:o,randomBytes:s}=t,a=i==="x25519";if(!a&&i!=="x448")throw Error("invalid type");let c=s===void 0?ic:s,l=a?255:448,u=a?32:56,f=a?BigInt(9):BigInt(5),p=a?BigInt(121665):BigInt(39081),m=a?hm**BigInt(254):hm**BigInt(447),y=a?BigInt(8)*hm**BigInt(251)-cc:BigInt(4)*hm**BigInt(445)-cc,g=m+y+cc,b=(I)=>gt(I,r),_=T(f);function T(I){return ju(b(I),u)}function A(I){let O=ko(ct(I,u,"uCoordinate"));if(a)O[31]&=127;return b(An(O))}function z(I){return An(n(ko(ct(I,u,"scalar"))))}function j(I,O){let R=X(A(O),z(I));if(R===Ku)throw Error("invalid private or public key received");return T(R)}function E(I){return j(I,_)}let F=E,D=j;function H(I,O,R){let M=b(I*(O-R));return O=b(O-M),R=b(R+M),{x_2:O,x_3:R}}function X(I,O){zi("u",I,Ku,r),zi("scalar",O,m,g);let R=O,M=I,L=cc,V=Ku,k=I,te=cc,ue=Ku;for(let be=BigInt(l-1);be>=Ku;be--){let Ee=R>>be&cc;ue^=Ee,{x_2:L,x_3:k}=H(ue,L,k),{x_2:V,x_3:te}=H(ue,V,te),ue=Ee;let Ce=L+V,Re=b(Ce*Ce),_e=L-V,Je=b(_e*_e),Ne=Re-Je,Ye=k+te,mt=k-te,zt=b(mt*Ce),dr=b(Ye*_e),Kr=zt+dr,Jr=zt-dr;k=b(Kr*Kr),te=b(M*b(Jr*Jr)),L=b(Re*Je),V=b(Ne*(Re+b(p*Ne)))}({x_2:L,x_3:k}=H(ue,L,k)),{x_2:V,x_3:te}=H(ue,V,te);let C=o(V);return b(L*C)}let Z={secretKey:u,publicKey:u,seed:u},P=(I)=>(I=I===void 0?c(u):I,ct(I,Z.seed,"seed"),I),N={randomSecretKey:P};return Object.freeze(Z),Object.freeze(N),Object.freeze({keygen:Fu(P,F),getSharedSecret:D,getPublicKey:F,scalarMult:j,scalarMultBase:E,utils:N,GuBytes:_.slice(),lengths:Z})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var A7=BigInt(0),Di=BigInt(1),lz=BigInt(2),$7=BigInt(3),C7=BigInt(5),R7=BigInt(8),Zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Tx=(()=>({p:Zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:R7,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function fz(e){let t=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),o=Zs,a=e*e%o*e%o,c=pn(a,lz,o)*a%o,l=pn(c,Di,o)*e%o,u=pn(l,C7,o)*l%o,f=pn(u,t,o)*u%o,p=pn(f,r,o)*f%o,m=pn(p,i,o)*p%o,y=pn(m,n,o)*m%o,g=pn(y,n,o)*m%o,b=pn(g,t,o)*u%o;return{pow_p_5_8:pn(b,lz,o)*e%o,b2:a}}function O7(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var kx=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ax(e,t){let r=Zs,i=gt(t*t*t,r),n=gt(i*i*t,r),o=fz(e*n).pow_p_5_8,s=gt(e*i*o,r),a=gt(t*s*s,r),c=s,l=gt(s*kx,r),u=a===e,f=a===gt(-e,r),p=a===gt(-e*kx,r);if(u)s=c;if(f||p)s=l;if(Ni(s,r))s=gt(-s,r);return{isValid:u||f,value:s}}var qs=az(Tx,{uvRatio:Ax}),To=(()=>qs.Fp)(),pz=(()=>qs.Fn)();var gm=(()=>{let e=Zs;return cz({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:i}=fz(t);return gt(pn(r,$7,e)*i,e)},adjustScalarBytes:O7})})();var Ex=kx,P7=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),z7=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),N7=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),D7=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),uz=(e)=>Ax(Di,e),L7=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ix=(e)=>To.create(An(e)&L7);function dz(e){let{d:t}=Tx,r=Zs,i=(_)=>To.create(_),n=i(Ex*e*e),o=i((n+Di)*N7),s=BigInt(-1),a=i((s-t*n)*i(n+t)),{isValid:c,value:l}=Ax(o,a),u=i(l*e);if(!Ni(u,r))u=i(-u);if(!c)l=u;if(!c)s=n;let f=i(s*(n-Di)*D7-a),p=l*l,m=i((l+l)*a),y=i(f*P7),g=i(Di-p),b=i(Di+p);return new qs(i(m*b),i(g*y),i(y*b),i(m*g))}class Tr extends _x{static BASE=(()=>new Tr(qs.BASE))();static ZERO=(()=>new Tr(qs.ZERO))();static Fp=(()=>To)();static Fn=(()=>pz)();constructor(e){super(e)}static fromAffine(e){return new Tr(qs.fromAffine(e))}assertSame(e){if(!(e instanceof Tr))throw Error("RistrettoPoint expected")}init(e){return new Tr(e)}static fromBytes(e){Yt(e,32);let{a:t,d:r}=Tx,i=Zs,n=(A)=>To.create(A),o=Ix(e);if(!PP(To.toBytes(o),e)||Ni(o,i))throw Error("invalid ristretto255 encoding 1");let s=n(o*o),a=n(Di+t*s),c=n(Di-t*s),l=n(a*a),u=n(c*c),f=n(t*r*l-u),{isValid:p,value:m}=uz(n(f*u)),y=n(m*c),g=n(m*y*f),b=n((o+o)*y);if(Ni(b,i))b=n(-b);let _=n(a*g),T=n(b*_);if(!p||Ni(T,i)||_===A7)throw Error("invalid ristretto255 encoding 2");return new Tr(new qs(b,_,Di,T))}static fromHex(e){return Tr.fromBytes(mu(e))}toBytes(){let{X:e,Y:t,Z:r,T:i}=this.ep,n=Zs,o=(g)=>To.create(g),s=o(o(r+t)*o(r-t)),a=o(e*t),c=o(a*a),{value:l}=uz(o(s*c)),u=o(l*s),f=o(l*a),p=o(u*f*i),m;if(Ni(i*p,n)){let g=o(t*Ex),b=o(e*Ex);e=g,t=b,m=o(u*z7)}else m=f;if(Ni(e*p,n))t=o(-t);let y=o((r-t)*m);if(Ni(y,n))y=o(-y);return To.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:i,Y:n}=e.ep,o=(c)=>To.create(c),s=o(t*n)===o(r*i),a=o(r*n)===o(t*i);return s||a}is0(){return this.equals(Tr.ZERO)}}Object.freeze(Tr.BASE);Object.freeze(Tr.ZERO);Object.freeze(Tr.prototype);Object.freeze(Tr);var B7=Object.freeze({Point:Tr,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,i=Sx(e,r,64,zp);return B7.deriveToCurve(i)},hashToScalar(e,t={DST:XP}){let r=Sx(e,t.DST,64,zp);return pz.create(An(r))},deriveToCurve(e){Yt(e,64);let t=Ix(e.subarray(0,32)),r=dz(t),i=Ix(e.subarray(32,64)),n=dz(i);return new Tr(r.add(n))}});var mz=!1,j7=!1;async function hz(e,t){if(j7)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 ym(e,t){return await hz(async()=>{let r=$x(e)?e:await q7(e),i=await crypto.subtle.importKey("raw",Z7(t),{name:"X25519"},mz,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:i},r,256))},()=>{if($x(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return gm.scalarMult(e,t)})}async function Ju(e){return await hz(async()=>ym(e,gm.GuBytes),()=>{if($x(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return gm.scalarMultBase(e)})}var U7=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function q7(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...U7,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},mz,["deriveBits"])}function $x(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function Z7(e){return e}class Cx{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),F7(Ms(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=Ms(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:Ms(this.transcript)}}}function F7(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function Ms(e){let t=e.reduce((n,o)=>n+o.length,0),r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r}function lc(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let i of t)r.enqueue(i)}}))}function bm(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function Rx(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function gz(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function yz(e,t){let r=e.getReader(),i=[],n=0;while(n<t){let{done:c,value:l}=await r.read();if(c)throw Error("stream ended before reading "+t.toString()+" bytes");i.push(l),n+=l.length}r.releaseLock();let o=Ms(i),s=o.subarray(0,t),a=lc(e,o.subarray(t));return{data:s,rest:a}}class ri{args;body;constructor(e,t){this.args=e,this.body=t}}async function H7(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 o of r)if(o.length===0)throw Error("invalid stanza");let i=[];for(;;){let o=await e.readLine();if(o===null)throw Error("invalid stanza");let s=pr.decode(o);if(s.length>48)throw Error("invalid stanza");if(i.push(s),s.length<48)break}let n=Ms(i);return{s:new ri(r,n)}}async function bz(e){let t=new Cx(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let i=[];for(;;){let{s:n,next:o}=await H7(t);if(n!==void 0){i.push(n);continue}if(!o.startsWith("--- "))throw Error("invalid header");let s=pr.decode(o.slice(4)),{rest:a,transcript:c}=t.close(),l=c.slice(0,c.length-1-o.length+3);return{stanzas:i,headerNoMAC:l,MAC:s,headerSize:c.length,rest:lc(e,a)}}}function Ox(e){let t=[];t.push(`age-encryption.org/v1
|
|
724
|
+
`)}function SR(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 ft(e,t){let r=e[t];return typeof r==="string"?r:void 0}function vs(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var Tp={name:"@rizom/ops",version:"0.2.0-alpha.591",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/auth-service":"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 rW,mkdirSync as nW,readFileSync as Gx,writeFileSync as Qx}from"fs";import{dirname as iW,join as Az}from"path";function uS(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function At(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 Yt(e,t,r=""){let i=uS(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=i?`length=${n}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;if(!i)throw TypeError(l);throw RangeError(l)}return e}function ki(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(At(e.outputLen),At(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 Ap(e,t){Yt(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function $p(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function kr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Fa(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function En(e,t){return e<<32-t|e>>>t}function Xe(e,t){return e<<t|e>>>32-t>>>0}var $9=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function C9(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function R9(e){for(let t=0;t<e.length;t++)e[t]=C9(e[t]);return e}var dS=$9?(e)=>e:R9,wR=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),O9=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Cp(e){if(Yt(e),wR)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=O9[e[r]];return t}var _i={_0:48,_9:57,A:65,F:70,a:97,f:102};function xR(e){if(e>=_i._0&&e<=_i._9)return e-_i._0;if(e>=_i.A&&e<=_i.F)return e-(_i.A-10);if(e>=_i.a&&e<=_i.f)return e-(_i.a-10);return}function mu(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(wR)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 i=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){let s=xR(e.charCodeAt(o)),a=xR(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw RangeError('hex string expected, got non-hex character "'+c+'" at index '+o)}i[n]=s*16+a}return i}function P9(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function fS(e,t=""){if(typeof e==="string")return P9(e);return Yt(e,void 0,t)}function pS(...e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];Yt(n),t+=n.length}let r=new Uint8Array(t);for(let i=0,n=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function Rp(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 mS(e,t={}){let r=(n,o)=>e(o).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.canXOF=i.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Ei(e=32){At(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 hS=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});class gS{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ki(e),Yt(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,i=new Uint8Array(r);i.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<i.length;n++)i[n]^=54;this.iHash.update(i),this.oHash=e.create();for(let n=0;n<i.length;n++)i[n]^=106;this.oHash.update(i),kr(i)}update(e){return Ma(this),this.iHash.update(e),this}digestInto(e){Ma(this),Ap(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:i,destroyed:n,blockLen:o,outputLen:s}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,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 Vn=(()=>{let e=(t,r,i)=>new gS(t,r).update(i).digest();return e.create=(t,r)=>new gS(t,r),e})();function hu(e,t,r){if(ki(e),r===void 0)r=new Uint8Array(e.outputLen);return Vn(e,r,t)}var yS=Uint8Array.of(0),vR=Uint8Array.of();function bS(e,t,r,i=32){ki(e),At(i,"length"),Yt(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(i>255*n)throw Error("Length must be <= 255*HashLen");let o=Math.ceil(i/n);if(r===void 0)r=vR;else Yt(r,void 0,"info");let s=new Uint8Array(o*n),a=Vn.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)yS[0]=u+1,c.update(u===0?vR:l).update(r).update(yS).digestInto(l),s.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),kr(l,yS),s.slice(0,i)}var lo=(e,t,r,i,n)=>bS(e,hu(e,t,r),i,n);function _R(e,t,r){return e&t^~e&r}function kR(e,t,r){return e&t^e&r^t&r}class Op{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Fa(this.buffer)}update(e){Ma(this),Yt(e);let{view:t,buffer:r,blockLen:i}=this,n=e.length;for(let o=0;o<n;){let s=Math.min(i-this.pos,n-o);if(s===i){let a=Fa(e);for(;i<=n-o;o+=i)this.process(a,o);continue}if(r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ma(this),Ap(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:o}=this;if(t[o++]=128,kr(this.buffer.subarray(o)),this.padOffset>i-o)this.process(r,0),o=0;for(let u=o;u<i;u++)t[u]=0;r.setBigUint64(i-8,BigInt(this.length*8),n),this.process(r,0);let s=Fa(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)s.setUint32(4*u,l[u],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:i,finished:n,destroyed:o,pos:s}=this;if(e.destroyed=o,e.finished=n,e.length=i,e.pos=s,i%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var Ii=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Xt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Pp=BigInt(4294967295),ER=BigInt(32);function z9(e,t=!1){if(t)return{h:Number(e&Pp),l:Number(e>>ER&Pp)};return{h:Number(e>>ER&Pp)|0,l:Number(e&Pp)|0}}function IR(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=z9(e[o],t);[i[o],n[o]]=[s,a]}return[i,n]}var SS=(e,t,r)=>e>>>r,xS=(e,t,r)=>e<<32-r|t>>>r,_s=(e,t,r)=>e>>>r|t<<32-r,ks=(e,t,r)=>e<<32-r|t>>>r,gu=(e,t,r)=>e<<64-r|t>>>r-32,yu=(e,t,r)=>e>>>r-32|t<<64-r;function Wn(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var TR=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),AR=(e,t,r,i)=>t+r+i+(e/4294967296|0)|0,$R=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),CR=(e,t,r,i,n)=>t+r+i+n+(e/4294967296|0)|0,RR=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),OR=(e,t,r,i,n,o)=>t+r+i+n+o+(e/4294967296|0)|0;var D9=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]),uo=new Uint32Array(64);class PR extends Op{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:i,E:n,F:o,G:s,H:a}=this;return[e,t,r,i,n,o,s,a]}set(e,t,r,i,n,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)uo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let f=uo[u-15],p=uo[u-2],m=En(f,7)^En(f,18)^f>>>3,y=En(p,17)^En(p,19)^p>>>10;uo[u]=y+uo[u-7]+m+uo[u-16]|0}let{A:r,B:i,C:n,D:o,E:s,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let f=En(s,6)^En(s,11)^En(s,25),p=l+f+_R(s,a,c)+D9[u]+uo[u]|0,y=(En(r,2)^En(r,13)^En(r,22))+kR(r,i,n)|0;l=c,c=a,a=s,s=o+p|0,o=n,n=i,i=r,r=p+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,i,n,o,s,a,c,l)}roundClean(){kr(uo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}}class zR extends PR{A=Ii[0]|0;B=Ii[1]|0;C=Ii[2]|0;D=Ii[3]|0;E=Ii[4]|0;F=Ii[5]|0;G=Ii[6]|0;H=Ii[7]|0;constructor(){super(32)}}var NR=(()=>IR(["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))))(),L9=(()=>NR[0])(),B9=(()=>NR[1])(),fo=new Uint32Array(80),po=new Uint32Array(80);class DR extends Op{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:f,Gh:p,Gl:m,Hh:y,Hl:g}=this;return[e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g]}set(e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=i|0,this.Ch=n|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let T=0;T<16;T++,t+=4)fo[T]=e.getUint32(t),po[T]=e.getUint32(t+=4);for(let T=16;T<80;T++){let A=fo[T-15]|0,z=po[T-15]|0,j=_s(A,z,1)^_s(A,z,8)^SS(A,z,7),E=ks(A,z,1)^ks(A,z,8)^xS(A,z,7),F=fo[T-2]|0,D=po[T-2]|0,H=_s(F,D,19)^gu(F,D,61)^SS(F,D,6),X=ks(F,D,19)^yu(F,D,61)^xS(F,D,6),Z=$R(E,X,po[T-7],po[T-16]),P=CR(Z,j,H,fo[T-7],fo[T-16]);fo[T]=P|0,po[T]=Z|0}let{Ah:r,Al:i,Bh:n,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:f,Fh:p,Fl:m,Gh:y,Gl:g,Hh:b,Hl:_}=this;for(let T=0;T<80;T++){let A=_s(u,f,14)^_s(u,f,18)^gu(u,f,41),z=ks(u,f,14)^ks(u,f,18)^yu(u,f,41),j=u&p^~u&y,E=f&m^~f&g,F=RR(_,z,E,B9[T],po[T]),D=OR(F,b,A,j,L9[T],fo[T]),H=F|0,X=_s(r,i,28)^gu(r,i,34)^gu(r,i,39),Z=ks(r,i,28)^yu(r,i,34)^yu(r,i,39),P=r&n^r&s^n&s,N=i&o^i&a^o&a;b=y|0,_=g|0,y=p|0,g=m|0,p=u|0,m=f|0,{h:u,l:f}=Wn(c|0,l|0,D|0,H|0),c=s|0,l=a|0,s=n|0,a=o|0,n=r|0,o=i|0;let I=TR(H,Z,N);r=AR(I,D,X,P),i=I|0}({h:r,l:i}=Wn(this.Ah|0,this.Al|0,r|0,i|0)),{h:n,l:o}=Wn(this.Bh|0,this.Bl|0,n|0,o|0),{h:s,l:a}=Wn(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l}=Wn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:f}=Wn(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:m}=Wn(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:g}=Wn(this.Gh|0,this.Gl|0,y|0,g|0),{h:b,l:_}=Wn(this.Hh|0,this.Hl|0,b|0,_|0),this.set(r,i,n,o,s,a,c,l,u,f,p,m,y,g,b,_)}roundClean(){kr(fo,po)}destroy(){this.destroyed=!0,kr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class LR extends DR{Ah=Xt[0]|0;Al=Xt[1]|0;Bh=Xt[2]|0;Bl=Xt[3]|0;Ch=Xt[4]|0;Cl=Xt[5]|0;Dh=Xt[6]|0;Dl=Xt[7]|0;Eh=Xt[8]|0;El=Xt[9]|0;Fh=Xt[10]|0;Fl=Xt[11]|0;Gh=Xt[12]|0;Gl=Xt[13]|0;Hh=Xt[14]|0;Hl=Xt[15]|0;constructor(){super(64)}}var $t=mS(()=>new zR,hS(1));var zp=mS(()=>new LR,hS(3));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function jp(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function _S(e){if(!jp(e))throw TypeError("Uint8Array expected")}function ZR(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 MR(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function mo(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function Su(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function Dp(e){if(!Array.isArray(e))throw TypeError("array expected")}function Lp(e,t){if(!ZR(!0,t))throw TypeError(`${e}: array of strings expected`)}function kS(e,t){if(!ZR(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Vr(...e){let t=(o)=>o,r=(o,s)=>(a)=>o(s(a)),i=e.map((o)=>o.encode).reduceRight(r,t),n=e.map((o)=>o.decode).reduce(r,t);return{encode:i,decode:n}}function Wr(e){let t=typeof e==="string"?e.split(""):e,r=t.length;Lp("alphabet",t);let i=new Map(t.map((n,o)=>[n,o]));return{encode:(n)=>(Dp(n),n.map((o)=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${e}`);return t[o]})),decode:(n)=>(Dp(n),n.map((o)=>{mo("alphabet.decode",o);let s=i.get(o);if(s===void 0)throw Error(`Unknown letter: "${o}". Allowed: ${e}`);return s}))}}function Gr(e=""){return mo("join",e),{encode:(t)=>(Lp("join.decode",t),t.join(e)),decode:(t)=>(mo("join.decode",t),t.split(e))}}function Up(e,t="="){return Su(e),mo("padding",t),{encode(r){Lp("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){Lp("padding.decode",r);let i=r.length;if(i*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;i>0&&r[i-1]===t;i--)if((i-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,i)}}}function FR(e){return MR(e),{encode:(t)=>t,decode:(t)=>e(t)}}function BR(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(Dp(e),!e.length)return[];let i=0,n=[],o=Array.from(e,(a)=>{if(Su(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=o.length;while(!0){let a=0,c=!0;for(let l=i;l<s;l++){let u=o[l],f=t*a,p=f+u;if(!Number.isSafeInteger(p)||f/t!==a||p-u!==f)throw Error("convertRadix: carry overflow");let m=p/r;a=p%r;let y=Math.floor(m);if(o[l]=y,!Number.isSafeInteger(y)||y*r+a!==p)throw Error("convertRadix: carry overflow");if(!c)continue;else if(!y)i=l;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 HR=(e,t)=>t===0?e:HR(t,e%t),Bp=(e,t)=>e+(t-HR(e,t)),Np=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function wS(e,t,r,i){if(Dp(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if(Bp(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${Bp(t,r)}`);let n=0,o=0,s=Np[t],a=Np[r]-1,c=[];for(let l of e){if(Su(l),l>=s)throw Error(`convertRadix2: invalid data word=${l} from=${t}`);if(n=n<<t|l,o+t>32)throw Error(`convertRadix2: carry overflow pos=${o} from=${t}`);o+=t;for(;o>=r;o-=r)c.push((n>>o-r&a)>>>0);let u=Np[o];if(u===void 0)throw Error("invalid carry");n&=u-1}if(n=n<<r-o&a,!i&&o>=t)throw Error("Excess padding");if(!i&&n>0)throw Error(`Non-zero padding: ${n}`);if(i&&o>0)c.push(n>>>0);return c}function j9(e){Su(e);let t=256;return{encode:(r)=>{if(!jp(r))throw TypeError("radix.encode input should be Uint8Array");return BR(Array.from(r),t,e)},decode:(r)=>(kS("radix.decode",r),Uint8Array.from(BR(r,e,t)))}}function cn(e,t=!1){if(Su(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if(Bp(8,e)>32||Bp(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!jp(r))throw TypeError("radix2.encode input should be Uint8Array");return wS(Array.from(r),8,e,!t)},decode:(r)=>(kS("radix2.decode",r),Uint8Array.from(wS(r,e,8,t)))}}function jR(e){return MR(e),function(...t){try{return e.apply(null,t)}catch(r){}}}var Pxe=Object.freeze(Vr(cn(4),Wr("0123456789ABCDEF"),Gr(""))),zxe=Object.freeze(Vr(cn(5),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Up(5),Gr(""))),Nxe=Object.freeze(Vr(cn(5),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Gr(""))),Dxe=Object.freeze(Vr(cn(5),Wr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Up(5),Gr(""))),Lxe=Object.freeze(Vr(cn(5),Wr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Gr(""))),Bxe=Object.freeze(Vr(cn(5),Wr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Gr(""),FR((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),KR=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),U9=/[\t\n\f\r ]/,JR=(e,t)=>{mo("base64",e);let r=t?"base64url":"base64";if(e.length>0&&U9.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},ES=Object.freeze(KR?{encode(e){return _S(e),e.toBase64()},decode(e){return JR(e,!1)}}:Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Up(6),Gr(""))),pr=Object.freeze(Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Gr(""))),jxe=Object.freeze(KR?{encode(e){return _S(e),e.toBase64({alphabet:"base64url"})},decode(e){return JR(e,!0)}}:Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Up(6),Gr(""))),Uxe=Object.freeze(Vr(cn(6),Wr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Gr(""))),IS=(e)=>Vr(j9(58),Wr(e),Gr("")),qxe=Object.freeze(IS("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Zxe=Object.freeze(IS("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),Mxe=Object.freeze(IS("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"));var vS=Vr(Wr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Gr("")),UR=[996825010,642813549,513874426,1027748829,705979059];function bu(e){let t=e>>25,r=(e&33554431)<<5;for(let i=0;i<UR.length;i++)if((t>>i&1)===1)r^=UR[i];return r}function qR(e,t,r=1){let i=e.length,n=1;for(let o=0;o<i;o++){let s=e.charCodeAt(o);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=bu(n)^s>>5}n=bu(n);for(let o=0;o<i;o++)n=bu(n)^e.charCodeAt(o)&31;for(let o of t)n=bu(n)^o;for(let o=0;o<6;o++)n=bu(n);return n^=r,vS.encode(wS([n%Np[30]],30,5,!1))}function VR(e){let t=e==="bech32"?1:734539939,r=cn(5),i=r.decode,n=r.encode,o=jR(i);function s(f,p,m=90){if(mo("bech32.encode prefix",f),jp(p))p=Array.from(p);kS("bech32.encode",p);let y=f.length;if(y===0)throw TypeError(`Invalid prefix length ${y}`);let g=y+7+p.length;if(m!==!1&&g>m)throw TypeError(`Length ${g} exceeds limit ${m}`);let b=f.toLowerCase(),_=qR(b,p,t);return`${b}1${vS.encode(p)}${_}`}function a(f,p=90){mo("bech32.decode input",f);let m=f.length;if(m<8||p!==!1&&m>p)throw TypeError(`invalid string length: ${m} (${f}). Expected (8..${p})`);let y=f.toLowerCase();if(f!==y&&f!==f.toUpperCase())throw Error("String must be lowercase or uppercase");let g=y.lastIndexOf("1");if(g===0||g===-1)throw Error('Letter "1" must be present between prefix and data only');let b=y.slice(0,g),_=y.slice(g+1);if(_.length<6)throw Error("Data must be at least 6 characters long");let T=vS.decode(_).slice(0,-6),A=qR(b,T,t);if(!_.endsWith(A))throw Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:b,words:T}}let c=jR(a);function l(f){let{prefix:p,words:m}=a(f,!1);return{prefix:p,words:m,bytes:i(m)}}function u(f,p){return s(f,n(p))}return{encode:s,decode:a,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:i,fromWordsUnsafe:o,toWords:n}}var Qr=Object.freeze(VR("bech32")),Fxe=Object.freeze(VR("bech32m"));var q9=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Z9={encode(e){return _S(e),e.toHex()},decode(e){return mo("hex",e),Uint8Array.fromHex(e)}},Hxe=Object.freeze(q9?Z9:Vr(cn(4),Wr("0123456789abcdef"),Gr(""),FR((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 F9(e,t,r,i){ki(e);let n=Rp({dkLen:32,asyncTick:10},i),{c:o,dkLen:s,asyncTick:a}=n;if(At(o,"c"),At(s,"dkLen"),At(a,"asyncTick"),o<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=fS(t,"password"),l=fS(r,"salt"),u=new Uint8Array(s),f=Vn.create(e,c),p=f._cloneInto().update(l);return{c:o,dkLen:s,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function H9(e,t,r,i,n){if(e.destroy(),t.destroy(),i)i.destroy();return kr(n),r}function TS(e,t,r,i){let{c:n,dkLen:o,DK:s,PRF:a,PRFSalt:c}=F9(e,t,r,i),l,u=new Uint8Array(4),f=Fa(u),p=new Uint8Array(a.outputLen);for(let m=1,y=0;y<o;m++,y+=a.outputLen){let g=s.subarray(y,y+a.outputLen);f.setInt32(0,m,!1),(l=c._cloneInto(l)).update(u).digestInto(p),g.set(p.subarray(0,g.length));for(let b=1;b<n;b++){a._cloneInto(l).update(p).digestInto(p);for(let _=0;_<g.length;_++)g[_]^=p[_]}}return H9(a,c,s,l,p)}function WR(e,t,r,i,n,o){let s=e[t++]^r[i++],a=e[t++]^r[i++],c=e[t++]^r[i++],l=e[t++]^r[i++],u=e[t++]^r[i++],f=e[t++]^r[i++],p=e[t++]^r[i++],m=e[t++]^r[i++],y=e[t++]^r[i++],g=e[t++]^r[i++],b=e[t++]^r[i++],_=e[t++]^r[i++],T=e[t++]^r[i++],A=e[t++]^r[i++],z=e[t++]^r[i++],j=e[t++]^r[i++],E=s,F=a,D=c,H=l,X=u,Z=f,P=p,N=m,I=y,O=g,R=b,M=_,L=T,V=A,k=z,te=j;for(let ue=0;ue<8;ue+=2)X^=Xe(E+L|0,7),I^=Xe(X+E|0,9),L^=Xe(I+X|0,13),E^=Xe(L+I|0,18),O^=Xe(Z+F|0,7),V^=Xe(O+Z|0,9),F^=Xe(V+O|0,13),Z^=Xe(F+V|0,18),k^=Xe(R+P|0,7),D^=Xe(k+R|0,9),P^=Xe(D+k|0,13),R^=Xe(P+D|0,18),H^=Xe(te+M|0,7),N^=Xe(H+te|0,9),M^=Xe(N+H|0,13),te^=Xe(M+N|0,18),F^=Xe(E+H|0,7),D^=Xe(F+E|0,9),H^=Xe(D+F|0,13),E^=Xe(H+D|0,18),P^=Xe(Z+X|0,7),N^=Xe(P+Z|0,9),X^=Xe(N+P|0,13),Z^=Xe(X+N|0,18),M^=Xe(R+O|0,7),I^=Xe(M+R|0,9),O^=Xe(I+M|0,13),R^=Xe(O+I|0,18),L^=Xe(te+k|0,7),V^=Xe(L+te|0,9),k^=Xe(V+L|0,13),te^=Xe(k+V|0,18);n[o++]=s+E|0,n[o++]=a+F|0,n[o++]=c+D|0,n[o++]=l+H|0,n[o++]=u+X|0,n[o++]=f+Z|0,n[o++]=p+P|0,n[o++]=m+N|0,n[o++]=y+I|0,n[o++]=g+O|0,n[o++]=b+R|0,n[o++]=_+M|0,n[o++]=T+L|0,n[o++]=A+V|0,n[o++]=z+k|0,n[o++]=j+te|0}function AS(e,t,r,i,n){let o=i+0,s=i+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++,o+=16,t+=16){if(WR(r,s,e,t,r,o),a>0)s+=16;WR(r,o,e,t+=16,r,s)}}function K9(e,t,r){let i=Rp({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:o,p:s,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=i;if(At(n,"N"),At(o,"r"),At(s,"p"),At(a,"dkLen"),At(c,"asyncTick"),At(l,"maxmem"),u!==void 0&&typeof u!=="function")throw Error("progressCb must be a function");let f=128*o,p=f/4,m=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>m)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(m-1)*32/f)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(m-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let y=f*(n+s+1);if(y>l)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+y+", maxmem="+l);let g=TS($t,e,t,{c:1,dkLen:f*s}),b=$p(g),_=$p(new Uint8Array(f*n)),T=$p(new Uint8Array(f)),A=()=>{};if(u){let z=2*n*s,j=Math.max(Math.floor(z/1e4),1),E=0;A=()=>{if(E++,u&&(!(E%j)||E===z))u(E/z)}}return{N:n,r:o,p:s,dkLen:a,blockSize32:p,V:_,B32:b,B:g,tmp:T,blockMixCb:A,asyncTick:c}}function J9(e,t,r,i,n){let o=TS($t,e,r,{c:1,dkLen:t});return kr(r,i,n),o}function $S(e,t,r){let{N:i,r:n,p:o,dkLen:s,blockSize32:a,V:c,B32:l,B:u,tmp:f,blockMixCb:p}=K9(e,t,r);dS(l);for(let m=0;m<o;m++){let y=a*m;for(let g=0;g<a;g++)c[g]=l[y+g];for(let g=0,b=0;g<i-1;g++)AS(c,b,c,b+=a,n),p();AS(c,(i-1)*a,l,y,n),p();for(let g=0;g<i;g++){let b=(l[y+a-16]&i-1)>>>0;for(let _=0;_<a;_++)f[_]=l[y+_]^c[b*a+_];AS(f,0,l,y,n),p()}}return dS(l),J9(e,s,u,c,f)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function V9(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function qp(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function Ha(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 jt(e,t,r=""){let i=V9(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=i?`length=${n}`:`type=${typeof e}`,l=s+"expected Uint8Array"+a+", got "+c;if(!i)throw TypeError(l);throw RangeError(l)}return e}function CS(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 GR(e,t,r=!1){jt(e,void 0,"output");let i=t.outputLen;if(e.length<i)throw RangeError("digestInto() expects output buffer of length at least "+i);if(r&&!Ka(e))throw Error("invalid output, must be aligned")}function Gn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function In(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function W9(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var Es=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),G9=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;var Q9=(e)=>{for(let t=0;t<e.length;t++)e[t]=G9(e[t]);return e},Ti=Es?(e)=>e:Q9;function QR(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function YR(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function XR(e,t,r){let i=t,n=r||(()=>[]),o=(a,c)=>i(c,...n(a)).update(a).digest(),s=i(new Uint8Array(e),...n(new Uint8Array(0)));return o.outputLen=s.outputLen,o.blockLen=s.blockLen,o.create=(a,...c)=>i(a,...c),o}var eO=(e,t)=>{function r(i,...n){if(jt(i,void 0,"key"),e.nonceLength!==void 0){let u=n[0];jt(u,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let o=e.tagLength;if(o&&n[1]!==void 0)jt(n[1],void 0,"AAD");let s=t(i,...n),a=(u,f)=>{if(f!==void 0){if(u!==2)throw Error("cipher output not supported");jt(f,void 0,"output")}},c=!1;return{encrypt(u,f){if(c)throw Error("cannot encrypt() twice with same key + nonce");return c=!0,jt(u),a(s.encrypt.length,f),s.encrypt(u,f)},decrypt(u,f){if(jt(u),o&&u.length<o)throw Error('"ciphertext" expected length bigger than tagLength='+o);return a(s.decrypt.length,f),s.decrypt(u,f)}}}return Object.assign(r,e),r};function xu(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(jt(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Ka(t))throw Error("invalid output, must be aligned");return t}function tO(e,t,r){Ha(e),Ha(t),qp(r);let i=new Uint8Array(16),n=W9(i);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),i}function Ka(e){return e.byteOffset%4===0}function Ja(e){return Uint8Array.from(jt(e))}var nO=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),Y9=(()=>Ti(Gn(nO("expand 16-byte k"))))(),X9=(()=>Ti(Gn(nO("expand 32-byte k"))))();function et(e,t){return e<<t|e>>>32-t}var wu=64,eV=16,RS=(()=>4294967295)(),rO=Uint32Array.of();function tV(e,t,r,i,n,o,s,a){let c=n.length,l=new Uint8Array(wu),u=Gn(l),f=Es&&Ka(n)&&Ka(o),p=f?Gn(n):rO,m=f?Gn(o):rO;if(!Es){for(let y=0;y<c;s++){if(e(t,r,i,u,s,a),Ti(u),s>=RS)throw Error("arx: counter overflow");let g=Math.min(wu,c-y);for(let b=0,_;b<g;b++)_=y+b,o[_]=n[_]^l[b];y+=g}return}for(let y=0;y<c;s++){if(e(t,r,i,u,s,a),s>=RS)throw Error("arx: counter overflow");let g=Math.min(wu,c-y);if(f&&g===wu){let b=y/4;if(y%4!==0)throw Error("arx: invalid block position");for(let _=0,T;_<eV;_++)T=b+_,m[T]=p[T]^u[_];y+=wu;continue}for(let b=0,_;b<g;b++)_=y+b,o[_]=n[_]^l[b];y+=g}}function iO(e,t){let{allowShortKeys:r,extendNonceFn:i,counterLength:n,counterRight:o,rounds:s}=QR({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return Ha(n),Ha(s),qp(o),qp(r),(a,c,l,u,f=0)=>{jt(a,void 0,"key"),jt(c,void 0,"nonce"),jt(l,void 0,"data");let p=l.length;if(u=xu(p,u,!1),Ha(f),f<0||f>=RS)throw Error("arx: counter overflow");let m=[],y=a.length,g,b;if(y===32)m.push(g=Ja(a)),b=X9;else if(y===16&&r)g=new Uint8Array(32),g.set(a),g.set(a,16),b=Y9,m.push(g);else throw jt(a,32,"arx key"),Error("invalid key size");if(!Es||!Ka(c))m.push(c=Ja(c));let _=Gn(g);if(i){if(c.length!==24)throw Error("arx: extended nonce must be 24 bytes");let z=c.subarray(0,16);if(Es)i(b,_,Gn(z),_);else{let j=Ti(Uint32Array.from(b));i(j,_,Gn(z),_),In(j),Ti(_)}c=c.subarray(16)}else if(!Es)Ti(_);let T=16-n;if(T!==c.length)throw Error(`arx: nonce must be ${T} or 16 bytes`);if(T!==12){let z=new Uint8Array(12);z.set(c,o?0:12-c.length),c=z,m.push(c)}let A=Ti(Gn(c));try{return tV(e,b,_,A,l,u,f,s),u}finally{In(...m)}}}function er(e,t){return e[t++]&255|(e[t++]&255)<<8}class oO{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=Ja(jt(e,32,"key"));let t=er(e,0),r=er(e,2),i=er(e,4),n=er(e,6),o=er(e,8),s=er(e,10),a=er(e,12),c=er(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>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 l=0;l<8;l++)this.pad[l]=er(e,16+2*l)}process(e,t,r=!1){let i=r?0:2048,{h:n,r:o}=this,s=o[0],a=o[1],c=o[2],l=o[3],u=o[4],f=o[5],p=o[6],m=o[7],y=o[8],g=o[9],b=er(e,t+0),_=er(e,t+2),T=er(e,t+4),A=er(e,t+6),z=er(e,t+8),j=er(e,t+10),E=er(e,t+12),F=er(e,t+14),D=n[0]+(b&8191),H=n[1]+((b>>>13|_<<3)&8191),X=n[2]+((_>>>10|T<<6)&8191),Z=n[3]+((T>>>7|A<<9)&8191),P=n[4]+((A>>>4|z<<12)&8191),N=n[5]+(z>>>1&8191),I=n[6]+((z>>>14|j<<2)&8191),O=n[7]+((j>>>11|E<<5)&8191),R=n[8]+((E>>>8|F<<8)&8191),M=n[9]+(F>>>5|i),L=0,V=L+D*s+H*(5*g)+X*(5*y)+Z*(5*m)+P*(5*p);L=V>>>13,V&=8191,V+=N*(5*f)+I*(5*u)+O*(5*l)+R*(5*c)+M*(5*a),L+=V>>>13,V&=8191;let k=L+D*a+H*s+X*(5*g)+Z*(5*y)+P*(5*m);L=k>>>13,k&=8191,k+=N*(5*p)+I*(5*f)+O*(5*u)+R*(5*l)+M*(5*c),L+=k>>>13,k&=8191;let te=L+D*c+H*a+X*s+Z*(5*g)+P*(5*y);L=te>>>13,te&=8191,te+=N*(5*m)+I*(5*p)+O*(5*f)+R*(5*u)+M*(5*l),L+=te>>>13,te&=8191;let ue=L+D*l+H*c+X*a+Z*s+P*(5*g);L=ue>>>13,ue&=8191,ue+=N*(5*y)+I*(5*m)+O*(5*p)+R*(5*f)+M*(5*u),L+=ue>>>13,ue&=8191;let C=L+D*u+H*l+X*c+Z*a+P*s;L=C>>>13,C&=8191,C+=N*(5*g)+I*(5*y)+O*(5*m)+R*(5*p)+M*(5*f),L+=C>>>13,C&=8191;let be=L+D*f+H*u+X*l+Z*c+P*a;L=be>>>13,be&=8191,be+=N*s+I*(5*g)+O*(5*y)+R*(5*m)+M*(5*p),L+=be>>>13,be&=8191;let Ee=L+D*p+H*f+X*u+Z*l+P*c;L=Ee>>>13,Ee&=8191,Ee+=N*a+I*s+O*(5*g)+R*(5*y)+M*(5*m),L+=Ee>>>13,Ee&=8191;let Ce=L+D*m+H*p+X*f+Z*u+P*l;L=Ce>>>13,Ce&=8191,Ce+=N*c+I*a+O*s+R*(5*g)+M*(5*y),L+=Ce>>>13,Ce&=8191;let Re=L+D*y+H*m+X*p+Z*f+P*u;L=Re>>>13,Re&=8191,Re+=N*l+I*c+O*a+R*s+M*(5*g),L+=Re>>>13,Re&=8191;let _e=L+D*g+H*y+X*m+Z*p+P*f;L=_e>>>13,_e&=8191,_e+=N*u+I*l+O*c+R*a+M*s,L+=_e>>>13,_e&=8191,L=(L<<2)+L|0,L=L+V|0,V=L&8191,L=L>>>13,k+=L,n[0]=V,n[1]=k,n[2]=te,n[3]=ue,n[4]=C,n[5]=be,n[6]=Ee,n[7]=Ce,n[8]=Re,n[9]=_e}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),i=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=i,i=e[s]>>>13,e[s]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+i,i=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(i^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 o=e[0]+t[0];e[0]=o&65535;for(let s=1;s<8;s++)o=(e[s]+t[s]|0)+(o>>>16)|0,e[s]=o&65535;In(r)}update(e){CS(this),jt(e),e=Ja(e);let{buffer:t,blockLen:r}=this,i=e.length;for(let n=0;n<i;){let o=Math.min(r-this.pos,i-n);if(o===r){for(;r<=i-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,In(this.h,this.r,this.buffer,this.pad)}digestInto(e){CS(this),GR(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:i}=this;if(i){t[i++]=1;for(;i<16;i++)t[i]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var sO=XR(32,(e)=>new oO(e));function rV(e,t,r,i,n,o=20){let s=e[0],a=e[1],c=e[2],l=e[3],u=t[0],f=t[1],p=t[2],m=t[3],y=t[4],g=t[5],b=t[6],_=t[7],T=n,A=r[0],z=r[1],j=r[2],E=s,F=a,D=c,H=l,X=u,Z=f,P=p,N=m,I=y,O=g,R=b,M=_,L=T,V=A,k=z,te=j;for(let C=0;C<o;C+=2)E=E+X|0,L=et(L^E,16),I=I+L|0,X=et(X^I,12),E=E+X|0,L=et(L^E,8),I=I+L|0,X=et(X^I,7),F=F+Z|0,V=et(V^F,16),O=O+V|0,Z=et(Z^O,12),F=F+Z|0,V=et(V^F,8),O=O+V|0,Z=et(Z^O,7),D=D+P|0,k=et(k^D,16),R=R+k|0,P=et(P^R,12),D=D+P|0,k=et(k^D,8),R=R+k|0,P=et(P^R,7),H=H+N|0,te=et(te^H,16),M=M+te|0,N=et(N^M,12),H=H+N|0,te=et(te^H,8),M=M+te|0,N=et(N^M,7),E=E+Z|0,te=et(te^E,16),R=R+te|0,Z=et(Z^R,12),E=E+Z|0,te=et(te^E,8),R=R+te|0,Z=et(Z^R,7),F=F+P|0,L=et(L^F,16),M=M+L|0,P=et(P^M,12),F=F+P|0,L=et(L^F,8),M=M+L|0,P=et(P^M,7),D=D+N|0,V=et(V^D,16),I=I+V|0,N=et(N^I,12),D=D+N|0,V=et(V^D,8),I=I+V|0,N=et(N^I,7),H=H+X|0,k=et(k^H,16),O=O+k|0,X=et(X^O,12),H=H+X|0,k=et(k^H,8),O=O+k|0,X=et(X^O,7);let ue=0;i[ue++]=s+E|0,i[ue++]=a+F|0,i[ue++]=c+D|0,i[ue++]=l+H|0,i[ue++]=u+X|0,i[ue++]=f+Z|0,i[ue++]=p+P|0,i[ue++]=m+N|0,i[ue++]=y+I|0,i[ue++]=g+O|0,i[ue++]=b+R|0,i[ue++]=_+M|0,i[ue++]=T+L|0,i[ue++]=A+V|0,i[ue++]=z+k|0,i[ue++]=j+te|0}var nV=iO(rV,{counterRight:!1,counterLength:4,allowShortKeys:!1});var iV=new Uint8Array(16),aO=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(iV.subarray(r))},oV=new Uint8Array(32);function cO(e,t,r,i,n){if(n!==void 0)jt(n,void 0,"AAD");let o=e(t,r,oV),s=tO(i.length,n?n.length:0,!0),a=sO.create(o);if(n)aO(a,n);aO(a,i),a.update(s);let c=a.digest();return In(o,s),c}var sV=(e)=>(t,r,i)=>({encrypt(o,s){let a=o.length;s=xu(a+16,s,!1),s.set(o);let c=s.subarray(0,-16);e(t,r,c,c,1);let l=cO(e,t,r,c,i);return s.set(l,a),In(l),s},decrypt(o,s){s=xu(o.length-16,s,!1);let a=o.subarray(0,-16),c=o.subarray(-16),l=cO(e,t,r,a,i);if(!YR(c,l))throw In(l),Error("invalid tag");return s.set(o.subarray(0,-16)),e(t,r,s,s,1),In(l),s}}),ln=eO({blockSize:64,nonceLength:12,tagLength:16},sV(nV));/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Va(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Kt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Pe(e,t,r=""){let i=Va(e),n=e?.length,o=t!==void 0;if(!i||o&&n!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=i?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+c)}return e}function un(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Kt(e.outputLen),Kt(e.blockLen)}function $i(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 Zp(e,t){Pe(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function Mp(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Br(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Fp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Tn(e,t){return e<<32-t|e>>>t}var aV=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function cV(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function lV(e){for(let t=0;t<e.length;t++)e[t]=cV(e[t]);return e}var OS=aV?(e)=>e:lV,uO=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),uV=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Is(e){if(Pe(e),uO)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=uV[e[r]];return t}var Ai={_0:48,_9:57,A:65,F:70,a:97,f:102};function lO(e){if(e>=Ai._0&&e<=Ai._9)return e-Ai._0;if(e>=Ai.A&&e<=Ai.F)return e-(Ai.A-10);if(e>=Ai.a&&e<=Ai.f)return e-(Ai.a-10);return}function Ts(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(uO)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 i=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){let s=lO(e.charCodeAt(o)),a=lO(e.charCodeAt(o+1));if(s===void 0||a===void 0){let c=e[o]+e[o+1];throw Error('hex string expected, got non-hex character "'+c+'" at index '+o)}i[n]=s*16+a}return i}function Nt(...e){let t=0;for(let i=0;i<e.length;i++){let n=e[i];Pe(n),t+=n.length}let r=new Uint8Array(t);for(let i=0,n=0;i<e.length;i++){let o=e[i];r.set(o,n),n+=o.length}return r}function Wa(e,t={}){let r=(n,o)=>e(o).update(n).digest(),i=e(void 0);return r.outputLen=i.outputLen,r.blockLen=i.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function ho(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 zS=BigInt(0),PS=BigInt(1);function vu(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function dO(e){if(typeof e==="bigint"){if(!Hp(e))throw Error("positive bigint expected, got "+e)}else Kt(e);return e}function _u(e){let t=dO(e).toString(16);return t.length&1?"0"+t:t}function fO(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?zS:BigInt("0x"+e)}function yo(e){return fO(Is(e))}function bo(e){return fO(Is(Kp(Pe(e)).reverse()))}function Ga(e,t){Kt(t),e=dO(e);let r=Ts(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function ku(e,t){return Ga(e,t).reverse()}function Kp(e){return Uint8Array.from(e)}function So(e){return Uint8Array.from(e,(t,r)=>{let i=t.charCodeAt(0);if(t.length!==1||i>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${i} at position ${r}`);return i})}var Hp=(e)=>typeof e==="bigint"&&zS<=e;function dV(e,t,r){return Hp(e)&&Hp(t)&&Hp(r)&&t<=e&&e<r}function Eu(e,t,r,i){if(!dV(t,r,i))throw Error("expected valid "+e+": "+r+" <= n < "+i+", got "+t)}function NS(e){let t;for(t=0;e>zS;e>>=PS,t+=1);return t}var Iu=(e)=>(PS<<BigInt(e))-PS;function pO(e,t,r){if(Kt(e,"hashLen"),Kt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let i=(b)=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=i(e),l=i(e),u=0,f=()=>{c.fill(1),l.fill(0),u=0},p=(...b)=>r(l,Nt(c,...b)),m=(b=n)=>{if(l=p(o,b),c=p(),b.length===0)return;l=p(s,b),c=p()},y=()=>{if(u++>=a)throw Error("drbg: tried max amount of iterations");let b=0,_=[];while(b<t){c=p();let T=c.slice();_.push(T),b+=c.length}return Nt(..._)};return(b,_)=>{f(),m(b);let T=void 0;while(!(T=_(y())))m();return f(),T}}function As(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function i(o,s,a){let c=e[o];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw Error(`param "${o}" is invalid: expected ${s}, got ${l}`)}let n=(o,s)=>Object.entries(o).forEach(([a,c])=>i(a,c,s));n(t,!1),n(r,!0)}function DS(e){let t=new WeakMap;return(r,...i)=>{let n=t.get(r);if(n!==void 0)return n;let o=e(r,...i);return t.set(r,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Ir=BigInt(0),mr=BigInt(1),$s=BigInt(2),gO=BigInt(3),yO=BigInt(4),bO=BigInt(5),fV=BigInt(7),SO=BigInt(8),pV=BigInt(9),xO=BigInt(16);function Er(e,t){let r=e%t;return r>=Ir?r:t+r}function dn(e,t,r){let i=e;while(t-- >Ir)i*=i,i%=r;return i}function mO(e,t){if(e===Ir)throw Error("invert: expected non-zero number");if(t<=Ir)throw Error("invert: expected positive modulus, got "+t);let r=Er(e,t),i=t,n=Ir,o=mr,s=mr,a=Ir;while(r!==Ir){let l=i/r,u=i%r,f=n-s*l,p=o-a*l;i=r,r=u,n=s,o=a,s=f,a=p}if(i!==mr)throw Error("invert: does not exist");return Er(n,t)}function LS(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function wO(e,t){let r=(e.ORDER+mr)/yO,i=e.pow(t,r);return LS(e,i,t),i}function mV(e,t){let r=(e.ORDER-bO)/SO,i=e.mul(t,$s),n=e.pow(i,r),o=e.mul(t,n),s=e.mul(e.mul(o,$s),n),a=e.mul(o,e.sub(s,e.ONE));return LS(e,a,t),a}function hV(e){let t=Jp(e),r=vO(e),i=r(t,t.neg(t.ONE)),n=r(t,i),o=r(t,t.neg(i)),s=(e+fV)/xO;return(a,c)=>{let l=a.pow(c,s),u=a.mul(l,i),f=a.mul(l,n),p=a.mul(l,o),m=a.eql(a.sqr(u),c),y=a.eql(a.sqr(f),c);l=a.cmov(l,u,m),u=a.cmov(p,f,y);let g=a.eql(a.sqr(u),c),b=a.cmov(l,u,g);return LS(a,b,c),b}}function vO(e){if(e<gO)throw Error("sqrt is not defined for small field");let t=e-mr,r=0;while(t%$s===Ir)t/=$s,r++;let i=$s,n=Jp(e);while(hO(n,i)===1)if(i++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return wO;let o=n.pow(i,t),s=(t+mr)/$s;return function(c,l){if(c.is0(l))return l;if(hO(c,l)!==1)throw Error("Cannot find square root");let u=r,f=c.mul(c.ONE,o),p=c.pow(l,t),m=c.pow(l,s);while(!c.eql(p,c.ONE)){if(c.is0(p))return c.ZERO;let y=1,g=c.sqr(p);while(!c.eql(g,c.ONE))if(y++,g=c.sqr(g),y===u)throw Error("Cannot find square root");let b=mr<<BigInt(u-y-1),_=c.pow(f,b);u=y,f=c.sqr(_),p=c.mul(p,f),m=c.mul(m,_)}return m}}function gV(e){if(e%yO===gO)return wO;if(e%SO===bO)return mV;if(e%xO===pV)return hV(e);return vO(e)}var yV=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function BS(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=yV.reduce((i,n)=>(i[n]="function",i),t);return As(e,r),e}function bV(e,t,r){if(r<Ir)throw Error("invalid exponent, negatives unsupported");if(r===Ir)return e.ONE;if(r===mr)return t;let i=e.ONE,n=t;while(r>Ir){if(r&mr)i=e.mul(i,n);n=e.sqr(n),r>>=mr}return i}function Tu(e,t,r=!1){let i=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,c)=>{if(e.is0(a))return s;return i[c]=s,e.mul(s,a)},e.ONE),o=e.inv(n);return t.reduceRight((s,a,c)=>{if(e.is0(a))return s;return i[c]=e.mul(s,i[c]),e.mul(s,a)},o),i}function hO(e,t){let r=(e.ORDER-mr)/$s,i=e.pow(t,r),n=e.eql(i,e.ONE),o=e.eql(i,e.ZERO),s=e.eql(i,e.neg(e.ONE));if(!n&&!o&&!s)throw Error("invalid Legendre symbol result");return n?1:o?0:-1}function SV(e,t){if(t!==void 0)Kt(t);let r=t!==void 0?t:e.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}class _O{ORDER;BITS;BYTES;isLE;ZERO=Ir;ONE=mr;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Ir)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:i,nByteLength:n}=SV(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Er(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return Ir<=e&&e<this.ORDER}is0(e){return e===Ir}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&mr)===mr}neg(e){return Er(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Er(e*e,this.ORDER)}add(e,t){return Er(e+t,this.ORDER)}sub(e,t){return Er(e-t,this.ORDER)}mul(e,t){return Er(e*t,this.ORDER)}pow(e,t){return bV(this,e,t)}div(e,t){return Er(e*mO(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 mO(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=gV(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?ku(e,this.BYTES):Ga(e,this.BYTES)}fromBytes(e,t=!1){Pe(e);let{_lengths:r,BYTES:i,isLE:n,ORDER:o,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>i)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(i);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==i)throw Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=n?bo(e):yo(e);if(s)a=Er(a,o);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Tu(this,e)}cmov(e,t,r){return r?t:e}}function Jp(e,t={}){return new _O(e,t)}function kO(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function jS(e){let t=kO(e);return t+Math.ceil(t/2)}function EO(e,t,r=!1){Pe(e);let i=e.length,n=kO(t),o=jS(t);if(i<16||i<o||i>1024)throw Error("expected "+o+"-1024 bytes of input, got "+i);let s=r?bo(e):yo(e),a=Er(s,t-mr)+mr;return r?ku(a,n):Ga(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Qa=BigInt(0),Cs=BigInt(1);function Au(e,t){let r=t.negate();return e?r:t}function MS(e,t){let r=Tu(e.Fp,t.map((i)=>i.Z));return t.map((i,n)=>e.fromAffine(i.toAffine(r[n])))}function $O(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function US(e,t){$O(e,t);let r=Math.ceil(t/e)+1,i=2**(e-1),n=2**e,o=Iu(e),s=BigInt(e);return{windows:r,windowSize:i,mask:o,maxNumber:n,shiftBy:s}}function IO(e,t,r){let{windowSize:i,mask:n,maxNumber:o,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>i)a-=o,c+=Cs;let l=t*i,u=l+Math.abs(a)-1,f=a===0,p=a<0,m=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:m,offsetF:l}}var qS=new WeakMap,CO=new WeakMap;function ZS(e){return CO.get(e)||1}function TO(e){if(e!==Qa)throw Error("invalid wNAF")}class FS{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 i=e;while(t>Qa){if(t&Cs)r=r.add(i);i=i.double(),t>>=Cs}return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=US(t,this.bits),n=[],o=e,s=o;for(let a=0;a<r;a++){s=o,n.push(s);for(let c=1;c<i;c++)s=s.add(o),n.push(s);o=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let i=this.ZERO,n=this.BASE,o=US(e,this.bits);for(let s=0;s<o.windows;s++){let{nextN:a,offset:c,isZero:l,isNeg:u,isNegF:f,offsetF:p}=IO(r,s,o);if(r=a,l)n=n.add(Au(f,t[p]));else i=i.add(Au(u,t[c]))}return TO(r),{p:i,f:n}}wNAFUnsafe(e,t,r,i=this.ZERO){let n=US(e,this.bits);for(let o=0;o<n.windows;o++){if(r===Qa)break;let{nextN:s,offset:a,isZero:c,isNeg:l}=IO(r,o,n);if(r=s,c)continue;else{let u=t[a];i=i.add(l?u.negate():u)}}return TO(r),i}getPrecomputes(e,t,r){let i=qS.get(t);if(!i){if(i=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")i=r(i);qS.set(t,i)}}return i}cached(e,t,r){let i=ZS(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let n=ZS(e);if(n===1)return this._unsafeLadder(e,t,i);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,i)}createCache(e,t){$O(t,this.bits),CO.set(e,t),qS.delete(e)}hasCache(e){return ZS(e)!==1}}function RO(e,t,r,i){let n=t,o=e.ZERO,s=e.ZERO;while(r>Qa||i>Qa){if(r&Cs)o=o.add(n);if(i&Cs)s=s.add(n);n=n.double(),r>>=Cs,i>>=Cs}return{p1:o,p2:s}}function AO(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return BS(t),t}else return Jp(e,{isLE:r})}function OO(e,t,r={},i){if(i===void 0)i=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l==="bigint"&&l>Qa))throw Error(`CURVE.${c} must be positive bigint`)}let n=AO(t.p,r.Fp,i),o=AO(t.n,r.Fn,i),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:o}}function Vp(e,t){return function(i){let n=e(i);return{secretKey:n,publicKey:t(n)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $u=BigInt(0),Ya=BigInt(1),Wp=BigInt(2);function xV(e){return As(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function PO(e){let t=xV(e),{P:r,type:i,adjustScalarBytes:n,powPminus2:o,randomBytes:s}=t,a=i==="x25519";if(!a&&i!=="x448")throw Error("invalid type");let c=s||ho,l=a?255:448,u=a?32:56,f=a?BigInt(9):BigInt(5),p=a?BigInt(121665):BigInt(39081),m=a?Wp**BigInt(254):Wp**BigInt(447),y=a?BigInt(8)*Wp**BigInt(251)-Ya:BigInt(4)*Wp**BigInt(445)-Ya,g=m+y+Ya,b=(I)=>Er(I,r),_=T(f);function T(I){return ku(b(I),u)}function A(I){let O=Kp(Pe(I,u,"uCoordinate"));if(a)O[31]&=127;return b(bo(O))}function z(I){return bo(n(Kp(Pe(I,u,"scalar"))))}function j(I,O){let R=X(A(O),z(I));if(R===$u)throw Error("invalid private or public key received");return T(R)}function E(I){return j(I,_)}let F=E,D=j;function H(I,O,R){let M=b(I*(O-R));return O=b(O-M),R=b(R+M),{x_2:O,x_3:R}}function X(I,O){Eu("u",I,$u,r),Eu("scalar",O,m,g);let R=O,M=I,L=Ya,V=$u,k=I,te=Ya,ue=$u;for(let be=BigInt(l-1);be>=$u;be--){let Ee=R>>be&Ya;ue^=Ee,{x_2:L,x_3:k}=H(ue,L,k),{x_2:V,x_3:te}=H(ue,V,te),ue=Ee;let Ce=L+V,Re=b(Ce*Ce),_e=L-V,Je=b(_e*_e),Ne=Re-Je,Ye=k+te,mt=k-te,zt=b(mt*Ce),dr=b(Ye*_e),Kr=zt+dr,Jr=zt-dr;k=b(Kr*Kr),te=b(M*b(Jr*Jr)),L=b(Re*Je),V=b(Ne*(Re+b(p*Ne)))}({x_2:L,x_3:k}=H(ue,L,k)),{x_2:V,x_3:te}=H(ue,V,te);let C=o(V);return b(L*C)}let Z={secretKey:u,publicKey:u,seed:u},P=(I=c(u))=>(Pe(I,Z.seed,"seed"),I),N={randomSecretKey:P};return Object.freeze({keygen:Vp(P,F),getSharedSecret:D,getPublicKey:F,scalarMult:j,scalarMultBase:E,utils:N,GuBytes:_.slice(),lengths:Z})}class HS{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(un(e),Pe(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,i=new Uint8Array(r);i.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<i.length;n++)i[n]^=54;this.iHash.update(i),this.oHash=e.create();for(let n=0;n<i.length;n++)i[n]^=106;this.oHash.update(i),Br(i)}update(e){return $i(this),this.iHash.update(e),this}digestInto(e){$i(this),Pe(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:i,destroyed:n,blockLen:o,outputLen:s}=this;return e=e,e.finished=i,e.destroyed=n,e.blockLen=o,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 Xa=(e,t,r)=>new HS(e,t).update(r).digest();Xa.create=(e,t)=>new HS(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zO=(e,t)=>(e+(e>=0?t:-t)/DO)/t;function wV(e,t,r){let[[i,n],[o,s]]=t,a=zO(s*e,r),c=zO(-n*e,r),l=e-a*i-c*o,u=-a*n-c*s,f=l<Ci,p=u<Ci;if(f)l=-l;if(p)u=-u;let m=Iu(Math.ceil(NS(r)/2))+ec;if(l<Ci||l>=m||u<Ci||u>=m)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:f,k1:l,k2neg:p,k2:u}}function JS(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function KS(e,t){let r={};for(let i of Object.keys(t))r[i]=e[i]===void 0?t[i]:e[i];if(vu(r.lowS,"lowS"),vu(r.prehash,"prehash"),r.format!==void 0)JS(r.format);return r}class NO extends Error{constructor(e=""){super(e)}}var xo={Err:NO,_tlv:{encode:(e,t)=>{let{Err:r}=xo;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let i=t.length/2,n=_u(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let o=i>127?_u(n.length/2|128):"";return _u(e)+o+n+t},decode(e,t){let{Err:r}=xo,i=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[i++],o=!!(n&128),s=0;if(!o)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 l=t.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(i+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(i,i+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(i+s)}}},_int:{encode(e){let{Err:t}=xo;if(e<Ci)throw new t("integer: negative integers are not allowed");let r=_u(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}=xo;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 yo(e)}},toSig(e){let{Err:t,_int:r,_tlv:i}=xo,n=Pe(e,void 0,"signature"),{v:o,l:s}=i.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=i.decode(2,o),{v:l,l:u}=i.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=xo,i=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),o=i+n;return t.encode(48,o)}},Ci=BigInt(0),ec=BigInt(1),DO=BigInt(2),Gp=BigInt(3),vV=BigInt(4);function VS(e,t={}){let r=OO("weierstrass",e,t),{Fp:i,Fn:n}=r,o=r.CURVE,{h:s,n:a}=o;As(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c){if(!i.is0(o.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let l=BO(i,n);function u(){if(!i.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function f(P,N,I){let{x:O,y:R}=N.toAffine(),M=i.toBytes(O);if(vu(I,"isCompressed"),I){u();let L=!i.isOdd(R);return Nt(LO(L),M)}else return Nt(Uint8Array.of(4),M,i.toBytes(R))}function p(P){Pe(P,void 0,"Point");let{publicKey:N,publicKeyUncompressed:I}=l,O=P.length,R=P[0],M=P.subarray(1);if(O===N&&(R===2||R===3)){let L=i.fromBytes(M);if(!i.isValid(L))throw Error("bad point: is not on curve, wrong x");let V=g(L),k;try{k=i.sqrt(V)}catch(C){let be=C instanceof Error?": "+C.message:"";throw Error("bad point: is not on curve, sqrt error"+be)}u();let te=i.isOdd(k);if((R&1)===1!==te)k=i.neg(k);return{x:L,y:k}}else if(O===I&&R===4){let L=i.BYTES,V=i.fromBytes(M.subarray(0,L)),k=i.fromBytes(M.subarray(L,L*2));if(!b(V,k))throw Error("bad point: is not on curve");return{x:V,y:k}}else throw Error(`bad point: got length ${O}, expected compressed=${N} or uncompressed=${I}`)}let m=t.toBytes||f,y=t.fromBytes||p;function g(P){let N=i.sqr(P),I=i.mul(N,P);return i.add(i.add(I,i.mul(P,o.a)),o.b)}function b(P,N){let I=i.sqr(N),O=g(P);return i.eql(I,O)}if(!b(o.Gx,o.Gy))throw Error("bad curve params: generator point");let _=i.mul(i.pow(o.a,Gp),vV),T=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(_,T)))throw Error("bad curve params: a or b");function A(P,N,I=!1){if(!i.isValid(N)||I&&i.is0(N))throw Error(`bad point coordinate ${P}`);return N}function z(P){if(!(P instanceof H))throw Error("Weierstrass Point expected")}function j(P){if(!c||!c.basises)throw Error("no endo");return wV(P,c.basises,n.ORDER)}let E=DS((P,N)=>{let{X:I,Y:O,Z:R}=P;if(i.eql(R,i.ONE))return{x:I,y:O};let M=P.is0();if(N==null)N=M?i.ONE:i.inv(R);let L=i.mul(I,N),V=i.mul(O,N),k=i.mul(R,N);if(M)return{x:i.ZERO,y:i.ZERO};if(!i.eql(k,i.ONE))throw Error("invZ was invalid");return{x:L,y:V}}),F=DS((P)=>{if(P.is0()){if(t.allowInfinityPoint&&!i.is0(P.Y))return;throw Error("bad point: ZERO")}let{x:N,y:I}=P.toAffine();if(!i.isValid(N)||!i.isValid(I))throw Error("bad point: x or y not field elements");if(!b(N,I))throw Error("bad point: equation left != right");if(!P.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function D(P,N,I,O,R){return I=new H(i.mul(I.X,P),I.Y,I.Z),N=Au(O,N),I=Au(R,I),N.add(I)}class H{static BASE=new H(o.Gx,o.Gy,i.ONE);static ZERO=new H(i.ZERO,i.ONE,i.ZERO);static Fp=i;static Fn=n;X;Y;Z;constructor(P,N,I){this.X=A("x",P),this.Y=A("y",N,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return o}static fromAffine(P){let{x:N,y:I}=P||{};if(!P||!i.isValid(N)||!i.isValid(I))throw Error("invalid affine point");if(P instanceof H)throw Error("projective point not allowed");if(i.is0(N)&&i.is0(I))return H.ZERO;return new H(N,I,i.ONE)}static fromBytes(P){let N=H.fromAffine(y(Pe(P,void 0,"point")));return N.assertValidity(),N}static fromHex(P){return H.fromBytes(Ts(P))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(P=8,N=!0){if(Z.createCache(this,P),!N)this.multiply(Gp);return this}assertValidity(){F(this)}hasEvenY(){let{y:P}=this.toAffine();if(!i.isOdd)throw Error("Field doesn't support isOdd");return!i.isOdd(P)}equals(P){z(P);let{X:N,Y:I,Z:O}=this,{X:R,Y:M,Z:L}=P,V=i.eql(i.mul(N,L),i.mul(R,O)),k=i.eql(i.mul(I,L),i.mul(M,O));return V&&k}negate(){return new H(this.X,i.neg(this.Y),this.Z)}double(){let{a:P,b:N}=o,I=i.mul(N,Gp),{X:O,Y:R,Z:M}=this,L=i.ZERO,V=i.ZERO,k=i.ZERO,te=i.mul(O,O),ue=i.mul(R,R),C=i.mul(M,M),be=i.mul(O,R);return be=i.add(be,be),k=i.mul(O,M),k=i.add(k,k),L=i.mul(P,k),V=i.mul(I,C),V=i.add(L,V),L=i.sub(ue,V),V=i.add(ue,V),V=i.mul(L,V),L=i.mul(be,L),k=i.mul(I,k),C=i.mul(P,C),be=i.sub(te,C),be=i.mul(P,be),be=i.add(be,k),k=i.add(te,te),te=i.add(k,te),te=i.add(te,C),te=i.mul(te,be),V=i.add(V,te),C=i.mul(R,M),C=i.add(C,C),te=i.mul(C,be),L=i.sub(L,te),k=i.mul(C,ue),k=i.add(k,k),k=i.add(k,k),new H(L,V,k)}add(P){z(P);let{X:N,Y:I,Z:O}=this,{X:R,Y:M,Z:L}=P,V=i.ZERO,k=i.ZERO,te=i.ZERO,ue=o.a,C=i.mul(o.b,Gp),be=i.mul(N,R),Ee=i.mul(I,M),Ce=i.mul(O,L),Re=i.add(N,I),_e=i.add(R,M);Re=i.mul(Re,_e),_e=i.add(be,Ee),Re=i.sub(Re,_e),_e=i.add(N,O);let Je=i.add(R,L);return _e=i.mul(_e,Je),Je=i.add(be,Ce),_e=i.sub(_e,Je),Je=i.add(I,O),V=i.add(M,L),Je=i.mul(Je,V),V=i.add(Ee,Ce),Je=i.sub(Je,V),te=i.mul(ue,_e),V=i.mul(C,Ce),te=i.add(V,te),V=i.sub(Ee,te),te=i.add(Ee,te),k=i.mul(V,te),Ee=i.add(be,be),Ee=i.add(Ee,be),Ce=i.mul(ue,Ce),_e=i.mul(C,_e),Ee=i.add(Ee,Ce),Ce=i.sub(be,Ce),Ce=i.mul(ue,Ce),_e=i.add(_e,Ce),be=i.mul(Ee,_e),k=i.add(k,be),be=i.mul(Je,_e),V=i.mul(Re,V),V=i.sub(V,be),be=i.mul(Re,Ee),te=i.mul(Je,te),te=i.add(te,be),new H(V,k,te)}subtract(P){return this.add(P.negate())}is0(){return this.equals(H.ZERO)}multiply(P){let{endo:N}=t;if(!n.isValidNot0(P))throw Error("invalid scalar: out of range");let I,O,R=(M)=>Z.cached(this,M,(L)=>MS(H,L));if(N){let{k1neg:M,k1:L,k2neg:V,k2:k}=j(P),{p:te,f:ue}=R(L),{p:C,f:be}=R(k);O=ue.add(be),I=D(N.beta,te,C,M,V)}else{let{p:M,f:L}=R(P);I=M,O=L}return MS(H,[I,O])[0]}multiplyUnsafe(P){let{endo:N}=t,I=this;if(!n.isValid(P))throw Error("invalid scalar: out of range");if(P===Ci||I.is0())return H.ZERO;if(P===ec)return I;if(Z.hasCache(this))return this.multiply(P);if(N){let{k1neg:O,k1:R,k2neg:M,k2:L}=j(P),{p1:V,p2:k}=RO(H,I,R,L);return D(N.beta,V,k,O,M)}else return Z.unsafe(I,P)}toAffine(P){return E(this,P)}isTorsionFree(){let{isTorsionFree:P}=t;if(s===ec)return!0;if(P)return P(H,this);return Z.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:P}=t;if(s===ec)return this;if(P)return P(H,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(P=!0){return vu(P,"isCompressed"),this.assertValidity(),m(H,this,P)}toHex(P=!0){return Is(this.toBytes(P))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=n.BITS,Z=new FS(H,t.endo?Math.ceil(X/2):X);return H.BASE.precompute(8),H}function LO(e){return Uint8Array.of(e?2:3)}function BO(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function _V(e,t={}){let{Fn:r}=e,i=t.randomBytes||ho,n=Object.assign(BO(e.Fp,r),{seed:jS(r.ORDER)});function o(m){try{let y=r.fromBytes(m);return r.isValidNot0(y)}catch(y){return!1}}function s(m,y){let{publicKey:g,publicKeyUncompressed:b}=n;try{let _=m.length;if(y===!0&&_!==g)return!1;if(y===!1&&_!==b)return!1;return!!e.fromBytes(m)}catch(_){return!1}}function a(m=i(n.seed)){return EO(Pe(m,n.seed,"seed"),r.ORDER)}function c(m,y=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(y)}function l(m){let{secretKey:y,publicKey:g,publicKeyUncompressed:b}=n;if(!Va(m))return;if("_lengths"in r&&r._lengths||y===g)return;let _=Pe(m,void 0,"key").length;return _===g||_===b}function u(m,y,g=!0){if(l(m)===!0)throw Error("first arg must be private key");if(l(y)===!1)throw Error("second arg must be public key");let b=r.fromBytes(m);return e.fromBytes(y).multiply(b).toBytes(g)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a},p=Vp(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:f,lengths:n})}function WS(e,t,r={}){un(t),As(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let i=r.randomBytes||ho,n=r.hmac||((I,O)=>Xa(t,I,O)),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:p,lengths:m}=_V(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},g=a*DO<o.ORDER;function b(I){let O=a>>ec;return I>O}function _(I,O){if(!s.isValidNot0(O))throw Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return O}function T(){if(g)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(I,O){JS(O);let R=m.signature,M=O==="compact"?R:O==="recovered"?R+1:void 0;return Pe(I,M)}class z{r;s;recovery;constructor(I,O,R){if(this.r=_("r",I),this.s=_("s",O),R!=null){if(T(),![0,1,2,3].includes(R))throw Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(I,O=y.format){A(I,O);let R;if(O==="der"){let{r:k,s:te}=xo.toSig(Pe(I));return new z(k,te)}if(O==="recovered")R=I[0],O="compact",I=I.subarray(1);let M=m.signature/2,L=I.subarray(0,M),V=I.subarray(M,M*2);return new z(s.fromBytes(L),s.fromBytes(V),R)}static fromHex(I,O){return this.fromBytes(Ts(I),O)}assertRecovery(){let{recovery:I}=this;if(I==null)throw Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new z(this.r,this.s,I)}recoverPublicKey(I){let{r:O,s:R}=this,M=this.assertRecovery(),L=M===2||M===3?O+a:O;if(!o.isValid(L))throw Error("invalid recovery id: sig.r+curve.n != R.x");let V=o.toBytes(L),k=e.fromBytes(Nt(LO((M&1)===0),V)),te=s.inv(L),ue=E(Pe(I,void 0,"msgHash")),C=s.create(-ue*te),be=s.create(R*te),Ee=e.BASE.multiplyUnsafe(C).add(k.multiplyUnsafe(be));if(Ee.is0())throw Error("invalid recovery: point at infinify");return Ee.assertValidity(),Ee}hasHighS(){return b(this.s)}toBytes(I=y.format){if(JS(I),I==="der")return Ts(xo.hexFromSig(this));let{r:O,s:R}=this,M=s.toBytes(O),L=s.toBytes(R);if(I==="recovered")return T(),Nt(Uint8Array.of(this.assertRecovery()),M,L);return Nt(M,L)}toHex(I){return Is(this.toBytes(I))}}let j=r.bits2int||function(O){if(O.length>8192)throw Error("input is too large");let R=yo(O),M=O.length*8-c;return M>0?R>>BigInt(M):R},E=r.bits2int_modN||function(O){return s.create(j(O))},F=Iu(c);function D(I){return Eu("num < 2^"+c,I,Ci,F),s.toBytes(I)}function H(I,O){return Pe(I,void 0,"message"),O?Pe(t(I),void 0,"prehashed message"):I}function X(I,O,R){let{lowS:M,prehash:L,extraEntropy:V}=KS(R,y);I=H(I,L);let k=E(I),te=s.fromBytes(O);if(!s.isValidNot0(te))throw Error("invalid private key");let ue=[D(te),D(k)];if(V!=null&&V!==!1){let Ce=V===!0?i(m.secretKey):V;ue.push(Pe(Ce,void 0,"extraEntropy"))}let C=Nt(...ue),be=k;function Ee(Ce){let Re=j(Ce);if(!s.isValidNot0(Re))return;let _e=s.inv(Re),Je=e.BASE.multiply(Re).toAffine(),Ne=s.create(Je.x);if(Ne===Ci)return;let Ye=s.create(_e*s.create(be+Ne*te));if(Ye===Ci)return;let mt=(Je.x===Ne?0:2)|Number(Je.y&ec),zt=Ye;if(M&&b(Ye))zt=s.neg(Ye),mt^=1;return new z(Ne,zt,g?void 0:mt)}return{seed:C,k2sig:Ee}}function Z(I,O,R={}){let{seed:M,k2sig:L}=X(I,O,R);return pO(t.outputLen,s.BYTES,n)(M,L).toBytes(R.format)}function P(I,O,R,M={}){let{lowS:L,prehash:V,format:k}=KS(M,y);if(R=Pe(R,void 0,"publicKey"),O=H(O,V),!Va(I)){let te=I instanceof z?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+te)}A(I,k);try{let te=z.fromBytes(I,k),ue=e.fromBytes(R);if(L&&te.hasHighS())return!1;let{r:C,s:be}=te,Ee=E(O),Ce=s.inv(be),Re=s.create(Ee*Ce),_e=s.create(C*Ce),Je=e.BASE.multiplyUnsafe(Re).add(ue.multiplyUnsafe(_e));if(Je.is0())return!1;return s.create(Je.x)===C}catch(te){return!1}}function N(I,O,R={}){let{prehash:M}=KS(R,y);return O=H(O,M),z.fromBytes(I,"recovered").recoverPublicKey(O).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:p,lengths:m,Point:e,sign:Z,verify:P,recoverPublicKey:N,Signature:z,hash:t})}function jO(e,t,r){return e&t^~e&r}function UO(e,t,r){return e&t^e&r^t&r}class Qp{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,i){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Fp(this.buffer)}update(e){$i(this),Pe(e);let{view:t,buffer:r,blockLen:i}=this,n=e.length;for(let o=0;o<n;){let s=Math.min(i-this.pos,n-o);if(s===i){let a=Fp(e);for(;i<=n-o;o+=i)this.process(a,o);continue}if(r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===i)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){$i(this),Zp(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:o}=this;if(t[o++]=128,Br(this.buffer.subarray(o)),this.padOffset>i-o)this.process(r,0),o=0;for(let u=o;u<i;u++)t[u]=0;r.setBigUint64(i-8,BigInt(this.length*8),n),this.process(r,0);let s=Fp(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)s.setUint32(4*u,l[u],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:i,finished:n,destroyed:o,pos:s}=this;if(e.destroyed=o,e.finished=n,e.length=i,e.pos=s,i%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var Ri=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var tr=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);var Yp=BigInt(4294967295),qO=BigInt(32);function kV(e,t=!1){if(t)return{h:Number(e&Yp),l:Number(e>>qO&Yp)};return{h:Number(e>>qO&Yp)|0,l:Number(e&Yp)|0}}function Xp(e,t=!1){let r=e.length,i=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=kV(e[o],t);[i[o],n[o]]=[s,a]}return[i,n]}var GS=(e,t,r)=>e>>>r,QS=(e,t,r)=>e<<32-r|t>>>r,Rs=(e,t,r)=>e>>>r|t<<32-r,Os=(e,t,r)=>e<<32-r|t>>>r,Cu=(e,t,r)=>e<<64-r|t>>>r-32,Ru=(e,t,r)=>e>>>r-32|t<<64-r;var ZO=(e,t,r)=>e<<r|t>>>32-r,MO=(e,t,r)=>t<<r|e>>>32-r,FO=(e,t,r)=>t<<r-32|e>>>64-r,HO=(e,t,r)=>e<<r-32|t>>>64-r;function Qn(e,t,r,i){let n=(t>>>0)+(i>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var KO=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),JO=(e,t,r,i)=>t+r+i+(e/4294967296|0)|0,VO=(e,t,r,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0),WO=(e,t,r,i,n)=>t+r+i+n+(e/4294967296|0)|0,GO=(e,t,r,i,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(i>>>0)+(n>>>0),QO=(e,t,r,i,n,o)=>t+r+i+n+o+(e/4294967296|0)|0;var IV=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]),wo=new Uint32Array(64);class YO extends Qp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:i,E:n,F:o,G:s,H:a}=this;return[e,t,r,i,n,o,s,a]}set(e,t,r,i,n,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=n|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let u=0;u<16;u++,t+=4)wo[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){let f=wo[u-15],p=wo[u-2],m=Tn(f,7)^Tn(f,18)^f>>>3,y=Tn(p,17)^Tn(p,19)^p>>>10;wo[u]=y+wo[u-7]+m+wo[u-16]|0}let{A:r,B:i,C:n,D:o,E:s,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){let f=Tn(s,6)^Tn(s,11)^Tn(s,25),p=l+f+jO(s,a,c)+IV[u]+wo[u]|0,y=(Tn(r,2)^Tn(r,13)^Tn(r,22))+UO(r,i,n)|0;l=c,c=a,a=s,s=o+p|0,o=n,n=i,i=r,r=p+y|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,i,n,o,s,a,c,l)}roundClean(){Br(wo)}destroy(){this.set(0,0,0,0,0,0,0,0),Br(this.buffer)}}class XO extends YO{A=Ri[0]|0;B=Ri[1]|0;C=Ri[2]|0;D=Ri[3]|0;E=Ri[4]|0;F=Ri[5]|0;G=Ri[6]|0;H=Ri[7]|0;constructor(){super(32)}}var eP=(()=>Xp(["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))))(),TV=(()=>eP[0])(),AV=(()=>eP[1])(),vo=new Uint32Array(80),_o=new Uint32Array(80);class tP extends Qp{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:i,Ch:n,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:f,Gh:p,Gl:m,Hh:y,Hl:g}=this;return[e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g]}set(e,t,r,i,n,o,s,a,c,l,u,f,p,m,y,g){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=i|0,this.Ch=n|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=f|0,this.Gh=p|0,this.Gl=m|0,this.Hh=y|0,this.Hl=g|0}process(e,t){for(let T=0;T<16;T++,t+=4)vo[T]=e.getUint32(t),_o[T]=e.getUint32(t+=4);for(let T=16;T<80;T++){let A=vo[T-15]|0,z=_o[T-15]|0,j=Rs(A,z,1)^Rs(A,z,8)^GS(A,z,7),E=Os(A,z,1)^Os(A,z,8)^QS(A,z,7),F=vo[T-2]|0,D=_o[T-2]|0,H=Rs(F,D,19)^Cu(F,D,61)^GS(F,D,6),X=Os(F,D,19)^Ru(F,D,61)^QS(F,D,6),Z=VO(E,X,_o[T-7],_o[T-16]),P=WO(Z,j,H,vo[T-7],vo[T-16]);vo[T]=P|0,_o[T]=Z|0}let{Ah:r,Al:i,Bh:n,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:f,Fh:p,Fl:m,Gh:y,Gl:g,Hh:b,Hl:_}=this;for(let T=0;T<80;T++){let A=Rs(u,f,14)^Rs(u,f,18)^Cu(u,f,41),z=Os(u,f,14)^Os(u,f,18)^Ru(u,f,41),j=u&p^~u&y,E=f&m^~f&g,F=GO(_,z,E,AV[T],_o[T]),D=QO(F,b,A,j,TV[T],vo[T]),H=F|0,X=Rs(r,i,28)^Cu(r,i,34)^Cu(r,i,39),Z=Os(r,i,28)^Ru(r,i,34)^Ru(r,i,39),P=r&n^r&s^n&s,N=i&o^i&a^o&a;b=y|0,_=g|0,y=p|0,g=m|0,p=u|0,m=f|0,{h:u,l:f}=Qn(c|0,l|0,D|0,H|0),c=s|0,l=a|0,s=n|0,a=o|0,n=r|0,o=i|0;let I=KO(H,Z,N);r=JO(I,D,X,P),i=I|0}({h:r,l:i}=Qn(this.Ah|0,this.Al|0,r|0,i|0)),{h:n,l:o}=Qn(this.Bh|0,this.Bl|0,n|0,o|0),{h:s,l:a}=Qn(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l}=Qn(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:f}=Qn(this.Eh|0,this.El|0,u|0,f|0),{h:p,l:m}=Qn(this.Fh|0,this.Fl|0,p|0,m|0),{h:y,l:g}=Qn(this.Gh|0,this.Gl|0,y|0,g|0),{h:b,l:_}=Qn(this.Hh|0,this.Hl|0,b|0,_|0),this.set(r,i,n,o,s,a,c,l,u,f,p,m,y,g,b,_)}roundClean(){Br(vo,_o)}destroy(){Br(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class rP extends tP{Ah=tr[0]|0;Al=tr[1]|0;Bh=tr[2]|0;Bl=tr[3]|0;Ch=tr[4]|0;Cl=tr[5]|0;Dh=tr[6]|0;Dl=tr[7]|0;Eh=tr[8]|0;El=tr[9]|0;Fh=tr[10]|0;Fl=tr[11]|0;Gh=tr[12]|0;Gl=tr[13]|0;Hh=tr[14]|0;Hl=tr[15]|0;constructor(){super(48)}}var em=Wa(()=>new XO,go(1));var nP=Wa(()=>new rP,go(2));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var $V=BigInt(1),iP=BigInt(2),CV=BigInt(3),RV=BigInt(5),Vwe=BigInt(8),oP=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");function OV(e){let t=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),o=oP,a=e*e%o*e%o,c=dn(a,iP,o)*a%o,l=dn(c,$V,o)*e%o,u=dn(l,RV,o)*l%o,f=dn(u,t,o)*u%o,p=dn(f,r,o)*f%o,m=dn(p,i,o)*p%o,y=dn(m,n,o)*m%o,g=dn(y,n,o)*m%o,b=dn(g,t,o)*u%o;return{pow_p_5_8:dn(b,iP,o)*e%o,b2:a}}function PV(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var sP=(()=>{let e=oP;return PO({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:i}=OV(t);return Er(dn(r,CV,e)*i,e)},adjustScalarBytes:PV})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var zV=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),NV=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))();var DV=VS(zV),YS=WS(DV,em);var LV=VS(NV),aP=WS(LV,nP);function lP(e,t,r){if(un(e),r===void 0)r=new Uint8Array(e.outputLen);return Xa(e,r,t)}var XS=Uint8Array.of(0),cP=Uint8Array.of();function uP(e,t,r,i=32){un(e),Kt(i,"length");let n=e.outputLen;if(i>255*n)throw Error("Length must be <= 255*HashLen");let o=Math.ceil(i/n);if(r===void 0)r=cP;else Pe(r,void 0,"info");let s=new Uint8Array(o*n),a=Xa.create(e,t),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<o;u++)XS[0]=u+1,c.update(u===0?cP:l).update(r).update(XS).digestInto(l),s.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),Br(l,XS),s.slice(0,i)}var BV=BigInt(0),Ou=BigInt(1),jV=BigInt(2),UV=BigInt(7),qV=BigInt(256),ZV=BigInt(113),pP=[],mP=[],hP=[];for(let e=0,t=Ou,r=1,i=0;e<24;e++){[r,i]=[i,(2*r+3*i)%5],pP.push(2*(5*i+r)),mP.push((e+1)*(e+2)/2%64);let n=BV;for(let o=0;o<7;o++)if(t=(t<<Ou^(t>>UV)*ZV)%qV,t&jV)n^=Ou<<(Ou<<BigInt(o))-Ou;hP.push(n)}var gP=Xp(hP,!0),MV=gP[0],FV=gP[1],dP=(e,t,r)=>r>32?FO(e,t,r):ZO(e,t,r),fP=(e,t,r)=>r>32?HO(e,t,r):MO(e,t,r);function HV(e,t=24){let r=new Uint32Array(10);for(let i=24-t;i<24;i++){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,l=r[c],u=r[c+1],f=dP(l,u,1)^r[a],p=fP(l,u,1)^r[a+1];for(let m=0;m<50;m+=10)e[s+m]^=f,e[s+m+1]^=p}let n=e[2],o=e[3];for(let s=0;s<24;s++){let a=mP[s],c=dP(n,o,a),l=fP(n,o,a),u=pP[s];n=e[u],o=e[u+1],e[u]=c,e[u+1]=l}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]^=MV[i],e[1]^=FV[i]}Br(r)}class tm{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,i=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=i,this.rounds=n,Kt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Mp(this.state)}clone(){return this._cloneInto()}keccak(){OS(this.state32),HV(this.state32,this.rounds),OS(this.state32),this.posOut=0,this.pos=0}update(e){$i(this),Pe(e);let{blockLen:t,state:r}=this,i=e.length;for(let n=0;n<i;){let o=Math.min(t-this.pos,i-n);for(let s=0;s<o;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:i}=this;if(e[r]^=t,(t&128)!==0&&r===i-1)this.keccak();e[i-1]^=128,this.keccak()}writeInto(e){$i(this,!1),Pe(e),this.finish();let t=this.state,{blockLen:r}=this;for(let i=0,n=e.length;i<n;){if(this.posOut>=r)this.keccak();let o=Math.min(r-this.posOut,n-i);e.set(t.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Kt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Zp(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,Br(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:i,rounds:n,enableXOF:o}=this;return e||=new tm(t,r,i,o,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=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}var yP=(e,t,r,i={})=>Wa(()=>new tm(t,e,r),i);var Ps=yP(6,136,32,go(8));var bP=yP(6,72,64,go(10));var SP=(e,t,r,i={})=>Wa((n={})=>new tm(t,e,n.dkLen===void 0?r:n.dkLen,!0),i),xP=SP(31,168,16,go(11)),Yn=SP(31,136,32,go(12));function ex(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function vP(e){return ex(e),(e&e-1)===0&&e!==0}function tx(e,t){ex(e);let r=0;for(let i=0;i<t;i++,e>>>=1)r=r<<1|e&1;return r}function _P(e){return ex(e),31-Math.clz32(e)}function wP(e){let t=e.length;if(t<2||!vP(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=_P(t);for(let i=0;i<t;i++){let n=tx(i,r);if(i<n){let o=e[i];e[i]=e[n],e[n]=o}}return e}var rx=(e,t)=>{let{N:r,roots:i,dit:n,invertButterflies:o=!1,skipStages:s=0,brp:a=!0}=t,c=_P(r);if(!vP(r))throw Error("FFT: Polynomial size should be power of two");let l=n!==o;return(u)=>{if(u.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)wP(u);for(let f=0,p=1;f<c-s;f++){let m=n?f+1+s:c-f,y=1<<m,g=y>>1,b=r>>m;for(let _=0;_<r;_+=y)for(let T=0,A=p++;T<g;T++){let z=o?n?r-A:A:T*b,j=_+T,E=_+T+g,F=i[z],D=u[E],H=u[j];if(l){let X=e.mul(D,F);u[j]=e.add(H,X),u[E]=e.sub(H,X)}else if(o)u[j]=e.add(D,H),u[E]=e.mul(e.sub(D,H),F);else u[j]=e.add(H,D),u[E]=e.mul(e.sub(H,D),F)}}if(!n&&a)wP(u);return u}};/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var Xn=ho;function rm(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function kP(e){return Uint8Array.from(e)}function zs(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,i=t.reduce((n,o)=>n+r(o),0);return{bytesLen:i,encode:(n)=>{let o=new Uint8Array(i);for(let s=0,a=0;s<t.length;s++){let c=t[s],l=r(c),u=typeof c==="number"?n[s]:c.encode(n[s]);if(Pe(u,l,e),o.set(u,a),typeof c!=="number")u.fill(0);a+=l}return o},decode:(n)=>{Pe(n,i,e);let o=[];for(let s of t){let a=r(s),c=n.subarray(0,a);o.push(typeof s==="number"?c:s.decode(c)),n=n.subarray(a)}return o}}}function nm(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(i)=>{if(i.length!==t)throw Error(`vecCoder.encode: wrong length=${i.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let o=0,s=0;o<i.length;o++){let a=e.encode(i[o]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(i)=>{Pe(i,r);let n=[];for(let o=0;o<i.length;o+=e.bytesLen)n.push(e.decode(i.subarray(o,o+e.bytesLen)));return n}}}function Ut(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function nx(e){return(1<<e)-1}var lve=Uint8Array.of();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var EP=(e)=>{let{newPoly:t,N:r,Q:i,F:n,ROOT_OF_UNITY:o,brvBits:s,isKyber:a}=e,c=(T,A=i)=>{let z=T%A|0;return(z>=0?z|0:A+z|0)|0},l=(T,A=i)=>{let z=c(T,A)|0;return(z>A>>1?z-A|0:z)|0};function u(){let T=t(r);for(let A=0;A<r;A++){let z=tx(A,s),j=BigInt(o)**BigInt(z)%BigInt(i);T[A]=Number(j)|0}return T}let f=u(),p={add:(T,A)=>c((T|0)+(A|0))|0,sub:(T,A)=>c((T|0)-(A|0))|0,mul:(T,A)=>c((T|0)*(A|0))|0,inv:(T)=>{throw Error("not implemented")}},m={N:r,roots:f,invertButterflies:!0,skipStages:a?1:0,brp:!1},y=rx(p,{dit:!1,...m}),g=rx(p,{dit:!0,...m});return{mod:c,smod:l,nttZetas:f,NTT:{encode:(T)=>y(T),decode:(T)=>{g(T);for(let A=0;A<T.length;A++)T[A]=c(n*T[A]);return T}},bitsCoder:(T,A)=>{let z=nx(T),j=T*(r/8);return{bytesLen:j,encode:(E)=>{let F=new Uint8Array(j);for(let D=0,H=0,X=0,Z=0;D<E.length;D++){H|=(A.encode(E[D])&z)<<X,X+=T;for(;X>=8;X-=8,H>>=8)F[Z++]=H&nx(X)}return F},decode:(E)=>{let F=t(r);for(let D=0,H=0,X=0,Z=0;D<E.length;D++){H|=E[D]<<X,X+=8;for(;X>=T;X-=T,H>>=T)F[Z++]=A.decode(H&z)}return F}}}}},KV=(e)=>(t,r)=>{if(!r)r=e.blockLen;let i=new Uint8Array(t.length+2);i.set(t);let n=t.length,o=new Uint8Array(r),s=e.create({}),a=0,c=0;return{stats:()=>({calls:a,xofs:c}),get:(l,u)=>(i[n+0]=l,i[n+1]=u,s.destroy(),s=e.create({}).update(i),a++,()=>(c++,s.xofInto(o))),clean:()=>{s.destroy(),Ut(o,i)}}},IP=KV(xP);/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */var hr=256,Oi=3329,JV=3303,VV=17,{mod:Nu,nttZetas:WV,NTT:Ns,bitsCoder:GV}=EP({N:hr,Q:Oi,F:JV,ROOT_OF_UNITY:VV,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0}),ix={512:{N:hr,Q:Oi,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:hr,Q:Oi,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:hr,Q:Oi,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}},QV=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+Oi/2)/Oi,decode:(r)=>r*Oi+t>>>e}},Pu=(e)=>GV(e,QV(e));function Ds(e,t){for(let r=0;r<hr;r++)e[r]=Nu(e[r]+t[r])}function YV(e,t){for(let r=0;r<hr;r++)e[r]=Nu(e[r]-t[r])}function XV(e,t,r,i,n){let o=Nu(t*i*n+e*r),s=Nu(e*i+t*r);return{c0:o,c1:s}}function im(e,t){for(let r=0;r<hr/2;r++){let i=WV[64+(r>>1)];if(r&1)i=-i;let{c0:n,c1:o}=XV(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],i);e[2*r+0]=n,e[2*r+1]=o}return e}function TP(e){let t=new Uint16Array(hr);for(let r=0;r<hr;){let i=e();if(i.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<hr&&n+3<=i.length;n+=3){let o=(i[n+0]>>0|i[n+1]<<8)&4095,s=(i[n+1]>>4|i[n+2]<<4)&4095;if(o<Oi)t[r++]=o;if(r<hr&&s<Oi)t[r++]=s}}return t}function zu(e,t,r,i){let n=e(i*hr/4,t,r),o=new Uint16Array(hr),s=Mp(n),a=0;for(let c=0,l=0,u=0,f=0;c<s.length;c++){let p=s[c];for(let m=0;m<32;m++)if(u+=p&1,p>>=1,a+=1,a===i)f=u,u=0;else if(a===2*i)o[l++]=Nu(f-u),u=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return o}var e7=(e)=>{let{K:t,PRF:r,XOF:i,HASH512:n,ETA1:o,ETA2:s,du:a,dv:c}=e,l=Pu(1),u=Pu(c),f=Pu(a),p=zs("publicKey",nm(Pu(12),t),32),m=nm(Pu(12),t),y=zs("ciphertext",nm(f,t),u),g=zs("seed",32,32);return{secretCoder:m,lengths:{secretKey:m.bytesLen,publicKey:p.bytesLen,cipherText:y.bytesLen},keygen:(b)=>{Pe(b,32,"seed");let _=new Uint8Array(33);_.set(b),_[32]=t;let T=n(_),[A,z]=g.decode(T),j=[],E=[];for(let H=0;H<t;H++)j.push(Ns.encode(zu(r,z,H,o)));let F=i(A);for(let H=0;H<t;H++){let X=Ns.encode(zu(r,z,t+H,o));for(let Z=0;Z<t;Z++){let P=TP(F.get(Z,H));Ds(X,im(P,j[Z]))}E.push(X)}F.clean();let D={publicKey:p.encode([E,A]),secretKey:m.encode(j)};return Ut(A,z,j,E,_,T),D},encrypt:(b,_,T)=>{let[A,z]=p.decode(b),j=[];for(let Z=0;Z<t;Z++)j.push(Ns.encode(zu(r,T,Z,o)));let E=i(z),F=new Uint16Array(hr),D=[];for(let Z=0;Z<t;Z++){let P=zu(r,T,t+Z,s),N=new Uint16Array(hr);for(let I=0;I<t;I++){let O=TP(E.get(Z,I));Ds(N,im(O,j[I]))}Ds(P,Ns.decode(N)),D.push(P),Ds(F,im(A[Z],j[Z])),Ut(N)}E.clean();let H=zu(r,T,2*t,s);Ds(H,Ns.decode(F));let X=l.decode(_);return Ds(X,H),Ut(A,j,F,H),y.encode([D,X])},decrypt:(b,_)=>{let[T,A]=y.decode(b),z=m.decode(_),j=new Uint16Array(hr);for(let E=0;E<t;E++)Ds(j,im(z[E],Ns.encode(T[E])));return YV(A,Ns.decode(j)),Ut(j,z,T),l.encode(A)}}};function ox(e){let t=e7(e),{HASH256:r,HASH512:i,KDF:n}=e,{secretCoder:o,lengths:s}=t,a=zs("secretKey",s.secretKey,s.publicKey,32,32),c=32,l=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(u=Xn(64))=>{Pe(u,64,"seed");let{publicKey:f,secretKey:p}=t.keygen(u.subarray(0,32)),m=r(f),y=a.encode([p,f,m,u.subarray(32)]);return Ut(p,m),{publicKey:f,secretKey:y}},getPublicKey:(u)=>{let[f,p,m,y]=a.decode(u);return Uint8Array.from(p)},encapsulate:(u,f=Xn(32))=>{Pe(u,s.publicKey,"publicKey"),Pe(f,32,"message");let p=u.subarray(0,384*e.K),m=o.encode(o.decode(kP(p)));if(!rm(m,p))throw Ut(m),Error("ML-KEM.encapsulate: wrong publicKey modulus");Ut(m);let y=i.create().update(f).update(r(u)).digest(),g=t.encrypt(u,f,y.subarray(32,64));return Ut(y.subarray(32)),{cipherText:g,sharedSecret:y.subarray(0,32)}},decapsulate:(u,f)=>{Pe(f,a.bytesLen,"secretKey"),Pe(u,s.cipherText,"cipherText");let p=a.bytesLen-96,m=p+32,y=r(f.subarray(p/2,m));if(!rm(y,f.subarray(m,m+32)))throw Error("invalid secretKey: hash check failed");let[g,b,_,T]=a.decode(f),A=t.decrypt(u,g),z=i.create().update(A).update(_).digest(),j=z.subarray(0,32),E=t.encrypt(b,A,z.subarray(32,64)),F=rm(u,E),D=n.create({dkLen:32}).update(T).update(u).digest();return Ut(A,E,!F?j:D),F?j:D}}}function t7(e,t,r){return Yn.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var sx={HASH256:Ps,HASH512:bP,KDF:Yn,XOF:IP,PRF:t7},xve=ox({...sx,...ix[512]}),Du=ox({...sx,...ix[768]}),AP=ox({...sx,...ix[1024]});/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */function r7(e,t=!1){let{lengths:r,keygen:i}=e;if(t){let o=e.Point.Fn;if(!o)throw Error("No Point.Fn");i=(s=Xn(r.seed))=>{Pe(s,r.seed,"seed");let a=o.isLE?bo(s):yo(s),c=o.toBytes(o.create(a));return{secretKey:c,publicKey:e.getPublicKey(c)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:i,getPublicKey:(n)=>e.getPublicKey(n)}}function ax(e,t=!1){let r=r7(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(i,n=Xn(e.lengths.seed)){let o=this.keygen(n).secretKey,s=this.decapsulate(i,o),a=e.getPublicKey(o);return Ut(o),{sharedSecret:s,cipherText:a}},decapsulate(i,n){let o=e.getSharedSecret(n,i);return e.lengths.publicKeyHasPrefix?o.subarray(1):o}}}function Lu(e,t){return zs(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function cx(e){return(t,r)=>e(t,{dkLen:r})}function n7(e,t,...r){let i=Lu(r,"seed"),n=Lu(r,"publicKey");if(e===void 0)e=i.bytesLen;Kt(e);function o(s){Pe(s,e);let a=i.decode(t(s,i.bytesLen)),c=r.map((f,p)=>f.keygen(a[p])),l=c.map((f)=>f.secretKey),u=c.map((f)=>f.publicKey);return{secretKey:l,publicKey:u}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Xn(e)){let{publicKey:a,secretKey:c}=o(s),l=n.encode(a);return Ut(a),Ut(c),{secretKey:s,publicKey:l}},expandDecapsulationKey:o,realSeedLen:e}}function om(e,t,r,i,...n){let o=n7(e,r,...n),s=Lu(n,"cipherText"),a=Lu(n,"publicKey"),c=Lu(n,"msg");if(t===void 0)t=c.bytesLen;return Kt(t),{lengths:{...o.info.lengths,msg:t,msgRand:c.bytesLen,cipherText:s.bytesLen},getPublicKey:o.getPublicKey,keygen:o.keygen,encapsulate(l,u=Xn(c.bytesLen)){let f=a.decode(l),p=c.decode(u),m=n.map((_,T)=>_.encapsulate(f[T],p[T])),y=m.map((_)=>_.sharedSecret),g=m.map((_)=>_.cipherText),b={sharedSecret:i(f,g,y),cipherText:s.encode(g)};return Ut(y,g),b},decapsulate(l,u){let f=s.decode(l),{publicKey:p,secretKey:m}=o.expandDecapsulationKey(u),y=n.map((g,b)=>g.decapsulate(f[b],m[b]));return i(p,f,y)}}}function $P(e,t,r,i,n){return un(i),un(n),om(32,32,cx(i),(o,s,a)=>n(Nt(a[0],a[1],s[1],o[1],So(e))),t,r)}var Rve=$P("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",Du,ax(YS,!0),Yn,Ps),Ove=$P("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",AP,ax(aP,!0),Yn,Ps);function i7(e,t,r,i,n){return un(i),un(n),om(32,32,cx(i),(o,s,a)=>{let c=Nt(a[0],a[1],s[0],o[0],s[1],o[1],So(e)),l=32,u=Nt(So("hybrid_prk"),c),f=lP(n,u),p=Nt(Ga(32,2),So("shared_secret"),So("")),m=uP(n,f,p,32);return Ut(f,p,u,c),m},t,r)}var CP=ax(sP),Pve=i7("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",Du,CP,Yn,em),o7=(()=>om(32,32,cx(Yn),(e,t,r)=>Ps(Nt(r[0],r[1],t[1],e[1],So("\\.//^\\"))),Du,CP))();function s7(e,t,r,i){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function o(s){let a;for(let u=0,f=t;;u=f,f+=t){if(f>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(u,f),!0),n.isValidNot0(a))break}let c=n.toBytes(n.create(a)),l=e.getPublicKey(c,!1);return{secretKey:c,publicKey:l}}return{lengths:{secretKey:t,publicKey:r,seed:i,msg:i,cipherText:r},keygen(s=Xn(i)){return Pe(s,i,"seed"),o(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Xn(i)){Pe(a,i,"rand");let{secretKey:c}=o(a),l=this.decapsulate(s,c),u=e.getPublicKey(c,!1);return Ut(c),{sharedSecret:l,cipherText:u}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function a7(e,t,r,i){let{secretKey:n,publicKeyUncompressed:o}=r.lengths;if(!n||!o)throw Error("wrong curve");let s=s7(r,n,o,i),a=64,c=a+i;return om(32,32,(l)=>{Pe(l,32);let u=Yn(l,{dkLen:c}),f=u.subarray(0,a),p=u.subarray(a,c);return Nt(f,p)},(l,u,f)=>Ps(Nt(f[0],f[1],u[1],l[1],So(e))),t,s)}var c7=(()=>a7("MLKEM768-P256",Du,YS,128))();var sm=o7,RP=c7;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ct=(e,t,r)=>Yt(e,t,r),ux=At,tc=Cp,rr=(...e)=>pS(...e),rc=(e)=>mu(e),nc=uS,ic=(e)=>Ei(e),cm=BigInt(0),lx=BigInt(1);function Pi(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function lm(e){if(typeof e==="bigint"){if(!am(e))throw RangeError("positive bigint expected, got "+e)}else ux(e);return e}function ei(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 Bu(e){let t=lm(e).toString(16);return t.length&1?"0"+t:t}function OP(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?cm:BigInt("0x"+e)}function Ls(e){return OP(Cp(e))}function An(e){return OP(Cp(ko(Yt(e)).reverse()))}function um(e,t){if(At(t),t===0)throw RangeError("zero length");e=lm(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return mu(r.padStart(t*2,"0"))}function ju(e,t){return um(e,t).reverse()}function PP(e,t){if(e=ct(e),t=ct(t),e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return r===0}function ko(e){return Uint8Array.from(ct(e))}function dm(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let i=t.charCodeAt(0);if(t.length!==1||i>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${i} at position ${r}`);return i})}var am=(e)=>typeof e==="bigint"&&cm<=e;function l7(e,t,r){return am(e)&&am(t)&&am(r)&&t<=e&&e<r}function zi(e,t,r,i){if(!l7(t,r,i))throw RangeError("expected valid "+e+": "+r+" <= n < "+i+", got "+t)}function oc(e){if(e<cm)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>cm;e>>=lx,t+=1);return t}var Uu=(e)=>(lx<<BigInt(e))-lx;function zP(e,t,r){if(At(e,"hashLen"),At(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let i=(b)=>new Uint8Array(b),n=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,c=i(e),l=i(e),u=0,f=()=>{c.fill(1),l.fill(0),u=0},p=(...b)=>r(l,rr(c,...b)),m=(b=n)=>{if(l=p(o,b),c=p(),b.length===0)return;l=p(s,b),c=p()},y=()=>{if(u++>=a)throw Error("drbg: tried max amount of iterations");let b=0,_=[];while(b<t){c=p();let T=c.slice();_.push(T),b+=c.length}return rr(..._)};return(b,_)=>{f(),m(b);let T=void 0;while((T=_(y()))===void 0)m();return f(),T}}function fn(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function i(o,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,o))throw TypeError(`param "${o}" is invalid: expected own property`);let c=e[o];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw TypeError(`param "${o}" is invalid: expected ${s}, got ${l}`)}let n=(o,s)=>Object.entries(o).forEach(([a,c])=>i(a,c,s));n(t,!1),n(r,!0)}var dx=()=>{throw Error("not implemented")};/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var nr=BigInt(0),_t=BigInt(1),Bs=BigInt(2),BP=BigInt(3),jP=BigInt(4),UP=BigInt(5),u7=BigInt(7),qP=BigInt(8),d7=BigInt(9),ZP=BigInt(16);function gt(e,t){if(t<=nr)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=nr?r:t+r}function pn(e,t,r){if(t<nr)throw Error("pow2: expected non-negative exponent, got "+t);let i=e;while(t-- >nr)i*=i,i%=r;return i}function NP(e,t){if(e===nr)throw Error("invert: expected non-zero number");if(t<=nr)throw Error("invert: expected positive modulus, got "+t);let r=gt(e,t),i=t,n=nr,o=_t,s=_t,a=nr;while(r!==nr){let l=i/r,u=i-r*l,f=n-s*l,p=o-a*l;i=r,r=u,n=s,o=a,s=f,a=p}if(i!==_t)throw Error("invert: does not exist");return gt(n,t)}function fx(e,t,r){let i=e;if(!i.eql(i.sqr(t),r))throw Error("Cannot find square root")}function MP(e,t){let r=e,i=(r.ORDER+_t)/jP,n=r.pow(t,i);return fx(r,n,t),n}function f7(e,t){let r=e,i=(r.ORDER-UP)/qP,n=r.mul(t,Bs),o=r.pow(n,i),s=r.mul(t,o),a=r.mul(r.mul(s,Bs),o),c=r.mul(s,r.sub(a,r.ONE));return fx(r,c,t),c}function p7(e){let t=fm(e),r=FP(e),i=r(t,t.neg(t.ONE)),n=r(t,i),o=r(t,t.neg(i)),s=(e+u7)/ZP;return(a,c)=>{let l=a,u=l.pow(c,s),f=l.mul(u,i),p=l.mul(u,n),m=l.mul(u,o),y=l.eql(l.sqr(f),c),g=l.eql(l.sqr(p),c);u=l.cmov(u,f,y),f=l.cmov(m,p,g);let b=l.eql(l.sqr(f),c),_=l.cmov(u,f,b);return fx(l,_,c),_}}function FP(e){if(e<BP)throw Error("sqrt is not defined for small field");let t=e-_t,r=0;while(t%Bs===nr)t/=Bs,r++;let i=Bs,n=fm(e);while(DP(n,i)===1)if(i++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return MP;let o=n.pow(i,t),s=(t+_t)/Bs;return function(c,l){let u=c;if(u.is0(l))return l;if(DP(u,l)!==1)throw Error("Cannot find square root");let f=r,p=u.mul(u.ONE,o),m=u.pow(l,t),y=u.pow(l,s);while(!u.eql(m,u.ONE)){if(u.is0(m))return u.ZERO;let g=1,b=u.sqr(m);while(!u.eql(b,u.ONE))if(g++,b=u.sqr(b),g===f)throw Error("Cannot find square root");let _=_t<<BigInt(f-g-1),T=u.pow(p,_);f=g,p=u.sqr(T),m=u.mul(m,p),y=u.mul(y,T)}return y}}function m7(e){if(e%jP===BP)return MP;if(e%qP===UP)return f7;if(e%ZP===d7)return p7(e);return FP(e)}var Ni=(e,t)=>(gt(e,t)&_t)===_t,h7=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function px(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=h7.reduce((i,n)=>(i[n]="function",i),t);if(fn(e,r),ei(e.BYTES,"BYTES"),ei(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=_t)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function g7(e,t,r){let i=e;if(r<nr)throw Error("invalid exponent, negatives unsupported");if(r===nr)return i.ONE;if(r===_t)return t;let n=i.ONE,o=t;while(r>nr){if(r&_t)n=i.mul(n,o);o=i.sqr(o),r>>=_t}return n}function qu(e,t,r=!1){let i=e,n=Array(t.length).fill(r?i.ZERO:void 0),o=t.reduce((a,c,l)=>{if(i.is0(c))return a;return n[l]=a,i.mul(a,c)},i.ONE),s=i.inv(o);return t.reduceRight((a,c,l)=>{if(i.is0(c))return a;return n[l]=i.mul(a,n[l]),i.mul(a,c)},s),n}function DP(e,t){let r=e,i=(r.ORDER-_t)/Bs,n=r.pow(t,i),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!a)throw Error("invalid Legendre symbol result");return o?1:s?0:-1}function y7(e,t){if(t!==void 0)ux(t);if(e<=nr)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=oc(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let i=t!==void 0?t:r,n=Math.ceil(i/8);return{nBitLength:i,nByteLength:n}}var LP=new WeakMap;class mx{ORDER;BITS;BYTES;isLE;ZERO=nr;ONE=_t;_lengths;_mod;constructor(e,t={}){if(e<=_t)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:i,nByteLength:n}=y7(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=n,Object.freeze(this)}create(e){return gt(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return nr<=e&&e<this.ORDER}is0(e){return e===nr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&_t)===_t}neg(e){return gt(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return gt(e*e,this.ORDER)}add(e,t){return gt(e+t,this.ORDER)}sub(e,t){return gt(e-t,this.ORDER)}mul(e,t){return gt(e*t,this.ORDER)}pow(e,t){return g7(this,e,t)}div(e,t){return gt(e*NP(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 NP(e,this.ORDER)}sqrt(e){let t=LP.get(this);if(!t)LP.set(this,t=m7(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?ju(e,this.BYTES):um(e,this.BYTES)}fromBytes(e,t=!1){ct(e);let{_lengths:r,BYTES:i,isLE:n,ORDER:o,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>i)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(i);c.set(e,n?0:c.length-e.length),e=c}if(e.length!==i)throw Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=n?An(e):Ls(e);if(s)a=gt(a,o);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return qu(this,e)}cmov(e,t,r){return Pi(r,"condition"),r?t:e}}Object.freeze(mx.prototype);function fm(e,t={}){return new mx(e,t)}function HP(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=_t)throw Error("field order must be greater than 1");let t=oc(e-_t);return Math.ceil(t/8)}function hx(e){let t=HP(e);return t+Math.ceil(t/2)}function KP(e,t,r=!1){ct(e);let i=e.length,n=HP(t),o=Math.max(hx(t),16);if(i<o||i>1024)throw Error("expected "+o+"-1024 bytes of input, got "+i);let s=r?An(e):Ls(e),a=gt(s,t-_t)+_t;return r?ju(a,n):um(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var sc=BigInt(0),js=BigInt(1);function Zu(e,t){let r=t.negate();return e?r:t}function Us(e,t){let r=qu(e.Fp,t.map((i)=>i.Z));return t.map((i,n)=>e.fromAffine(i.toAffine(r[n])))}function GP(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function gx(e,t){GP(e,t);let r=Math.ceil(t/e)+1,i=2**(e-1),n=2**e,o=Uu(e),s=BigInt(e);return{windows:r,windowSize:i,mask:o,maxNumber:n,shiftBy:s}}function JP(e,t,r){let{windowSize:i,mask:n,maxNumber:o,shiftBy:s}=r,a=Number(e&n),c=e>>s;if(a>i)a-=o,c+=js;let l=t*i,u=l+Math.abs(a)-1,f=a===0,p=a<0,m=t%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:p,isNegF:m,offsetF:l}}var yx=new WeakMap,QP=new WeakMap;function bx(e){return QP.get(e)||1}function VP(e){if(e!==sc)throw Error("invalid wNAF")}class Mu{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 i=e;while(t>sc){if(t&js)r=r.add(i);i=i.double(),t>>=js}return r}precomputeWindow(e,t){let{windows:r,windowSize:i}=gx(t,this.bits),n=[],o=e,s=o;for(let a=0;a<r;a++){s=o,n.push(s);for(let c=1;c<i;c++)s=s.add(o),n.push(s);o=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let i=this.ZERO,n=this.BASE,o=gx(e,this.bits);for(let s=0;s<o.windows;s++){let{nextN:a,offset:c,isZero:l,isNeg:u,isNegF:f,offsetF:p}=JP(r,s,o);if(r=a,l)n=n.add(Zu(f,t[p]));else i=i.add(Zu(u,t[c]))}return VP(r),{p:i,f:n}}wNAFUnsafe(e,t,r,i=this.ZERO){let n=gx(e,this.bits);for(let o=0;o<n.windows;o++){if(r===sc)break;let{nextN:s,offset:a,isZero:c,isNeg:l}=JP(r,o,n);if(r=s,c)continue;else{let u=t[a];i=i.add(l?u.negate():u)}}return VP(r),i}getPrecomputes(e,t,r){let i=yx.get(t);if(!i){if(i=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")i=r(i);yx.set(t,i)}}return i}cached(e,t,r){let i=bx(e);return this.wNAF(i,this.getPrecomputes(i,e,r),t)}unsafe(e,t,r,i){let n=bx(e);if(n===1)return this._unsafeLadder(e,t,i);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,i)}createCache(e,t){GP(t,this.bits),QP.set(e,t),yx.delete(e)}hasCache(e){return bx(e)!==1}}function YP(e,t,r,i){let n=t,o=e.ZERO,s=e.ZERO;while(r>sc||i>sc){if(r&js)o=o.add(n);if(i&js)s=s.add(n);n=n.double(),r>>=js,i>>=js}return{p1:o,p2:s}}function WP(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return px(t),t}else return fm(e,{isLE:r})}function pm(e,t,r={},i){if(i===void 0)i=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l==="bigint"&&l>sc))throw Error(`CURVE.${c} must be positive bigint`)}let n=WP(t.p,r.Fp,i),o=WP(t.n,r.Fn,i),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:o}}function Fu(e,t){return function(i){let n=e(i);return{secretKey:n,publicKey:t(n)}}}function Hu(e,t){if(ei(e),ei(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 i=t-1;i>=0;i--)r[i]=e&255,e>>>=8;return new Uint8Array(r)}function b7(e,t){let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}function S7(e){if(!nc(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?dm(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function Sx(e,t,r,i){if(ct(e),ei(r),t=S7(t),t.length>255)t=i(rr(dm("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:o}=i,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=rr(t,Hu(t.length,1)),c=new Uint8Array(o),l=Hu(r,2),u=Array(s),f=i(rr(c,e,l,Hu(0,1),a));u[0]=i(rr(f,Hu(1,1),a));for(let m=1;m<s;m++){let y=[b7(f,u[m-1]),Hu(m+1,1),a];u[m]=i(rr(...y))}return rr(...u).slice(0,r)}var XP="HashToScalar-";/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ez=(e,t)=>(e+(e>=0?t:-t)/rz)/t;function x7(e,t,r){zi("scalar",e,ti,r);let[[i,n],[o,s]]=t,a=ez(s*e,r),c=ez(-n*e,r),l=e-a*i-c*o,u=-a*n-c*s,f=l<ti,p=u<ti;if(f)l=-l;if(p)u=-u;let m=Uu(Math.ceil(oc(r)/2))+Eo;if(l<ti||l>=m||u<ti||u>=m)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:f,k1:l,k2neg:p,k2:u}}function wx(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function xx(e,t){fn(e);let r={};for(let i of Object.keys(t))r[i]=e[i]===void 0?t[i]:e[i];if(Pi(r.lowS,"lowS"),Pi(r.prehash,"prehash"),r.format!==void 0)wx(r.format);return r}class tz extends Error{constructor(e=""){super(e)}}var $n={Err:tz,_tlv:{encode:(e,t)=>{let{Err:r}=$n;if(ei(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 i=t.length/2,n=Bu(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let o=i>127?Bu(n.length/2|128):"";return Bu(e)+o+n+t},decode(e,t){let{Err:r}=$n;t=ct(t,void 0,"DER data");let i=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[i++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[i++],o=!!(n&128),s=0;if(!o)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 l=t.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(i+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(i,i+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(i+s)}}},_int:{encode(e){let{Err:t}=$n;if(lm(e),e<ti)throw new t("integer: negative integers are not allowed");let r=Bu(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}=$n;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 Ls(e)}},toSig(e){let{Err:t,_int:r,_tlv:i}=$n,n=ct(e,void 0,"signature"),{v:o,l:s}=i.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=i.decode(2,o),{v:l,l:u}=i.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){let{_tlv:t,_int:r}=$n,i=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),o=i+n;return t.encode(48,o)}};Object.freeze($n._tlv);Object.freeze($n._int);Object.freeze($n);var ti=BigInt(0),Eo=BigInt(1),rz=BigInt(2),mm=BigInt(3),w7=BigInt(4);function nz(e,t={}){let r=pm("weierstrass",e,t),i=r.Fp,n=r.Fn,o=r.CURVE,{h:s,n:a}=o;fn(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c,allowInfinityPoint:l}=t;if(c){if(!i.is0(o.a)||typeof c.beta!=="bigint"||!Array.isArray(c.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=oz(i,n);function f(){if(!i.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function p(Z,P,N){if(l&&P.is0())return Uint8Array.of(0);let{x:I,y:O}=P.toAffine(),R=i.toBytes(I);if(Pi(N,"isCompressed"),N){f();let M=!i.isOdd(O);return rr(iz(M),R)}else return rr(Uint8Array.of(4),R,i.toBytes(O))}function m(Z){ct(Z,void 0,"Point");let{publicKey:P,publicKeyUncompressed:N}=u,I=Z.length,O=Z[0],R=Z.subarray(1);if(l&&I===1&&O===0)return{x:i.ZERO,y:i.ZERO};if(I===P&&(O===2||O===3)){let M=i.fromBytes(R);if(!i.isValid(M))throw Error("bad point: is not on curve, wrong x");let L=b(M),V;try{V=i.sqrt(L)}catch(ue){let C=ue instanceof Error?": "+ue.message:"";throw Error("bad point: is not on curve, sqrt error"+C)}f();let k=i.isOdd(V);if((O&1)===1!==k)V=i.neg(V);return{x:M,y:V}}else if(I===N&&O===4){let M=i.BYTES,L=i.fromBytes(R.subarray(0,M)),V=i.fromBytes(R.subarray(M,M*2));if(!_(L,V))throw Error("bad point: is not on curve");return{x:L,y:V}}else throw Error(`bad point: got length ${I}, expected compressed=${P} or uncompressed=${N}`)}let y=t.toBytes===void 0?p:t.toBytes,g=t.fromBytes===void 0?m:t.fromBytes;function b(Z){let P=i.sqr(Z),N=i.mul(P,Z);return i.add(i.add(N,i.mul(Z,o.a)),o.b)}function _(Z,P){let N=i.sqr(P),I=b(Z);return i.eql(N,I)}if(!_(o.Gx,o.Gy))throw Error("bad curve params: generator point");let T=i.mul(i.pow(o.a,mm),w7),A=i.mul(i.sqr(o.b),BigInt(27));if(i.is0(i.add(T,A)))throw Error("bad curve params: a or b");function z(Z,P,N=!1){if(!i.isValid(P)||N&&i.is0(P))throw Error(`bad point coordinate ${Z}`);return P}function j(Z){if(!(Z instanceof D))throw Error("Weierstrass Point expected")}function E(Z){if(!c||!c.basises)throw Error("no endo");return x7(Z,c.basises,n.ORDER)}function F(Z,P,N,I,O){return N=new D(i.mul(N.X,Z),N.Y,N.Z),P=Zu(I,P),N=Zu(O,N),P.add(N)}class D{static BASE=new D(o.Gx,o.Gy,i.ONE);static ZERO=new D(i.ZERO,i.ONE,i.ZERO);static Fp=i;static Fn=n;X;Y;Z;constructor(Z,P,N){this.X=z("x",Z),this.Y=z("y",P,!0),this.Z=z("z",N),Object.freeze(this)}static CURVE(){return o}static fromAffine(Z){let{x:P,y:N}=Z||{};if(!Z||!i.isValid(P)||!i.isValid(N))throw Error("invalid affine point");if(Z instanceof D)throw Error("projective point not allowed");if(i.is0(P)&&i.is0(N))return D.ZERO;return new D(P,N,i.ONE)}static fromBytes(Z){let P=D.fromAffine(g(ct(Z,void 0,"point")));return P.assertValidity(),P}static fromHex(Z){return D.fromBytes(rc(Z))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(Z=8,P=!0){if(X.createCache(this,Z),!P)this.multiply(mm);return this}assertValidity(){let Z=this;if(Z.is0()){if(t.allowInfinityPoint&&i.is0(Z.X)&&i.eql(Z.Y,i.ONE)&&i.is0(Z.Z))return;throw Error("bad point: ZERO")}let{x:P,y:N}=Z.toAffine();if(!i.isValid(P)||!i.isValid(N))throw Error("bad point: x or y not field elements");if(!_(P,N))throw Error("bad point: equation left != right");if(!Z.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:Z}=this.toAffine();if(!i.isOdd)throw Error("Field doesn't support isOdd");return!i.isOdd(Z)}equals(Z){j(Z);let{X:P,Y:N,Z:I}=this,{X:O,Y:R,Z:M}=Z,L=i.eql(i.mul(P,M),i.mul(O,I)),V=i.eql(i.mul(N,M),i.mul(R,I));return L&&V}negate(){return new D(this.X,i.neg(this.Y),this.Z)}double(){let{a:Z,b:P}=o,N=i.mul(P,mm),{X:I,Y:O,Z:R}=this,M=i.ZERO,L=i.ZERO,V=i.ZERO,k=i.mul(I,I),te=i.mul(O,O),ue=i.mul(R,R),C=i.mul(I,O);return C=i.add(C,C),V=i.mul(I,R),V=i.add(V,V),M=i.mul(Z,V),L=i.mul(N,ue),L=i.add(M,L),M=i.sub(te,L),L=i.add(te,L),L=i.mul(M,L),M=i.mul(C,M),V=i.mul(N,V),ue=i.mul(Z,ue),C=i.sub(k,ue),C=i.mul(Z,C),C=i.add(C,V),V=i.add(k,k),k=i.add(V,k),k=i.add(k,ue),k=i.mul(k,C),L=i.add(L,k),ue=i.mul(O,R),ue=i.add(ue,ue),k=i.mul(ue,C),M=i.sub(M,k),V=i.mul(ue,te),V=i.add(V,V),V=i.add(V,V),new D(M,L,V)}add(Z){j(Z);let{X:P,Y:N,Z:I}=this,{X:O,Y:R,Z:M}=Z,L=i.ZERO,V=i.ZERO,k=i.ZERO,te=o.a,ue=i.mul(o.b,mm),C=i.mul(P,O),be=i.mul(N,R),Ee=i.mul(I,M),Ce=i.add(P,N),Re=i.add(O,R);Ce=i.mul(Ce,Re),Re=i.add(C,be),Ce=i.sub(Ce,Re),Re=i.add(P,I);let _e=i.add(O,M);return Re=i.mul(Re,_e),_e=i.add(C,Ee),Re=i.sub(Re,_e),_e=i.add(N,I),L=i.add(R,M),_e=i.mul(_e,L),L=i.add(be,Ee),_e=i.sub(_e,L),k=i.mul(te,Re),L=i.mul(ue,Ee),k=i.add(L,k),L=i.sub(be,k),k=i.add(be,k),V=i.mul(L,k),be=i.add(C,C),be=i.add(be,C),Ee=i.mul(te,Ee),Re=i.mul(ue,Re),be=i.add(be,Ee),Ee=i.sub(C,Ee),Ee=i.mul(te,Ee),Re=i.add(Re,Ee),C=i.mul(be,Re),V=i.add(V,C),C=i.mul(_e,Re),L=i.mul(Ce,L),L=i.sub(L,C),C=i.mul(Ce,be),k=i.mul(_e,k),k=i.add(k,C),new D(L,V,k)}subtract(Z){return j(Z),this.add(Z.negate())}is0(){return this.equals(D.ZERO)}multiply(Z){let{endo:P}=t;if(!n.isValidNot0(Z))throw RangeError("invalid scalar: out of range");let N,I,O=(R)=>X.cached(this,R,(M)=>Us(D,M));if(P){let{k1neg:R,k1:M,k2neg:L,k2:V}=E(Z),{p:k,f:te}=O(M),{p:ue,f:C}=O(V);I=te.add(C),N=F(P.beta,k,ue,R,L)}else{let{p:R,f:M}=O(Z);N=R,I=M}return Us(D,[N,I])[0]}multiplyUnsafe(Z){let{endo:P}=t,N=this,I=Z;if(!n.isValid(I))throw RangeError("invalid scalar: out of range");if(I===ti||N.is0())return D.ZERO;if(I===Eo)return N;if(X.hasCache(this))return this.multiply(I);if(P){let{k1neg:O,k1:R,k2neg:M,k2:L}=E(I),{p1:V,p2:k}=YP(D,N,R,L);return F(P.beta,V,k,O,M)}else return X.unsafe(N,I)}toAffine(Z){let P=this,N=Z,{X:I,Y:O,Z:R}=P;if(i.eql(R,i.ONE))return{x:I,y:O};let M=P.is0();if(N==null)N=M?i.ONE:i.inv(R);let L=i.mul(I,N),V=i.mul(O,N),k=i.mul(R,N);if(M)return{x:i.ZERO,y:i.ZERO};if(!i.eql(k,i.ONE))throw Error("invZ was invalid");return{x:L,y:V}}isTorsionFree(){let{isTorsionFree:Z}=t;if(s===Eo)return!0;if(Z)return Z(D,this);return X.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:Z}=t;if(s===Eo)return this;if(Z)return Z(D,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===Eo)return this.is0();return this.clearCofactor().is0()}toBytes(Z=!0){return Pi(Z,"isCompressed"),this.assertValidity(),y(D,this,Z)}toHex(Z=!0){return tc(this.toBytes(Z))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let H=n.BITS,X=new Mu(D,t.endo?Math.ceil(H/2):H);if(H>=8)D.BASE.precompute(8);return Object.freeze(D.prototype),Object.freeze(D),D}function iz(e){return Uint8Array.of(e?2:3)}function oz(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function v7(e,t={}){let{Fn:r}=e,i=t.randomBytes===void 0?ic:t.randomBytes,n=Object.assign(oz(e.Fp,r),{seed:Math.max(hx(r.ORDER),16)});function o(m){try{let y=r.fromBytes(m);return r.isValidNot0(y)}catch(y){return!1}}function s(m,y){let{publicKey:g,publicKeyUncompressed:b}=n;try{let _=m.length;if(y===!0&&_!==g)return!1;if(y===!1&&_!==b)return!1;return!!e.fromBytes(m)}catch(_){return!1}}function a(m){return m=m===void 0?i(n.seed):m,KP(ct(m,n.seed,"seed"),r.ORDER)}function c(m,y=!0){return e.BASE.multiply(r.fromBytes(m)).toBytes(y)}function l(m){let{secretKey:y,publicKey:g,publicKeyUncompressed:b}=n,_=r._lengths;if(!nc(m))return;let T=ct(m,void 0,"key").length,A=T===g||T===b,z=T===y||!!_?.includes(T);if(A&&z)return;return A}function u(m,y,g=!0){if(l(m)===!0)throw Error("first arg must be private key");if(l(y)===!1)throw Error("second arg must be public key");let b=r.fromBytes(m);return e.fromBytes(y).multiply(b).toBytes(g)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a},p=Fu(a,c);return Object.freeze(f),Object.freeze(n),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:p,Point:e,utils:f,lengths:n})}function sz(e,t,r={}){let i=t;ki(i),fn(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?ic:r.randomBytes,o=r.hmac===void 0?(O,R)=>Vn(i,O,R):r.hmac,{Fp:s,Fn:a}=e,{ORDER:c,BITS:l}=a,{keygen:u,getPublicKey:f,getSharedSecret:p,utils:m,lengths:y}=v7(e,r),g={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},b=c*rz+Eo<s.ORDER;function _(O){let R=c>>Eo;return O>R}function T(O,R){if(!a.isValidNot0(R))throw Error(`invalid signature ${O}: out of range 1..Point.Fn.ORDER`);return R}function A(){if(b)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function z(O,R){wx(R);let M=y.signature,L=R==="compact"?M:R==="recovered"?M+1:void 0;return ct(O,L)}class j{r;s;recovery;constructor(O,R,M){if(this.r=T("r",O),this.s=T("s",R),M!=null){if(A(),![0,1,2,3].includes(M))throw Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(O,R=g.format){z(O,R);let M;if(R==="der"){let{r:te,s:ue}=$n.toSig(ct(O));return new j(te,ue)}if(R==="recovered")M=O[0],R="compact",O=O.subarray(1);let L=y.signature/2,V=O.subarray(0,L),k=O.subarray(L,L*2);return new j(a.fromBytes(V),a.fromBytes(k),M)}static fromHex(O,R){return this.fromBytes(rc(O),R)}assertRecovery(){let{recovery:O}=this;if(O==null)throw Error("invalid recovery id: must be present");return O}addRecoveryBit(O){return new j(this.r,this.s,O)}recoverPublicKey(O){let{r:R,s:M}=this,L=this.assertRecovery(),V=L===2||L===3?R+c:R;if(!s.isValid(V))throw Error("invalid recovery id: sig.r+curve.n != R.x");let k=s.toBytes(V),te=e.fromBytes(rr(iz((L&1)===0),k)),ue=a.inv(V),C=F(ct(O,void 0,"msgHash")),be=a.create(-C*ue),Ee=a.create(M*ue),Ce=e.BASE.multiplyUnsafe(be).add(te.multiplyUnsafe(Ee));if(Ce.is0())throw Error("invalid recovery: point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return _(this.s)}toBytes(O=g.format){if(wx(O),O==="der")return rc($n.hexFromSig(this));let{r:R,s:M}=this,L=a.toBytes(R),V=a.toBytes(M);if(O==="recovered")return A(),rr(Uint8Array.of(this.assertRecovery()),L,V);return rr(L,V)}toHex(O){return tc(this.toBytes(O))}}Object.freeze(j.prototype),Object.freeze(j);let E=r.bits2int===void 0?function(R){if(R.length>8192)throw Error("input is too large");let M=Ls(R),L=R.length*8-l;return L>0?M>>BigInt(L):M}:r.bits2int,F=r.bits2int_modN===void 0?function(R){return a.create(E(R))}:r.bits2int_modN,D=Uu(l);function H(O){return zi("num < 2^"+l,O,ti,D),a.toBytes(O)}function X(O,R){return ct(O,void 0,"message"),R?ct(i(O),void 0,"prehashed message"):O}function Z(O,R,M){let{lowS:L,prehash:V,extraEntropy:k}=xx(M,g);O=X(O,V);let te=F(O),ue=a.fromBytes(R);if(!a.isValidNot0(ue))throw Error("invalid private key");let C=[H(ue),H(te)];if(k!=null&&k!==!1){let Re=k===!0?n(y.secretKey):k;C.push(ct(Re,void 0,"extraEntropy"))}let be=rr(...C),Ee=te;function Ce(Re){let _e=E(Re);if(!a.isValidNot0(_e))return;let Je=a.inv(_e),Ne=e.BASE.multiply(_e).toAffine(),Ye=a.create(Ne.x);if(Ye===ti)return;let mt=a.create(Je*a.create(Ee+Ye*ue));if(mt===ti)return;let zt=(Ne.x===Ye?0:2)|Number(Ne.y&Eo),dr=mt;if(L&&_(mt))dr=a.neg(mt),zt^=1;return new j(Ye,dr,b?void 0:zt)}return{seed:be,k2sig:Ce}}function P(O,R,M={}){let{seed:L,k2sig:V}=Z(O,R,M);return zP(i.outputLen,a.BYTES,o)(L,V).toBytes(M.format)}function N(O,R,M,L={}){let{lowS:V,prehash:k,format:te}=xx(L,g);if(M=ct(M,void 0,"publicKey"),R=X(R,k),!nc(O)){let ue=O instanceof j?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ue)}z(O,te);try{let ue=j.fromBytes(O,te),C=e.fromBytes(M);if(V&&ue.hasHighS())return!1;let{r:be,s:Ee}=ue,Ce=F(R),Re=a.inv(Ee),_e=a.create(Ce*Re),Je=a.create(be*Re),Ne=e.BASE.multiplyUnsafe(_e).add(C.multiplyUnsafe(Je));if(Ne.is0())return!1;return a.create(Ne.x)===be}catch(ue){return!1}}function I(O,R,M={}){let{prehash:L}=xx(M,g);return R=X(R,L),j.fromBytes(O,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:p,utils:m,lengths:y,Point:e,sign:P,verify:N,recoverPublicKey:I,Signature:j,hash:i})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var _7=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))();var k7=nz(_7),ac=sz(k7,$t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var Io=BigInt(0),jr=BigInt(1),vx=BigInt(2),E7=BigInt(8);function I7(e,t,r,i){let n=e.sqr(r),o=e.sqr(i),s=e.add(e.mul(t.a,n),o),a=e.add(e.ONE,e.mul(t.d,e.mul(n,o)));return e.eql(s,a)}function az(e,t={}){let r=t,i=pm("edwards",e,r,r.FpFnLE),{Fp:n,Fn:o}=i,s=i.CURVE,{h:a}=s;fn(r,{},{uvRatio:"function"});let c=vx<<BigInt(o.BYTES*8)-jr,l=(g)=>n.create(g),u=r.uvRatio===void 0?(g,b)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,b))}}catch(_){return{isValid:!1,value:Io}}}:r.uvRatio;if(!I7(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function f(g,b,_=!1){let T=_?jr:Io;return zi("coordinate "+g,b,T,c),b}function p(g){if(!(g instanceof m))throw Error("EdwardsPoint expected")}class m{static BASE=new m(s.Gx,s.Gy,jr,l(s.Gx*s.Gy));static ZERO=new m(Io,jr,jr,Io);static Fp=n;static Fn=o;X;Y;Z;T;constructor(g,b,_,T){this.X=f("x",g),this.Y=f("y",b),this.Z=f("z",_,!0),this.T=f("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){if(g instanceof m)throw Error("extended point not allowed");let{x:b,y:_}=g||{};return f("x",b),f("y",_),new m(b,_,jr,l(b*_))}static fromBytes(g,b=!1){let _=n.BYTES,{a:T,d:A}=s;g=ko(ct(g,_,"point")),Pi(b,"zip215");let z=ko(g),j=g[_-1];z[_-1]=j&-129;let E=An(z),F=b?c:n.ORDER;zi("point.y",E,Io,F);let D=l(E*E),H=l(D-jr),X=l(A*D-T),{isValid:Z,value:P}=u(H,X);if(!Z)throw Error("bad point: invalid y coordinate");let N=(P&jr)===jr,I=(j&128)!==0;if(!b&&P===Io&&I)throw Error("bad point: x=0 and x_0=1");if(I!==N)P=l(-P);return m.fromAffine({x:P,y:E})}static fromHex(g,b=!1){return m.fromBytes(rc(g),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,b=!0){if(y.createCache(this,g),!b)this.multiply(vx);return this}assertValidity(){let g=this,{a:b,d:_}=s;if(g.is0())throw Error("bad point: ZERO");let{X:T,Y:A,Z:z,T:j}=g,E=l(T*T),F=l(A*A),D=l(z*z),H=l(D*D),X=l(E*b),Z=l(D*l(X+F)),P=l(H+l(_*l(E*F)));if(Z!==P)throw Error("bad point: equation left != right (1)");let N=l(T*A),I=l(z*j);if(N!==I)throw Error("bad point: equation left != right (2)")}equals(g){p(g);let{X:b,Y:_,Z:T}=this,{X:A,Y:z,Z:j}=g,E=l(b*j),F=l(A*T),D=l(_*j),H=l(z*T);return E===F&&D===H}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.X),this.Y,this.Z,l(-this.T))}double(){let{a:g}=s,{X:b,Y:_,Z:T}=this,A=l(b*b),z=l(_*_),j=l(vx*l(T*T)),E=l(g*A),F=b+_,D=l(l(F*F)-A-z),H=E+z,X=H-j,Z=E-z,P=l(D*X),N=l(H*Z),I=l(D*Z),O=l(X*H);return new m(P,N,O,I)}add(g){p(g);let{a:b,d:_}=s,{X:T,Y:A,Z:z,T:j}=this,{X:E,Y:F,Z:D,T:H}=g,X=l(T*E),Z=l(A*F),P=l(j*_*H),N=l(z*D),I=l((T+A)*(E+F)-X-Z),O=N-P,R=N+P,M=l(Z-b*X),L=l(I*O),V=l(R*M),k=l(I*M),te=l(O*R);return new m(L,V,te,k)}subtract(g){return p(g),this.add(g.negate())}multiply(g){if(!o.isValidNot0(g))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:_}=y.cached(this,g,(T)=>Us(m,T));return Us(m,[b,_])[0]}multiplyUnsafe(g){if(!o.isValid(g))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(g===Io)return m.ZERO;if(this.is0()||g===jr)return this;return y.unsafe(this,g,(b)=>Us(m,b))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return y.unsafe(this,s.n).is0()}toAffine(g){let b=this,_=g,{X:T,Y:A,Z:z}=b,j=b.is0();if(_==null)_=j?E7:n.inv(z);let E=l(T*_),F=l(A*_),D=n.mul(z,_);if(j)return{x:Io,y:jr};if(D!==jr)throw Error("invZ was invalid");return{x:E,y:F}}clearCofactor(){if(a===jr)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:g,y:b}=this.toAffine(),_=n.toBytes(b);return _[_.length-1]|=g&jr?128:0,_}toHex(){return tc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let y=new Mu(m,o.BITS);if(o.BITS>=8)m.BASE.precompute(8);return Object.freeze(m.prototype),Object.freeze(m),m}class _x{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){dx()}static fromHex(e){dx()}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 tc(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 Ku=BigInt(0),cc=BigInt(1),hm=BigInt(2);function T7(e){return fn(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function cz(e){let t=T7(e),{P:r,type:i,adjustScalarBytes:n,powPminus2:o,randomBytes:s}=t,a=i==="x25519";if(!a&&i!=="x448")throw Error("invalid type");let c=s===void 0?ic:s,l=a?255:448,u=a?32:56,f=a?BigInt(9):BigInt(5),p=a?BigInt(121665):BigInt(39081),m=a?hm**BigInt(254):hm**BigInt(447),y=a?BigInt(8)*hm**BigInt(251)-cc:BigInt(4)*hm**BigInt(445)-cc,g=m+y+cc,b=(I)=>gt(I,r),_=T(f);function T(I){return ju(b(I),u)}function A(I){let O=ko(ct(I,u,"uCoordinate"));if(a)O[31]&=127;return b(An(O))}function z(I){return An(n(ko(ct(I,u,"scalar"))))}function j(I,O){let R=X(A(O),z(I));if(R===Ku)throw Error("invalid private or public key received");return T(R)}function E(I){return j(I,_)}let F=E,D=j;function H(I,O,R){let M=b(I*(O-R));return O=b(O-M),R=b(R+M),{x_2:O,x_3:R}}function X(I,O){zi("u",I,Ku,r),zi("scalar",O,m,g);let R=O,M=I,L=cc,V=Ku,k=I,te=cc,ue=Ku;for(let be=BigInt(l-1);be>=Ku;be--){let Ee=R>>be&cc;ue^=Ee,{x_2:L,x_3:k}=H(ue,L,k),{x_2:V,x_3:te}=H(ue,V,te),ue=Ee;let Ce=L+V,Re=b(Ce*Ce),_e=L-V,Je=b(_e*_e),Ne=Re-Je,Ye=k+te,mt=k-te,zt=b(mt*Ce),dr=b(Ye*_e),Kr=zt+dr,Jr=zt-dr;k=b(Kr*Kr),te=b(M*b(Jr*Jr)),L=b(Re*Je),V=b(Ne*(Re+b(p*Ne)))}({x_2:L,x_3:k}=H(ue,L,k)),{x_2:V,x_3:te}=H(ue,V,te);let C=o(V);return b(L*C)}let Z={secretKey:u,publicKey:u,seed:u},P=(I)=>(I=I===void 0?c(u):I,ct(I,Z.seed,"seed"),I),N={randomSecretKey:P};return Object.freeze(Z),Object.freeze(N),Object.freeze({keygen:Fu(P,F),getSharedSecret:D,getPublicKey:F,scalarMult:j,scalarMultBase:E,utils:N,GuBytes:_.slice(),lengths:Z})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var A7=BigInt(0),Di=BigInt(1),lz=BigInt(2),$7=BigInt(3),C7=BigInt(5),R7=BigInt(8),Zs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Tx=(()=>({p:Zs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:R7,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function fz(e){let t=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),o=Zs,a=e*e%o*e%o,c=pn(a,lz,o)*a%o,l=pn(c,Di,o)*e%o,u=pn(l,C7,o)*l%o,f=pn(u,t,o)*u%o,p=pn(f,r,o)*f%o,m=pn(p,i,o)*p%o,y=pn(m,n,o)*m%o,g=pn(y,n,o)*m%o,b=pn(g,t,o)*u%o;return{pow_p_5_8:pn(b,lz,o)*e%o,b2:a}}function O7(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var kx=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Ax(e,t){let r=Zs,i=gt(t*t*t,r),n=gt(i*i*t,r),o=fz(e*n).pow_p_5_8,s=gt(e*i*o,r),a=gt(t*s*s,r),c=s,l=gt(s*kx,r),u=a===e,f=a===gt(-e,r),p=a===gt(-e*kx,r);if(u)s=c;if(f||p)s=l;if(Ni(s,r))s=gt(-s,r);return{isValid:u||f,value:s}}var qs=az(Tx,{uvRatio:Ax}),To=(()=>qs.Fp)(),pz=(()=>qs.Fn)();var gm=(()=>{let e=Zs;return cz({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:i}=fz(t);return gt(pn(r,$7,e)*i,e)},adjustScalarBytes:O7})})();var Ex=kx,P7=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),z7=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),N7=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),D7=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),uz=(e)=>Ax(Di,e),L7=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ix=(e)=>To.create(An(e)&L7);function dz(e){let{d:t}=Tx,r=Zs,i=(_)=>To.create(_),n=i(Ex*e*e),o=i((n+Di)*N7),s=BigInt(-1),a=i((s-t*n)*i(n+t)),{isValid:c,value:l}=Ax(o,a),u=i(l*e);if(!Ni(u,r))u=i(-u);if(!c)l=u;if(!c)s=n;let f=i(s*(n-Di)*D7-a),p=l*l,m=i((l+l)*a),y=i(f*P7),g=i(Di-p),b=i(Di+p);return new qs(i(m*b),i(g*y),i(y*b),i(m*g))}class Tr extends _x{static BASE=(()=>new Tr(qs.BASE))();static ZERO=(()=>new Tr(qs.ZERO))();static Fp=(()=>To)();static Fn=(()=>pz)();constructor(e){super(e)}static fromAffine(e){return new Tr(qs.fromAffine(e))}assertSame(e){if(!(e instanceof Tr))throw Error("RistrettoPoint expected")}init(e){return new Tr(e)}static fromBytes(e){Yt(e,32);let{a:t,d:r}=Tx,i=Zs,n=(A)=>To.create(A),o=Ix(e);if(!PP(To.toBytes(o),e)||Ni(o,i))throw Error("invalid ristretto255 encoding 1");let s=n(o*o),a=n(Di+t*s),c=n(Di-t*s),l=n(a*a),u=n(c*c),f=n(t*r*l-u),{isValid:p,value:m}=uz(n(f*u)),y=n(m*c),g=n(m*y*f),b=n((o+o)*y);if(Ni(b,i))b=n(-b);let _=n(a*g),T=n(b*_);if(!p||Ni(T,i)||_===A7)throw Error("invalid ristretto255 encoding 2");return new Tr(new qs(b,_,Di,T))}static fromHex(e){return Tr.fromBytes(mu(e))}toBytes(){let{X:e,Y:t,Z:r,T:i}=this.ep,n=Zs,o=(g)=>To.create(g),s=o(o(r+t)*o(r-t)),a=o(e*t),c=o(a*a),{value:l}=uz(o(s*c)),u=o(l*s),f=o(l*a),p=o(u*f*i),m;if(Ni(i*p,n)){let g=o(t*Ex),b=o(e*Ex);e=g,t=b,m=o(u*z7)}else m=f;if(Ni(e*p,n))t=o(-t);let y=o((r-t)*m);if(Ni(y,n))y=o(-y);return To.toBytes(y)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:i,Y:n}=e.ep,o=(c)=>To.create(c),s=o(t*n)===o(r*i),a=o(r*n)===o(t*i);return s||a}is0(){return this.equals(Tr.ZERO)}}Object.freeze(Tr.BASE);Object.freeze(Tr.ZERO);Object.freeze(Tr.prototype);Object.freeze(Tr);var B7=Object.freeze({Point:Tr,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,i=Sx(e,r,64,zp);return B7.deriveToCurve(i)},hashToScalar(e,t={DST:XP}){let r=Sx(e,t.DST,64,zp);return pz.create(An(r))},deriveToCurve(e){Yt(e,64);let t=Ix(e.subarray(0,32)),r=dz(t),i=Ix(e.subarray(32,64)),n=dz(i);return new Tr(r.add(n))}});var mz=!1,j7=!1;async function hz(e,t){if(j7)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 ym(e,t){return await hz(async()=>{let r=$x(e)?e:await q7(e),i=await crypto.subtle.importKey("raw",Z7(t),{name:"X25519"},mz,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:i},r,256))},()=>{if($x(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return gm.scalarMult(e,t)})}async function Ju(e){return await hz(async()=>ym(e,gm.GuBytes),()=>{if($x(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return gm.scalarMultBase(e)})}var U7=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function q7(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...U7,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},mz,["deriveBits"])}function $x(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function Z7(e){return e}class Cx{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),F7(Ms(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=Ms(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:Ms(this.transcript)}}}function F7(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function Ms(e){let t=e.reduce((n,o)=>n+o.length,0),r=new Uint8Array(t),i=0;for(let n of e)r.set(n,i),i+=n.length;return r}function lc(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let i of t)r.enqueue(i)}}))}function bm(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function Rx(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function gz(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function yz(e,t){let r=e.getReader(),i=[],n=0;while(n<t){let{done:c,value:l}=await r.read();if(c)throw Error("stream ended before reading "+t.toString()+" bytes");i.push(l),n+=l.length}r.releaseLock();let o=Ms(i),s=o.subarray(0,t),a=lc(e,o.subarray(t));return{data:s,rest:a}}class ri{args;body;constructor(e,t){this.args=e,this.body=t}}async function H7(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 o of r)if(o.length===0)throw Error("invalid stanza");let i=[];for(;;){let o=await e.readLine();if(o===null)throw Error("invalid stanza");let s=pr.decode(o);if(s.length>48)throw Error("invalid stanza");if(i.push(s),s.length<48)break}let n=Ms(i);return{s:new ri(r,n)}}async function bz(e){let t=new Cx(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let i=[];for(;;){let{s:n,next:o}=await H7(t);if(n!==void 0){i.push(n);continue}if(!o.startsWith("--- "))throw Error("invalid header");let s=pr.decode(o.slice(4)),{rest:a,transcript:c}=t.close(),l=c.slice(0,c.length-1-o.length+3);return{stanzas:i,headerNoMAC:l,MAC:s,headerSize:c.length,rest:lc(e,a)}}}function Ox(e){let t=[];t.push(`age-encryption.org/v1
|
|
725
725
|
`);for(let r of e){t.push("-> "+r.args.join(" ")+`
|
|
726
726
|
`);for(let i=0;i<r.body.length;i+=48){let n=i+48;if(n>r.body.length)n=r.body.length;t.push(pr.encode(r.body.subarray(i,n))+`
|
|
727
727
|
`)}if(r.body.length%48===0)t.push(`
|