@rizom/ops 0.2.0-alpha.756 → 0.2.0-alpha.757

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/index.js CHANGED
@@ -249,7 +249,7 @@ for (const spec of specs) {
249
249
  }
250
250
  `;var V2=v(()=>{Un()});function Ju(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=RG(e);return t===Object.prototype||t===null}function TG(e){return e instanceof Error&&"code"in e&&typeof e.code==="string"}function mh(e){return TG(e)&&e.code==="ENOENT"}var RG;var Ku=v(()=>{RG=Object.getPrototypeOf});import{lstat as cI,mkdir as W2,readFile as G2,unlink as $G,writeFile as Q2}from"fs/promises";import{join as pn}from"path";import{isDeepStrictEqual as OG}from"util";function tD(e){return pn("deploy","runtime",CG.parse(e.tag))}function rD(e){let t={"@rizom/brain":$t.parse(e.brainVersion)};for(let r of[...e.sitePackages].sort()){let o=r.lastIndexOf("@"),n=X2.parse(r.slice(0,o)),i=$t.parse(r.slice(o+1));if(t[n]!==void 0&&t[n]!==i)throw Error(`Conflicting runtime dependency pin: ${r}`);t[n]=i}return eD.parse({name:"rover-pilot-runtime",private:!0,packageManager:"bun@1.4.0",dependencies:t,overrides:{"postcss-selector-parser":"7.1.6"}})}async function lI(e){try{return await cI(e),!0}catch(t){if(mh(t))return!1;throw t}}async function Y2(e){if(!(await cI(e)).isFile())throw Error(`Runtime lock input must be a regular file: ${e}`)}async function nD(e){if(!(await cI(e)).isDirectory())throw Error(`Runtime lock input must be a directory: ${e}`)}async function oD(e){for(let t of["deploy",pn("deploy","runtime")]){let r=pn(e,t);if(await lI(r))await nD(r)}}async function aI(e,t){let r=pn(e,"package.json"),o=pn(e,"bun.lock");await Y2(r),await Y2(o);let n=eD.parse(JSON.parse(await G2(r,"utf8")));if(!OG(n,rD(t)))throw Error(`Runtime dependency manifest does not match ${t.tag}`);if(!(await G2(o,"utf8")).trim())throw Error(`Empty runtime dependency lock: ${o}`)}async function uI(e,t){await oD(e);let r=pn(e,tD(t));if(await nD(r),await lI(pn(r,".incomplete")))throw Error(`Incomplete runtime dependency lock: ${r}`);await aI(r,t)}async function iD(e,t,r=jt){if(Bun.version!=="1.4.0")throw Error("Runtime dependency locks must be generated with Bun 1.4.0");let o=rD(t);await oD(e);let n=pn(e,tD(t));if(await lI(n))return await uI(e,t),"existing";await W2(pn(e,"deploy","runtime"),{recursive:!0}),await W2(n);let i=pn(n,".incomplete");return await Q2(i,`Runtime dependency resolution has not completed.
251
251
  `,{flag:"wx"}),await Q2(pn(n,"package.json"),`${JSON.stringify(o,null,2)}
252
- `,{flag:"wx"}),await r(process.execPath,["install","--lockfile-only","--ignore-scripts"],{cwd:n}),await aI(n,t),await r(process.execPath,["install","--frozen-lockfile","--ignore-scripts","--dry-run"],{cwd:n}),await aI(n,t),await $G(i),"created"}var CG,X2,eD;var dI=v(()=>{Ku();pe();Zn();Un();CG=c.string().regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/),X2=c.string().regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/),eD=c.strictObject({name:c.literal("rover-pilot-runtime"),private:c.literal(!0),packageManager:c.literal("bun@1.4.0"),dependencies:c.record(X2,$t),overrides:c.strictObject({"postcss-selector-parser":c.literal("7.1.6")})})});function Hu(e,t=[]){let r=`brain-${e}`,o=[...new Set(t)].sort();if(o.length===0)return r;let n=`${r}--${o.map((a)=>a.replace(/^@/,"").replace("/","-").replace(/@(?=[^@]*$)/,"-")).join("--")}`,s=`--s${nh(JSON.stringify([e,...o])).slice(0,12)}`;return`${n.length+s.length<=PG?n:r}${s}`}function hh(e){if(!e)return[];return[sD(e.package,e.version),sD(e.theme,e.themeVersion)].filter((t)=>t!==void 0)}function sD(e,t){if(!e?.startsWith("@rizom/"))return;if(t===void 0)throw Error(`Package ${e} has no explicit version pin`);return`${e}@${t}`}function aD(e){let t=new Map;for(let r of e){let o=[...new Set(hh(r.siteOverride))].sort(),n=Hu(r.brainVersion,o),i=t.get(n);if(i&&(i.brainVersion!==r.brainVersion||!Bun.deepEquals(i.sitePackages,o)))throw Error(`Image tag collision for distinct runtime requirements: ${n}`);t.set(n,{tag:n,brainVersion:r.brainVersion,sitePackages:o})}return[...t.values()].sort((r,o)=>r.tag.localeCompare(o.tag))}function zG(e,t){let r=new Map;for(let o of[...e,...t]){let n=o.lastIndexOf("@"),i=n>0?o.slice(0,n):o,s=r.get(i);if(s&&s!==o)throw Error(`Fleet shared images have conflicting pins for ${i}: ${s} and ${o}`);r.set(i,o)}return[...r.values()].sort()}async function gh(e){let t=e.brainVersionInput?.trim()??"";if(t){let o=zG([],(e.sitePackagesInput??"").split(/\s+/).filter(Boolean)),n=Hu(t,o);if(!e.allowTagOverwrite&&await e.imageExists(n))throw Error(`Image tag ${n} already exists; published tags are immutable. Pick a new version, or pass overwrite=true only when replacing a tag whose containers were never deployed.`);return[{tag:n,brainVersion:t,sitePackages:o}]}let r=[];for(let o of aD(e.users))if(!await e.imageExists(o.tag))r.push(o);else await e.verifyImage(o);return r}async function NG(e,t,r){try{return await e("docker",["manifest","inspect",`${t}:${r}`]),!0}catch(o){if(o instanceof Error&&/exited with code/.test(o.message))return!1;throw o}}async function DG(e){let t=e.env??process.env,r=e.runCommand??jt,o=e.log??console.log,n=t.BRAIN_VERSION_INPUT?.trim()??"",i=t.SITE_PACKAGES_INPUT?.trim()??"",s=t.ALLOW_TAG_OVERWRITE?.trim()==="true",{users:a}=await ut(e.rootDir),l=await gh({users:a,brainVersionInput:n,sitePackagesInput:i,allowTagOverwrite:s,imageExists:(u)=>NG(r,e.imageRepository,u),verifyImage:(u)=>H2(e.imageRepository,u,r)});for(let u of l){try{await uI(e.rootDir,u)}catch(d){throw Error(`Missing or invalid runtime lock for ${u.tag}; run brains-ops images:lock and commit its reviewed package.json and bun.lock before building.`,{cause:d})}o(`build needed: ${u.tag} (brain ${u.brainVersion}${u.sitePackages.length>0?`, sites ${u.sitePackages.join(" ")}`:""})`)}if(l.length===0)o("All declared images already exist; nothing to build.");return e.writeOutput("images_json",JSON.stringify(l.map((u)=>({tag:u.tag,brain_version:u.brainVersion,site_packages:u.sitePackages.join(" ")})))),l}var PG=128;var yh=v(()=>{V2();dI();Hr();Un();oh()});var lD,LG,BG,jG,go,Vu,ZG,pI,UG,MG,cD,qG,FG,uD,$Ie,dD;var bh=v(()=>{PE();lD=["primary","secondary"],LG=c.custom((e)=>typeof e==="function","Expected a React component"),BG=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(lD).optional(),priority:c.number().optional()}),jG=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),go=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),Vu=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),ZG=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(jG).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:BG.optional(),translations:c.record(go,Vu).optional()}),pI=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(lD).optional(),priority:c.number().optional()}).optional()}),UG=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional()}),MG=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),cD=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),UG)}),qG=c.record(c.string(),c.json()),FG=c.record(c.string(),c.record(c.string(),qG)),uD={layouts:c.record(c.string(),LG).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(ZG),content:FG.optional(),sections:c.union([cD,c.array(cD)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),pI),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(go).min(1).optional(),dataSources:c.array(MG).readonly().optional()},$Ie=c.strictObject(uD).partial(),dD=c.strictObject(uD).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((b)=>p===b||p.startsWith(`${b}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[b,y]of(d.sections??[]).entries()){let S=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(S)t.addIssue({code:"custom",path:["routes",u,"sections",b,"template"],message:`Section template "${y.template}" is written "${S[1]}:${S[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let b=p.sections[m];if(!b){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=b.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var pD,fD,mD,Sh,hD,KG,gD,yD,HG,bD,SD,VG,vh;var fI=v(()=>{Tt();pe();bh();bh();pD=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),fD=["primary","secondary"],mD=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(fD).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),Sh=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(pD).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:mD,translations:c.record(go,Vu).optional(),languages:c.array(go).optional()}),hD=c.object({routes:c.array(Sh),pluginId:c.string()}),KG=we({channel:"plugin:site-builder:route:register",request:hD,response:c.void(),delivery:"command"}),gD=c.strictObject({}),yD=c.array(Sh),HG=we({channel:"site-builder:routes:list",request:gD,response:yD,delivery:"request"}),bD=c.strictObject({}),SD=c.array(Sh),VG=we({channel:"plugin:site-builder:pages",request:bD,response:SD,delivery:"collect"}),vh=c.object({label:c.string(),href:c.string(),priority:c.number()})});var vD,wD,xD,WG;var _D=v(()=>{Tt();pe();vD=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),wD=c.strictObject({}),xD=c.array(vD),WG=we({channel:"plugin:site-builder:slots",request:wD,response:xD,delivery:"collect"})});var ED="site:metadata:updated",wh,ID,kD,hc,AD,GG,QG,YG;var mI=v(()=>{Tt();pe();fI();wh=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),ID=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:wh.optional()}),kD=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),hc=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:wh.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),kD).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(go,ID).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),AD=c.strictObject({}),GG=we({channel:"site:metadata:get",request:AD,response:hc,delivery:"request"}),QG=di(ED,hc),YG=hc.extend({copyright:c.string(),navigation:c.object({primary:c.array(vh),secondary:c.array(vh)}),socialLinks:c.array(XE).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ![alt](entity://image/<id>)")})});var JIe;var hI=v(()=>{pe();JIe=c.record(c.string(),c.unknown())});var Wu=v(()=>{hI()});var RD=v(()=>{Tt();Wu()});var TD=v(()=>{Wu();Tt()});var $D=v(()=>{Wu();Tt()});var ake;var OD=v(()=>{pe();ake=c.record(c.string(),c.unknown())});var uke;var CD=v(()=>{pe();$a();uke=c.record(c.string(),c.unknown())});var PD=v(()=>{$a()});var zD=v(()=>{Wu();RD();TD();$D();OD();CD();PD();hI()});var cQ;var ND=v(()=>{pe();cQ=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var yI=v(()=>{zD();ND()});var DD=v(()=>{yI();pe()});var bI=()=>{};var lQ,uQ,dQ;var _h=v(()=>{pe();Tt();lQ={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},uQ={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},dQ=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var Eh=v(()=>{_h()});var jD=v(()=>{Eh()});var SI=()=>{};var fQ,mQ,gc,ZD,hQ;var UD=v(()=>{Tt();pe();SI();fQ=c.enum(["admin","trusted","public"]),mQ=c.enum(["create","update","delete","extract","publish"]),gc=c.enum(["never","admin","trusted","public"]),ZD=c.strictObject({create:gc.optional(),update:gc.optional(),delete:gc.optional(),extract:gc.optional(),publish:gc.optional()}),hQ=c.record(c.string(),ZD)});var MD=v(()=>{Eh();_h()});var gQ,yQ,Ih,bQ,SQ,vQ;var qD=v(()=>{pe();gQ=c.enum(["site-content-preview","site-content-production"]),yQ=c.enum(["web","image","pdf","epub"]),Ih=c.custom((e)=>typeof e==="function"),bQ=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([Ih,c.string()]).optional(),image:c.union([Ih,c.string()]).optional(),pdf:c.union([Ih,c.string()]).optional(),epub:c.union([Ih,c.string()]).optional()})}),SQ=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),vQ=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var FD=v(()=>{_h();jD();Eh();UD();SI();MD();qD()});var vI=ge(function(xQ,kh){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||St}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||St}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case Ae:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case ke:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(co.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){ds||(ds=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return ps[g]||(ps[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var ye=J===""?"."+L(se,0):J;return Or(M)?(D="",ye!=null&&(D=ye.replace(Ea,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(A(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Ea,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,ye=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Qo||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Qo=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
252
+ `,{flag:"wx"}),await r(process.execPath,["install","--lockfile-only","--ignore-scripts"],{cwd:n}),await aI(n,t),await r(process.execPath,["install","--frozen-lockfile","--ignore-scripts","--dry-run"],{cwd:n}),await aI(n,t),await $G(i),"created"}var CG,X2,eD;var dI=v(()=>{Ku();pe();Zn();Un();CG=c.string().regex(/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/),X2=c.string().regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/),eD=c.strictObject({name:c.literal("rover-pilot-runtime"),private:c.literal(!0),packageManager:c.literal("bun@1.4.0"),dependencies:c.record(X2,$t),overrides:c.strictObject({"postcss-selector-parser":c.literal("7.1.6")})})});function Hu(e,t=[]){let r=`brain-${e}`,o=[...new Set(t)].sort();if(o.length===0)return r;let n=`${r}--${o.map((a)=>a.replace(/^@/,"").replace("/","-").replace(/@(?=[^@]*$)/,"-")).join("--")}`,s=`--s${nh(JSON.stringify([e,...o])).slice(0,12)}`;return`${n.length+s.length<=PG?n:r}${s}`}function hh(e){if(!e)return[];return[sD(e.package,e.version),sD(e.theme,e.themeVersion)].filter((t)=>t!==void 0)}function sD(e,t){if(!e?.startsWith("@rizom/"))return;if(t===void 0)throw Error(`Package ${e} has no explicit version pin`);return`${e}@${t}`}function aD(e){let t=new Map;for(let r of e){let o=[...new Set(hh(r.siteOverride))].sort(),n=Hu(r.brainVersion,o),i=t.get(n);if(i&&(i.brainVersion!==r.brainVersion||!Bun.deepEquals(i.sitePackages,o)))throw Error(`Image tag collision for distinct runtime requirements: ${n}`);t.set(n,{tag:n,brainVersion:r.brainVersion,sitePackages:o})}return[...t.values()].sort((r,o)=>r.tag.localeCompare(o.tag))}function zG(e,t){let r=new Map;for(let o of[...e,...t]){let n=o.lastIndexOf("@"),i=n>0?o.slice(0,n):o,s=r.get(i);if(s&&s!==o)throw Error(`Fleet shared images have conflicting pins for ${i}: ${s} and ${o}`);r.set(i,o)}return[...r.values()].sort()}async function gh(e){let t=e.brainVersionInput?.trim()??"";if(t){let o=zG([],(e.sitePackagesInput??"").split(/\s+/).filter(Boolean)),n=Hu(t,o);if(!e.allowTagOverwrite&&await e.imageExists(n))throw Error(`Image tag ${n} already exists; published tags are immutable. Pick a new version, or pass overwrite=true only when replacing a tag whose containers were never deployed.`);return[{tag:n,brainVersion:t,sitePackages:o}]}let r=[];for(let o of aD(e.users))if(!await e.imageExists(o.tag))r.push(o);else await e.verifyImage(o);return r}async function NG(e,t,r){try{return await e("docker",["manifest","inspect",`${t}:${r}`]),!0}catch(o){if(o instanceof Error&&/exited with code/.test(o.message))return!1;throw o}}async function DG(e){let t=e.env??process.env,r=e.runCommand??jt,o=e.log??console.log,n=t.BRAIN_VERSION_INPUT?.trim()??"",i=t.SITE_PACKAGES_INPUT?.trim()??"",s=t.ALLOW_TAG_OVERWRITE?.trim()==="true",{users:a}=await ut(e.rootDir),l=await gh({users:a,brainVersionInput:n,sitePackagesInput:i,allowTagOverwrite:s,imageExists:(u)=>NG(r,e.imageRepository,u),verifyImage:(u)=>H2(e.imageRepository,u,r)});for(let u of l){try{await uI(e.rootDir,u)}catch(d){throw Error(`Missing or invalid runtime lock for ${u.tag}; run brains-ops images:lock and commit its reviewed package.json and bun.lock before building.`,{cause:d})}o(`build needed: ${u.tag} (brain ${u.brainVersion}${u.sitePackages.length>0?`, sites ${u.sitePackages.join(" ")}`:""})`)}if(l.length===0)o("All declared images already exist; nothing to build.");return e.writeOutput("images_json",JSON.stringify(l.map((u)=>({tag:u.tag,brain_version:u.brainVersion,site_packages:u.sitePackages.join(" ")})))),l}var PG=128;var yh=v(()=>{V2();dI();Hr();Un();oh()});var lD,LG,BG,jG,go,Vu,ZG,pI,UG,MG,cD,qG,FG,uD,CIe,dD;var bh=v(()=>{PE();lD=["primary","secondary"],LG=c.custom((e)=>typeof e==="function","Expected a React component"),BG=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(lD).optional(),priority:c.number().optional()}),jG=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),go=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),Vu=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),ZG=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(jG).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:BG.optional(),translations:c.record(go,Vu).optional()}),pI=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(lD).optional(),priority:c.number().optional()}).optional()}),UG=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional()}),MG=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),cD=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),UG)}),qG=c.record(c.string(),c.json()),FG=c.record(c.string(),c.record(c.string(),qG)),uD={layouts:c.record(c.string(),LG).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(ZG),content:FG.optional(),sections:c.union([cD,c.array(cD)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),pI),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(go).min(1).optional(),dataSources:c.array(MG).readonly().optional()},CIe=c.strictObject(uD).partial(),dD=c.strictObject(uD).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((b)=>p===b||p.startsWith(`${b}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[b,y]of(d.sections??[]).entries()){let S=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(S)t.addIssue({code:"custom",path:["routes",u,"sections",b,"template"],message:`Section template "${y.template}" is written "${S[1]}:${S[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let b=p.sections[m];if(!b){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=b.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var pD,fD,mD,Sh,hD,KG,gD,yD,HG,bD,SD,VG,vh;var fI=v(()=>{Tt();pe();bh();bh();pD=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),fD=["primary","secondary"],mD=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(fD).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),Sh=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(pD).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:mD,translations:c.record(go,Vu).optional(),languages:c.array(go).optional()}),hD=c.object({routes:c.array(Sh),pluginId:c.string()}),KG=we({channel:"plugin:site-builder:route:register",request:hD,response:c.void(),delivery:"command"}),gD=c.strictObject({}),yD=c.array(Sh),HG=we({channel:"site-builder:routes:list",request:gD,response:yD,delivery:"request"}),bD=c.strictObject({}),SD=c.array(Sh),VG=we({channel:"plugin:site-builder:pages",request:bD,response:SD,delivery:"collect"}),vh=c.object({label:c.string(),href:c.string(),priority:c.number()})});var vD,wD,xD,WG;var _D=v(()=>{Tt();pe();vD=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),wD=c.strictObject({}),xD=c.array(vD),WG=we({channel:"plugin:site-builder:slots",request:wD,response:xD,delivery:"collect"})});var ED="site:metadata:updated",wh,ID,kD,hc,AD,GG,QG,YG;var mI=v(()=>{Tt();pe();fI();wh=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),ID=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:wh.optional()}),kD=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),hc=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:wh.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),kD).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(go,ID).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),AD=c.strictObject({}),GG=we({channel:"site:metadata:get",request:AD,response:hc,delivery:"request"}),QG=di(ED,hc),YG=hc.extend({copyright:c.string(),navigation:c.object({primary:c.array(vh),secondary:c.array(vh)}),socialLinks:c.array(XE).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ![alt](entity://image/<id>)")})});var HIe;var hI=v(()=>{pe();HIe=c.record(c.string(),c.unknown())});var Wu=v(()=>{hI()});var RD=v(()=>{Tt();Wu()});var TD=v(()=>{Wu();Tt()});var $D=v(()=>{Wu();Tt()});var lke;var OD=v(()=>{pe();lke=c.record(c.string(),c.unknown())});var pke;var CD=v(()=>{pe();$a();pke=c.record(c.string(),c.unknown())});var PD=v(()=>{$a()});var zD=v(()=>{Wu();RD();TD();$D();OD();CD();PD();hI()});var cQ;var ND=v(()=>{pe();cQ=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var yI=v(()=>{zD();ND()});var DD=v(()=>{yI();pe()});var bI=()=>{};var lQ,uQ,dQ;var _h=v(()=>{pe();Tt();lQ={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},uQ={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},dQ=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var Eh=v(()=>{_h()});var jD=v(()=>{Eh()});var SI=()=>{};var fQ,mQ,gc,ZD,hQ;var UD=v(()=>{Tt();pe();SI();fQ=c.enum(["admin","trusted","public"]),mQ=c.enum(["create","update","delete","extract","publish"]),gc=c.enum(["never","admin","trusted","public"]),ZD=c.strictObject({create:gc.optional(),update:gc.optional(),delete:gc.optional(),extract:gc.optional(),publish:gc.optional()}),hQ=c.record(c.string(),ZD)});var MD=v(()=>{Eh();_h()});var gQ,yQ,Ih,bQ,SQ,vQ;var qD=v(()=>{pe();gQ=c.enum(["site-content-preview","site-content-production"]),yQ=c.enum(["web","image","pdf","epub"]),Ih=c.custom((e)=>typeof e==="function"),bQ=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([Ih,c.string()]).optional(),image:c.union([Ih,c.string()]).optional(),pdf:c.union([Ih,c.string()]).optional(),epub:c.union([Ih,c.string()]).optional()})}),SQ=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),vQ=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var FD=v(()=>{_h();jD();Eh();UD();SI();MD();qD()});var vI=ge(function(xQ,kh){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||St}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||St}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case Ae:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case ke:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(co.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){ds||(ds=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return ps[g]||(ps[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var ye=J===""?"."+L(se,0):J;return Or(M)?(D="",ye!=null&&(D=ye.replace(Ea,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(A(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Ea,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,ye=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Qo||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Qo=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
253
253
 
254
254
  Your code should look like:
255
255
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -405,7 +405,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
405
405
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
406
406
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){yg(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",n=[];if(o&&t.sep&&!t.value){let i=[];for(let s=0;s<t.sep.length;++s){let a=t.sep[s];switch(a.type){case"newline":i.push(s);break;case"space":break;case"comment":if(a.indent>e.indent)i.length=0;break;default:i.length=0}}if(i.length>=2)n=t.sep.splice(i[1])}switch(this.type){case"anchor":case"tag":if(o||t.value)n.push(this.sourceToken),e.items.push({start:n}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(o||t.value)n.push(this.sourceToken),e.items.push({start:n,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(wi(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=Tc(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(wi(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]});else if(gj(t.key)&&!wi(t.sep,"newline")){let i=Tc(t.start),s=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:s,sep:a}]})}else if(n.length>0)t.sep=t.sep.concat(n,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||o)e.items.push({start:n,key:null,sep:[this.sourceToken]});else if(wi(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);if(o||t.value)e.items.push({start:n,key:i,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(i);else Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0;return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!wi(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)e.items.push({start:n});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){yg(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||wi(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:o,sep:[]});else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=gg(r),n=Tc(o);hj(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
407
407
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
408
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=gg(e),r=Tc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=gg(e),r=Tc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ise.Parser=yj});var xj=ge(function(mse){var bj=Tk(),ase=fd(),Sd=md(),cse=jI(),lse=qe(),use=jk(),Sj=Zk();function vj(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new use.LineCounter||null,prettyErrors:t}}function dse(e,t={}){let{lineCounter:r,prettyErrors:o}=vj(t),n=new Sj.Parser(r?.addNewLine),i=new bj.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(Sd.prettifyError(e,r)),a.warnings.forEach(Sd.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function wj(e,t={}){let{lineCounter:r,prettyErrors:o}=vj(t),n=new Sj.Parser(r?.addNewLine),i=new bj.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new Sd.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(Sd.prettifyError(e,r)),s.warnings.forEach(Sd.prettifyError(e,r));return s}function pse(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=wj(e,r);if(!n)return null;if(n.warnings.forEach((i)=>cse.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function fse(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(lse.isDocument(e)&&!o)return e.toString(r);return new ase.Document(e,o,r).toString(r)}mse.parse=pse;mse.parseAllDocuments=dse;mse.parseDocument=wj;mse.stringify=fse});var Sse,vse,wse,Uk,xse,xi,_se,Ese,Ise,kse,oOe,Ase,Rse,Tse,bg,_j,$se,Ose,Cse,Pse,zse,Nse,Dse,Lse,Bse,jse,hn,So,Zse,vo,Mk,Use,Mse,qse,Fse,Jse,Kse,Hse,Vse,Wse,Gr,Gse,Qse,Yse;var $c=v(()=>{Sse=Tk(),vse=fd(),wse=fk(),Uk=md(),xse=Xu(),xi=qe(),_se=yi(),Ese=Et(),Ise=Si(),kse=vi(),oOe=mg(),Ase=Bk(),Rse=jk(),Tse=Zk(),bg=xj(),_j=Qu();$se=Sse.Composer,Ose=vse.Document,Cse=wse.Schema,Pse=Uk.YAMLError,zse=Uk.YAMLParseError,Nse=Uk.YAMLWarning,Dse=xse.Alias,Lse=xi.isAlias,Bse=xi.isCollection,jse=xi.isDocument,hn=xi.isMap,So=xi.isNode,Zse=xi.isPair,vo=xi.isScalar,Mk=xi.isSeq,Use=_se.Pair,Mse=Ese.Scalar,qse=Ise.YAMLMap,Fse=kse.YAMLSeq,Jse=Ase.Lexer,Kse=Rse.LineCounter,Hse=Tse.Parser,Vse=bg.parse,Wse=bg.parseAllDocuments,Gr=bg.parseDocument,Gse=bg.stringify,Qse=_j.visit,Yse=_j.visitAsync});var Rj={};Lt(Rj,{assertPilotUsersRemoved:()=>Fk,createPilotOffboardDriver:()=>qk,offboardPilotUsers:()=>Ij});import{readdir as Xse,readFile as eae,rm as vd,writeFile as tae}from"fs/promises";import{basename as rae,join as wo}from"path";async function Ij(e,t){let r=[...new Set(t.handles.map((p)=>mr.parse(p)))].sort((p,m)=>p.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await ut(e),l=r.map((p)=>nae(a,p,i)),u=t.driver??qk({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(l.map(async(p)=>({target:p,inspection:await u.inspect(p)})));if(iae(d),sae(d,o,s),!o){for(let p of d)if(!p.inspection.contentRepoArchived)await u.archiveContentRepo(p.target),s(`[${p.target.handle}] archived ${p.target.contentRepo}`);for(let p of d)for(let m of p.inspection.dnsRecords)await u.deleteDnsRecord(p.target,m),s(`[${p.target.handle}] deleted DNS ${m.name}`);for(let p of d)if(p.inspection.server)await u.deleteServer(p.target,p.inspection.server),s(`[${p.target.handle}] deleted ${p.target.instanceName}`);await oae(l,u,t.sleep??((p)=>new Promise((m)=>setTimeout(m,p)))),await aae(e,r),await mo(e),await Fk(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function nae(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=_I(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??Sg(r,"CF_ZONE_ID"),l=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=l.includes("/")?l:`${e.pilot.githubOrg}/${l}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function oae(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function iae(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function sae(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((l)=>`${l.type} ${l.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function aae(e,t){let r=new Set(t),o=wo(e,"cohorts");for(let n of(await Xse(o)).filter((i)=>i.endsWith(".yaml"))){let i=wo(o,n),s=await eae(i,"utf8"),a=Gr(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let l=a.get("members",!0);if(!Mk(l))throw Error(`${n}: members must be a sequence`);let u=l.items.filter((d)=>!vo(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===l.items.length)continue;if(u.length===0){await vd(i);continue}l.items=u,Kr.parse(a.toJS()),await tae(i,a.toString())}for(let n of t)await Promise.all([vd(wo(e,"users",`${n}.yaml`),{force:!0}),vd(wo(e,"users",`${n}.secrets.yaml`),{force:!0}),vd(wo(e,"users",`${n}.secrets.yaml.age`),{force:!0}),vd(wo(e,"users",n),{recursive:!0,force:!0})])}function qk(e){let t=e.fetchImpl??fetch,r=Sg(e.env,"HCLOUD_TOKEN"),o=Sg(e.env,"CF_API_TOKEN"),n=Sg(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,l]=await Promise.all([cae(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>lae(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),uae(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:l.archived}},async archiveContentRepo(i){await Oc(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:kj(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(Cc(await Oc(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:Aj(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await Oc(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function cae(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=Cc(await Oc(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=Cc(s),l=Ej(a.public_net),u=Ej(l?.ipv4);return{id:dae(a.id,"Hetzner server id"),name:wd(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function lae(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=Cc(await Oc(e,n.toString(),{headers:Aj(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let l=Cc(a),u=wd(l.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:wd(l.id,"Cloudflare record id"),name:wd(l.name,"Cloudflare record name"),type:u,content:wd(l.content,"Cloudflare record content")}})}async function uae(e,t,r){let o=Cc(await Oc(e,`https://api.github.com/repos/${r}`,{headers:kj(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function Oc(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function kj(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function Aj(e){return{Authorization:`Bearer ${e}`}}function Sg(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function Cc(e){if(!ks(e))throw Error("Provider returned an unexpected payload");return e}function Ej(e){return ks(e)?e:void 0}function wd(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function dae(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Fk(e,t){for(let r of t)for(let o of[wo(e,"users",`${r}.yaml`),wo(e,"users",`${r}.secrets.yaml.age`),wo(e,"users",r)])if(await Er(o))throw Error(`Offboarded user state remains: ${rae(o)}`)}var Jk=v(()=>{$c();Hr();EI();fc();Zn();Rs()});function Hk(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function vt(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 Ft(e,t,r=""){let o=Hk(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}function _o(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(vt(e.outputLen),vt(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function Pc(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 vg(e,t){Ft(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function wg(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function hr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zc(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function gn(e,t){return e<<32-t|e>>>t}function Fe(e,t){return e<<t|e>>>32-t>>>0}function wae(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function xae(e){for(let t=0;t<e.length;t++)e[t]=wae(e[t]);return e}function xg(e){if(Ft(e),Lj)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=_ae[e[r]];return t}function Dj(e){if(e>=xo._0&&e<=xo._9)return e-xo._0;if(e>=xo.A&&e<=xo.F)return e-(xo.A-10);if(e>=xo.a&&e<=xo.f)return e-(xo.a-10);return}function _d(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(Lj)try{return Uint8Array.fromHex(e)}catch(n){if(n instanceof SyntaxError)throw RangeError(n.message);throw n}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=Dj(e.charCodeAt(i)),a=Dj(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function Eae(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Wk(e,t=""){if(typeof e==="string")return Eae(e);return Ft(e,void 0,t)}function Gk(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Ft(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function _g(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 Qk(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.canXOF=o.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Eo(e=32){vt(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 vae,Vk,Lj,_ae,xo,Yk=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Qr=v(()=>{vae=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();Vk=vae?(e)=>e:xae,Lj=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),_ae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));xo={_0:48,_9:57,A:65,F:70,a:97,f:102}});class Xk{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(_o(e),Ft(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),hr(o)}update(e){return Pc(this),this.iHash.update(e),this}digestInto(e){Pc(this),vg(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Fn;var Ed=v(()=>{Qr();Fn=(()=>{let e=(t,r,o)=>new Xk(t,r).update(o).digest();return e.create=(t,r)=>new Xk(t,r),e})()});function Id(e,t,r){if(_o(e),r===void 0)r=new Uint8Array(e.outputLen);return Fn(e,r,t)}function tA(e,t,r,o=32){_o(e),vt(o,"length"),Ft(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=Bj;else Ft(r,void 0,"info");let s=new Uint8Array(i*n),a=Fn.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)eA[0]=d+1,l.update(d===0?Bj:u).update(r).update(eA).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),hr(u,eA),s.slice(0,o)}var eA,Bj,_i=(e,t,r,o,n)=>tA(e,Id(e,t,r),o,n);var rA=v(()=>{Ed();Qr();eA=Uint8Array.of(0),Bj=Uint8Array.of()});function jj(e,t,r){return e&t^~e&r}function Zj(e,t,r){return e&t^e&r^t&r}class Eg{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zc(this.buffer)}update(e){Pc(this),Ft(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=zc(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Pc(this),vg(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,hr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=zc(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var Io,Jt;var Uj=v(()=>{Qr();Io=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function Iae(e,t=!1){if(t)return{h:Number(e&Ig),l:Number(e>>Mj&Ig)};return{h:Number(e>>Mj&Ig)|0,l:Number(e&Ig)|0}}function qj(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=Iae(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Jn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var Ig,Mj,nA=(e,t,r)=>e>>>r,oA=(e,t,r)=>e<<32-r|t>>>r,Bs=(e,t,r)=>e>>>r|t<<32-r,js=(e,t,r)=>e<<32-r|t>>>r,kd=(e,t,r)=>e<<64-r|t>>>r-32,Ad=(e,t,r)=>e>>>r-32|t<<64-r,Fj=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Jj=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,Kj=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),Hj=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,Vj=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),Wj=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var Gj=v(()=>{Ig=BigInt(4294967295),Mj=BigInt(32)});var Aae,Ei,Qj,Yj,Xj,Rae,Tae,Ii,ki,eZ,tZ,wt,kg;var Nc=v(()=>{Uj();Gj();Qr();Aae=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]),Ei=new Uint32Array(64);Qj=class Qj extends Eg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Ei[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Ei[d-15],m=Ei[d-2],h=gn(p,7)^gn(p,18)^p>>>3,b=gn(m,17)^gn(m,19)^m>>>10;Ei[d]=b+Ei[d-7]+h+Ei[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=gn(s,6)^gn(s,11)^gn(s,25),m=u+p+jj(s,a,l)+Aae[d]+Ei[d]|0,b=(gn(r,2)^gn(r,13)^gn(r,22))+Zj(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){hr(Ei)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),hr(this.buffer)}};Yj=class Yj extends Qj{A=Io[0]|0;B=Io[1]|0;C=Io[2]|0;D=Io[3]|0;E=Io[4]|0;F=Io[5]|0;G=Io[6]|0;H=Io[7]|0;constructor(){super(32)}};Xj=(()=>qj(["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))))(),Rae=(()=>Xj[0])(),Tae=(()=>Xj[1])(),Ii=new Uint32Array(80),ki=new Uint32Array(80);eZ=class eZ extends Eg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ii[_]=e.getUint32(t),ki[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Ii[_-15]|0,O=ki[_-15]|0,L=Bs(A,O,1)^Bs(A,O,8)^nA(A,O,7),z=js(A,O,1)^js(A,O,8)^oA(A,O,7),K=Ii[_-2]|0,P=ki[_-2]|0,W=Bs(K,P,19)^kd(K,P,61)^nA(K,P,6),ee=js(K,P,19)^Ad(K,P,61)^oA(K,P,6),j=Kj(z,ee,ki[_-7],ki[_-16]),T=Hj(j,L,W,Ii[_-7],Ii[_-16]);Ii[_]=T|0,ki[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=Bs(d,p,14)^Bs(d,p,18)^kd(d,p,41),O=js(d,p,14)^js(d,p,18)^Ad(d,p,41),L=d&m^~d&b,z=p&h^~p&y,K=Vj(x,O,z,Tae[_],ki[_]),P=Wj(K,S,A,L,Rae[_],Ii[_]),W=K|0,ee=Bs(r,o,28)^kd(r,o,34)^kd(r,o,39),j=js(r,o,28)^Ad(r,o,34)^Ad(r,o,39),T=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Jn(l|0,u|0,P|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=Fj(W,j,B);r=Jj(I,P,ee,T),o=I|0}({h:r,l:o}=Jn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Jn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Jn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Jn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Jn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Jn(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=Jn(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=Jn(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,b,y,S,x)}roundClean(){hr(Ii,ki)}destroy(){this.destroyed=!0,hr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};tZ=class tZ extends eZ{Ah=Jt[0]|0;Al=Jt[1]|0;Bh=Jt[2]|0;Bl=Jt[3]|0;Ch=Jt[4]|0;Cl=Jt[5]|0;Dh=Jt[6]|0;Dl=Jt[7]|0;Eh=Jt[8]|0;El=Jt[9]|0;Fh=Jt[10]|0;Fl=Jt[11]|0;Gh=Jt[12]|0;Gl=Jt[13]|0;Hh=Jt[14]|0;Hl=Jt[15]|0;constructor(){super(64)}};wt=Qk(()=>new Yj,Yk(1)),kg=Qk(()=>new tZ,Yk(3))});function Og(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function aA(e){if(!Og(e))throw TypeError("Uint8Array expected")}function sZ(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 aZ(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function Ai(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function Td(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function Rg(e){if(!Array.isArray(e))throw TypeError("array expected")}function Tg(e,t){if(!sZ(!0,t))throw TypeError(`${e}: array of strings expected`)}function cA(e,t){if(!sZ(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Dr(...e){let t=(i)=>i,r=(i,s)=>(a)=>i(s(a)),o=e.map((i)=>i.encode).reduceRight(r,t),n=e.map((i)=>i.decode).reduce(r,t);return{encode:o,decode:n}}function Lr(e){let t=typeof e==="string"?e.split(""):e,r=t.length;Tg("alphabet",t);let o=new Map(t.map((n,i)=>[n,i]));return{encode:(n)=>(Rg(n),n.map((i)=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:(n)=>(Rg(n),n.map((i)=>{Ai("alphabet.decode",i);let s=o.get(i);if(s===void 0)throw Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Br(e=""){return Ai("join",e),{encode:(t)=>(Tg("join.decode",t),t.join(e)),decode:(t)=>(Ai("join.decode",t),t.split(e))}}function Cg(e,t="="){return Td(e),Ai("padding",t),{encode(r){Tg("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){Tg("padding.decode",r);let o=r.length;if(o*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;o>0&&r[o-1]===t;o--)if((o-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,o)}}}function cZ(e){return aZ(e),{encode:(t)=>t,decode:(t)=>e(t)}}function rZ(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(Rg(e),!e.length)return[];let o=0,n=[],i=Array.from(e,(a)=>{if(Td(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=i.length;while(!0){let a=0,l=!0;for(let u=o;u<s;u++){let d=i[u],p=t*a,m=p+d;if(!Number.isSafeInteger(m)||p/t!==a||m-d!==p)throw Error("convertRadix: carry overflow");let h=m/r;a=m%r;let b=Math.floor(h);if(i[u]=b,!Number.isSafeInteger(b)||b*r+a!==m)throw Error("convertRadix: carry overflow");if(!l)continue;else if(!b)o=u;else l=!1}if(n.push(a),l)break}for(let a=0;a<e.length-1&&e[a]===0;a++)n.push(0);return n.reverse()}function iA(e,t,r,o){if(Rg(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if($g(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${$g(t,r)}`);let n=0,i=0,s=Ag[t],a=Ag[r]-1,l=[];for(let u of e){if(Td(u),u>=s)throw Error(`convertRadix2: invalid data word=${u} from=${t}`);if(n=n<<t|u,i+t>32)throw Error(`convertRadix2: carry overflow pos=${i} from=${t}`);i+=t;for(;i>=r;i-=r)l.push((n>>i-r&a)>>>0);let d=Ag[i];if(d===void 0)throw Error("invalid carry");n&=d-1}if(n=n<<r-i&a,!o&&i>=t)throw Error("Excess padding");if(!o&&n>0)throw Error(`Non-zero padding: ${n}`);if(o&&i>0)l.push(n>>>0);return l}function $ae(e){Td(e);let t=256;return{encode:(r)=>{if(!Og(r))throw TypeError("radix.encode input should be Uint8Array");return rZ(Array.from(r),t,e)},decode:(r)=>(cA("radix.decode",r),Uint8Array.from(rZ(r,e,t)))}}function Yr(e,t=!1){if(Td(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if($g(8,e)>32||$g(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!Og(r))throw TypeError("radix2.encode input should be Uint8Array");return iA(Array.from(r),8,e,!t)},decode:(r)=>(cA("radix2.decode",r),Uint8Array.from(iA(r,e,8,t)))}}function nZ(e){return aZ(e),function(...t){try{return e.apply(null,t)}catch(r){}}}function Rd(e){let t=e>>25,r=(e&33554431)<<5;for(let o=0;o<oZ.length;o++)if((t>>o&1)===1)r^=oZ[o];return r}function iZ(e,t,r=1){let o=e.length,n=1;for(let i=0;i<o;i++){let s=e.charCodeAt(i);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=Rd(n)^s>>5}n=Rd(n);for(let i=0;i<o;i++)n=Rd(n)^e.charCodeAt(i)&31;for(let i of t)n=Rd(n)^i;for(let i=0;i<6;i++)n=Rd(n);return n^=r,sA.encode(iA([n%Ag[30]],30,5,!1))}function pZ(e){let t=e==="bech32"?1:734539939,r=Yr(5),o=r.decode,n=r.encode,i=nZ(o);function s(p,m,h=90){if(Ai("bech32.encode prefix",p),Og(m))m=Array.from(m);cA("bech32.encode",m);let b=p.length;if(b===0)throw TypeError(`Invalid prefix length ${b}`);let y=b+7+m.length;if(h!==!1&&y>h)throw TypeError(`Length ${y} exceeds limit ${h}`);let S=p.toLowerCase(),x=iZ(S,m,t);return`${S}1${sA.encode(m)}${x}`}function a(p,m=90){Ai("bech32.decode input",p);let h=p.length;if(h<8||m!==!1&&h>m)throw TypeError(`invalid string length: ${h} (${p}). Expected (8..${m})`);let b=p.toLowerCase();if(p!==b&&p!==p.toUpperCase())throw Error("String must be lowercase or uppercase");let y=b.lastIndexOf("1");if(y===0||y===-1)throw Error('Letter "1" must be present between prefix and data only');let S=b.slice(0,y),x=b.slice(y+1);if(x.length<6)throw Error("Data must be at least 6 characters long");let _=sA.decode(x).slice(0,-6),A=iZ(S,_,t);if(!x.endsWith(A))throw Error(`Invalid checksum in ${p}: expected "${A}"`);return{prefix:S,words:_}}let l=nZ(a);function u(p){let{prefix:m,words:h}=a(p,!1);return{prefix:m,words:h,bytes:o(h)}}function d(p,m){return s(p,n(m))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:l,fromWords:o,fromWordsUnsafe:i,toWords:n}}var lZ=(e,t)=>t===0?e:lZ(t,e%t),$g=(e,t)=>e+(t-lZ(e,t)),Ag,zOe,NOe,DOe,LOe,BOe,jOe,uZ,Oae,dZ=(e,t)=>{Ai("base64",e);let r=t?"base64url":"base64";if(e.length>0&&Oae.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},lA,tr,ZOe,UOe,uA=(e)=>Dr($ae(58),Lr(e),Br("")),MOe,qOe,FOe,sA,oZ,jr,JOe,Cae,Pae,KOe;var $d=v(()=>{/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ag=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();zOe=Object.freeze(Dr(Yr(4),Lr("0123456789ABCDEF"),Br(""))),NOe=Object.freeze(Dr(Yr(5),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Cg(5),Br(""))),DOe=Object.freeze(Dr(Yr(5),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Br(""))),LOe=Object.freeze(Dr(Yr(5),Lr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Cg(5),Br(""))),BOe=Object.freeze(Dr(Yr(5),Lr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Br(""))),jOe=Object.freeze(Dr(Yr(5),Lr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Br(""),cZ((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),uZ=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),Oae=/[\t\n\f\r ]/,lA=Object.freeze(uZ?{encode(e){return aA(e),e.toBase64()},decode(e){return dZ(e,!1)}}:Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Cg(6),Br(""))),tr=Object.freeze(Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Br(""))),ZOe=Object.freeze(uZ?{encode(e){return aA(e),e.toBase64({alphabet:"base64url"})},decode(e){return dZ(e,!0)}}:Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Cg(6),Br(""))),UOe=Object.freeze(Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Br(""))),MOe=Object.freeze(uA("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),qOe=Object.freeze(uA("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),FOe=Object.freeze(uA("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")),sA=Dr(Lr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Br("")),oZ=[996825010,642813549,513874426,1027748829,705979059];jr=Object.freeze(pZ("bech32")),JOe=Object.freeze(pZ("bech32m")),Cae=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Pae={encode(e){return aA(e),e.toHex()},decode(e){return Ai("hex",e),Uint8Array.fromHex(e)}},KOe=Object.freeze(Cae?Pae:Dr(Yr(4),Lr("0123456789abcdef"),Br(""),cZ((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 Nae(e,t,r,o){_o(e);let n=_g({dkLen:32,asyncTick:10},o),{c:i,dkLen:s,asyncTick:a}=n;if(vt(i,"c"),vt(s,"dkLen"),vt(a,"asyncTick"),i<1)throw Error("iterations (c) must be >= 1");if(s<1)throw Error('"dkLen" must be >= 1');if(s>4294967295*e.outputLen)throw Error("derived key too long");let l=Wk(t,"password"),u=Wk(r,"salt"),d=new Uint8Array(s),p=Fn.create(e,l),m=p._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:p,PRFSalt:m}}function Dae(e,t,r,o,n){if(e.destroy(),t.destroy(),o)o.destroy();return hr(n),r}function dA(e,t,r,o){let{c:n,dkLen:i,DK:s,PRF:a,PRFSalt:l}=Nae(e,t,r,o),u,d=new Uint8Array(4),p=zc(d),m=new Uint8Array(a.outputLen);for(let h=1,b=0;b<i;h++,b+=a.outputLen){let y=s.subarray(b,b+a.outputLen);p.setInt32(0,h,!1),(u=l._cloneInto(u)).update(d).digestInto(m),y.set(m.subarray(0,y.length));for(let S=1;S<n;S++){a._cloneInto(u).update(m).digestInto(m);for(let x=0;x<y.length;x++)y[x]^=m[x]}}return Dae(a,l,s,u,m)}var fZ=v(()=>{Ed();Qr()});function mZ(e,t,r,o,n,i){let s=e[t++]^r[o++],a=e[t++]^r[o++],l=e[t++]^r[o++],u=e[t++]^r[o++],d=e[t++]^r[o++],p=e[t++]^r[o++],m=e[t++]^r[o++],h=e[t++]^r[o++],b=e[t++]^r[o++],y=e[t++]^r[o++],S=e[t++]^r[o++],x=e[t++]^r[o++],_=e[t++]^r[o++],A=e[t++]^r[o++],O=e[t++]^r[o++],L=e[t++]^r[o++],z=s,K=a,P=l,W=u,ee=d,j=p,T=m,B=h,I=b,R=y,k=S,q=x,N=_,H=A,G=O,re=L;for(let ae=0;ae<8;ae+=2)ee^=Fe(z+N|0,7),I^=Fe(ee+z|0,9),N^=Fe(I+ee|0,13),z^=Fe(N+I|0,18),R^=Fe(j+K|0,7),H^=Fe(R+j|0,9),K^=Fe(H+R|0,13),j^=Fe(K+H|0,18),G^=Fe(k+T|0,7),P^=Fe(G+k|0,9),T^=Fe(P+G|0,13),k^=Fe(T+P|0,18),W^=Fe(re+q|0,7),B^=Fe(W+re|0,9),q^=Fe(B+W|0,13),re^=Fe(q+B|0,18),K^=Fe(z+W|0,7),P^=Fe(K+z|0,9),W^=Fe(P+K|0,13),z^=Fe(W+P|0,18),T^=Fe(j+ee|0,7),B^=Fe(T+j|0,9),ee^=Fe(B+T|0,13),j^=Fe(ee+B|0,18),q^=Fe(k+R|0,7),I^=Fe(q+k|0,9),R^=Fe(I+q|0,13),k^=Fe(R+I|0,18),N^=Fe(re+G|0,7),H^=Fe(N+re|0,9),G^=Fe(H+N|0,13),re^=Fe(G+H|0,18);n[i++]=s+z|0,n[i++]=a+K|0,n[i++]=l+P|0,n[i++]=u+W|0,n[i++]=d+ee|0,n[i++]=p+j|0,n[i++]=m+T|0,n[i++]=h+B|0,n[i++]=b+I|0,n[i++]=y+R|0,n[i++]=S+k|0,n[i++]=x+q|0,n[i++]=_+N|0,n[i++]=A+H|0,n[i++]=O+G|0,n[i++]=L+re|0}function pA(e,t,r,o,n){let i=o+0,s=o+16*n;for(let a=0;a<16;a++)r[s+a]=e[t+(2*n-1)*16+a];for(let a=0;a<n;a++,i+=16,t+=16){if(mZ(r,s,e,t,r,i),a>0)s+=16;mZ(r,i,e,t+=16,r,s)}}function Lae(e,t,r){let o=_g({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:i,p:s,dkLen:a,asyncTick:l,maxmem:u,onProgress:d}=o;if(vt(n,"N"),vt(i,"r"),vt(s,"p"),vt(a,"dkLen"),vt(l,"asyncTick"),vt(u,"maxmem"),d!==void 0&&typeof d!=="function")throw Error("progressCb must be a function");let p=128*i,m=p/4,h=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>h)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(h-1)*32/p)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(h-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let b=p*(n+s+1);if(b>u)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+b+", maxmem="+u);let y=dA(wt,e,t,{c:1,dkLen:p*s}),S=wg(y),x=wg(new Uint8Array(p*n)),_=wg(new Uint8Array(p)),A=()=>{};if(d){let O=2*n*s,L=Math.max(Math.floor(O/1e4),1),z=0;A=()=>{if(z++,d&&(!(z%L)||z===O))d(z/O)}}return{N:n,r:i,p:s,dkLen:a,blockSize32:m,V:x,B32:S,B:y,tmp:_,blockMixCb:A,asyncTick:l}}function Bae(e,t,r,o,n){let i=dA(wt,e,r,{c:1,dkLen:t});return hr(r,o,n),i}function fA(e,t,r){let{N:o,r:n,p:i,dkLen:s,blockSize32:a,V:l,B32:u,B:d,tmp:p,blockMixCb:m}=Lae(e,t,r);Vk(u);for(let h=0;h<i;h++){let b=a*h;for(let y=0;y<a;y++)l[y]=u[b+y];for(let y=0,S=0;y<o-1;y++)pA(l,S,l,S+=a,n),m();pA(l,(o-1)*a,u,b,n),m();for(let y=0;y<o;y++){let S=(u[b+a-16]&o-1)>>>0;for(let x=0;x<a;x++)p[x]=u[b+x]^l[S*a+x];pA(p,0,u,b,n),m()}}return Vk(u),Bae(e,s,d,l,p)}var hZ=v(()=>{fZ();Nc();Qr()});function jae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Pg(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function Dc(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 Ct(e,t,r=""){let o=jae(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}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 gZ(e,t,r=!1){Ct(e,void 0,"output");let o=t.outputLen;if(e.length<o)throw RangeError("digestInto() expects output buffer of length at least "+o);if(r&&!Lc(e))throw Error("invalid output, must be aligned")}function Kn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function yn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Zae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function yZ(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function bZ(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function SZ(e,t,r){let o=t,n=r||(()=>[]),i=(a,l)=>o(l,...n(a)).update(a).digest(),s=o(new Uint8Array(e),...n(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...l)=>o(a,...l),i}function Od(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(Ct(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Lc(t))throw Error("invalid output, must be aligned");return t}function wZ(e,t,r){Dc(e),Dc(t),Pg(r);let o=new Uint8Array(16),n=Zae(o);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),o}function Lc(e){return e.byteOffset%4===0}function Bc(e){return Uint8Array.from(Ct(e))}var Zs,Uae=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,Mae=(e)=>{for(let t=0;t<e.length;t++)e[t]=Uae(e[t]);return e},ko,vZ=(e,t)=>{function r(o,...n){if(Ct(o,void 0,"key"),e.nonceLength!==void 0){let d=n[0];Ct(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;if(i&&n[1]!==void 0)Ct(n[1],void 0,"AAD");let s=t(o,...n),a=(d,p)=>{if(p!==void 0){if(d!==2)throw Error("cipher output not supported");Ct(p,void 0,"output")}},l=!1;return{encrypt(d,p){if(l)throw Error("cannot encrypt() twice with same key + nonce");return l=!0,Ct(d),a(s.encrypt.length,p),s.encrypt(d,p)},decrypt(d,p){if(Ct(d),i&&d.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,p),s.decrypt(d,p)}}}return Object.assign(r,e),r};var zg=v(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Zs=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),ko=Zs?(e)=>e:Mae});function Je(e,t){return e<<t|e>>>32-t}function Kae(e,t,r,o,n,i,s,a){let l=n.length,u=new Uint8Array(Cd),d=Kn(u),p=Zs&&Lc(n)&&Lc(i),m=p?Kn(n):xZ,h=p?Kn(i):xZ;if(!Zs){for(let b=0;b<l;s++){if(e(t,r,o,d,s,a),ko(d),s>=hA)throw Error("arx: counter overflow");let y=Math.min(Cd,l-b);for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}return}for(let b=0;b<l;s++){if(e(t,r,o,d,s,a),s>=hA)throw Error("arx: counter overflow");let y=Math.min(Cd,l-b);if(p&&y===Cd){let S=b/4;if(b%4!==0)throw Error("arx: invalid block position");for(let x=0,_;x<Jae;x++)_=S+x,h[_]=m[_]^d[x];b+=Cd;continue}for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}}function EZ(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=yZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return Dc(n),Dc(s),Pg(i),Pg(r),(a,l,u,d,p=0)=>{Ct(a,void 0,"key"),Ct(l,void 0,"nonce"),Ct(u,void 0,"data");let m=u.length;if(d=Od(m,d,!1),Dc(p),p<0||p>=hA)throw Error("arx: counter overflow");let h=[],b=a.length,y,S;if(b===32)h.push(y=Bc(a)),S=Fae;else if(b===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),S=qae,h.push(y);else throw Ct(a,32,"arx key"),Error("invalid key size");if(!Zs||!Lc(l))h.push(l=Bc(l));let x=Kn(y);if(o){if(l.length!==24)throw Error("arx: extended nonce must be 24 bytes");let O=l.subarray(0,16);if(Zs)o(S,x,Kn(O),x);else{let L=ko(Uint32Array.from(S));o(L,x,Kn(O),x),yn(L),ko(x)}l=l.subarray(16)}else if(!Zs)ko(x);let _=16-n;if(_!==l.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let O=new Uint8Array(12);O.set(l,i?0:12-l.length),l=O,h.push(l)}let A=ko(Kn(l));try{return Kae(e,S,x,A,u,d,p,s),d}finally{yn(...h)}}}var _Z=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),qae,Fae,Cd=64,Jae=16,hA,xZ;var IZ=v(()=>{zg();qae=(()=>ko(Kn(_Z("expand 16-byte k"))))(),Fae=(()=>ko(Kn(_Z("expand 32-byte k"))))();hA=(()=>4294967295)(),xZ=Uint32Array.of()});function Kt(e,t){return e[t++]&255|(e[t++]&255)<<8}class kZ{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=Bc(Ct(e,32,"key"));let t=Kt(e,0),r=Kt(e,2),o=Kt(e,4),n=Kt(e,6),i=Kt(e,8),s=Kt(e,10),a=Kt(e,12),l=Kt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Kt(e,16+2*u)}process(e,t,r=!1){let o=r?0:2048,{h:n,r:i}=this,s=i[0],a=i[1],l=i[2],u=i[3],d=i[4],p=i[5],m=i[6],h=i[7],b=i[8],y=i[9],S=Kt(e,t+0),x=Kt(e,t+2),_=Kt(e,t+4),A=Kt(e,t+6),O=Kt(e,t+8),L=Kt(e,t+10),z=Kt(e,t+12),K=Kt(e,t+14),P=n[0]+(S&8191),W=n[1]+((S>>>13|x<<3)&8191),ee=n[2]+((x>>>10|_<<6)&8191),j=n[3]+((_>>>7|A<<9)&8191),T=n[4]+((A>>>4|O<<12)&8191),B=n[5]+(O>>>1&8191),I=n[6]+((O>>>14|L<<2)&8191),R=n[7]+((L>>>11|z<<5)&8191),k=n[8]+((z>>>8|K<<8)&8191),q=n[9]+(K>>>5|o),N=0,H=N+P*s+W*(5*y)+ee*(5*b)+j*(5*h)+T*(5*m);N=H>>>13,H&=8191,H+=B*(5*p)+I*(5*d)+R*(5*u)+k*(5*l)+q*(5*a),N+=H>>>13,H&=8191;let G=N+P*a+W*s+ee*(5*y)+j*(5*b)+T*(5*h);N=G>>>13,G&=8191,G+=B*(5*m)+I*(5*p)+R*(5*d)+k*(5*u)+q*(5*l),N+=G>>>13,G&=8191;let re=N+P*l+W*a+ee*s+j*(5*y)+T*(5*b);N=re>>>13,re&=8191,re+=B*(5*h)+I*(5*m)+R*(5*p)+k*(5*d)+q*(5*u),N+=re>>>13,re&=8191;let ae=N+P*u+W*l+ee*a+j*s+T*(5*y);N=ae>>>13,ae&=8191,ae+=B*(5*b)+I*(5*h)+R*(5*m)+k*(5*p)+q*(5*d),N+=ae>>>13,ae&=8191;let me=N+P*d+W*u+ee*l+j*a+T*s;N=me>>>13,me&=8191,me+=B*(5*y)+I*(5*b)+R*(5*h)+k*(5*m)+q*(5*p),N+=me>>>13,me&=8191;let be=N+P*p+W*d+ee*u+j*l+T*a;N=be>>>13,be&=8191,be+=B*s+I*(5*y)+R*(5*b)+k*(5*h)+q*(5*m),N+=be>>>13,be&=8191;let xe=N+P*m+W*p+ee*d+j*u+T*l;N=xe>>>13,xe&=8191,xe+=B*a+I*s+R*(5*y)+k*(5*b)+q*(5*h),N+=xe>>>13,xe&=8191;let Ae=N+P*h+W*m+ee*p+j*d+T*u;N=Ae>>>13,Ae&=8191,Ae+=B*l+I*a+R*s+k*(5*y)+q*(5*b),N+=Ae>>>13,Ae&=8191;let ke=N+P*b+W*h+ee*m+j*p+T*d;N=ke>>>13,ke&=8191,ke+=B*u+I*l+R*a+k*s+q*(5*y),N+=ke>>>13,ke&=8191;let _e=N+P*y+W*b+ee*h+j*m+T*p;N=_e>>>13,_e&=8191,_e+=B*d+I*u+R*l+k*a+q*s,N+=_e>>>13,_e&=8191,N=(N<<2)+N|0,N=N+H|0,H=N&8191,N=N>>>13,G+=N,n[0]=H,n[1]=G,n[2]=re,n[3]=ae,n[4]=me,n[5]=be,n[6]=xe,n[7]=Ae,n[8]=ke,n[9]=_e}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=o,o=e[s]>>>13,e[s]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+o,o=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(o^1)-1;for(let s=0;s<10;s++)r[s]&=n;n=~n;for(let s=0;s<10;s++)e[s]=e[s]&n|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=i&65535;yn(r)}update(e){mA(this),Ct(e),e=Bc(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,yn(this.h,this.r,this.buffer,this.pad)}digestInto(e){mA(this),gZ(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:o}=this;if(o){t[o++]=1;for(;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let i=0;i<8;i++)e[n++]=r[i]>>>0,e[n++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var AZ;var RZ=v(()=>{zg();AZ=SZ(32,(e)=>new kZ(e))});function Hae(e,t,r,o,n,i=20){let s=e[0],a=e[1],l=e[2],u=e[3],d=t[0],p=t[1],m=t[2],h=t[3],b=t[4],y=t[5],S=t[6],x=t[7],_=n,A=r[0],O=r[1],L=r[2],z=s,K=a,P=l,W=u,ee=d,j=p,T=m,B=h,I=b,R=y,k=S,q=x,N=_,H=A,G=O,re=L;for(let me=0;me<i;me+=2)z=z+ee|0,N=Je(N^z,16),I=I+N|0,ee=Je(ee^I,12),z=z+ee|0,N=Je(N^z,8),I=I+N|0,ee=Je(ee^I,7),K=K+j|0,H=Je(H^K,16),R=R+H|0,j=Je(j^R,12),K=K+j|0,H=Je(H^K,8),R=R+H|0,j=Je(j^R,7),P=P+T|0,G=Je(G^P,16),k=k+G|0,T=Je(T^k,12),P=P+T|0,G=Je(G^P,8),k=k+G|0,T=Je(T^k,7),W=W+B|0,re=Je(re^W,16),q=q+re|0,B=Je(B^q,12),W=W+B|0,re=Je(re^W,8),q=q+re|0,B=Je(B^q,7),z=z+j|0,re=Je(re^z,16),k=k+re|0,j=Je(j^k,12),z=z+j|0,re=Je(re^z,8),k=k+re|0,j=Je(j^k,7),K=K+T|0,N=Je(N^K,16),q=q+N|0,T=Je(T^q,12),K=K+T|0,N=Je(N^K,8),q=q+N|0,T=Je(T^q,7),P=P+B|0,H=Je(H^P,16),I=I+H|0,B=Je(B^I,12),P=P+B|0,H=Je(H^P,8),I=I+H|0,B=Je(B^I,7),W=W+ee|0,G=Je(G^W,16),R=R+G|0,ee=Je(ee^R,12),W=W+ee|0,G=Je(G^W,8),R=R+G|0,ee=Je(ee^R,7);let ae=0;o[ae++]=s+z|0,o[ae++]=a+K|0,o[ae++]=l+P|0,o[ae++]=u+W|0,o[ae++]=d+ee|0,o[ae++]=p+j|0,o[ae++]=m+T|0,o[ae++]=h+B|0,o[ae++]=b+I|0,o[ae++]=y+R|0,o[ae++]=S+k|0,o[ae++]=x+q|0,o[ae++]=_+N|0,o[ae++]=A+H|0,o[ae++]=O+G|0,o[ae++]=L+re|0}function $Z(e,t,r,o,n){if(n!==void 0)Ct(n,void 0,"AAD");let i=e(t,r,Gae),s=wZ(o.length,n?n.length:0,!0),a=AZ.create(i);if(n)TZ(a,n);TZ(a,o),a.update(s);let l=a.digest();return yn(i,s),l}var Vae,Wae,TZ=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(Wae.subarray(r))},Gae,Qae=(e)=>(t,r,o)=>({encrypt(i,s){let a=i.length;s=Od(a+16,s,!1),s.set(i);let l=s.subarray(0,-16);e(t,r,l,l,1);let u=$Z(e,t,r,l,o);return s.set(u,a),yn(u),s},decrypt(i,s){s=Od(i.length-16,s,!1);let a=i.subarray(0,-16),l=i.subarray(-16),u=$Z(e,t,r,a,o);if(!bZ(l,u))throw yn(u),Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,r,s,s,1),yn(u),s}}),Xr;var gA=v(()=>{IZ();RZ();zg();Vae=EZ(Hae,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Wae=new Uint8Array(16),Gae=new Uint8Array(32);Xr=vZ({blockSize:64,nonceLength:12,tagLength:16},Qae(Vae))});function jc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Re(e,t,r=""){let o=jc(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+l)}return e}function en(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Zt(e.outputLen),Zt(e.blockLen)}function Ro(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 Ng(e,t){Re(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function Dg(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 Lg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bn(e,t){return e<<32-t|e>>>t}function Xae(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ece(e){for(let t=0;t<e.length;t++)e[t]=Xae(e[t]);return e}function Us(e){if(Re(e),CZ)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=tce[e[r]];return t}function OZ(e){if(e>=Ao._0&&e<=Ao._9)return e-Ao._0;if(e>=Ao.A&&e<=Ao.F)return e-(Ao.A-10);if(e>=Ao.a&&e<=Ao.f)return e-(Ao.a-10);return}function Ms(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(CZ)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=OZ(e.charCodeAt(i)),a=OZ(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function It(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Re(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function Zc(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Ri(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 Yae,yA,CZ,tce,Ao,Ti=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Zr=v(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Yae=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();yA=Yae?(e)=>e:ece,CZ=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),tce=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Ao={_0:48,_9:57,A:65,F:70,a:97,f:102}});function Pd(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function PZ(e){if(typeof e==="bigint"){if(!Bg(e))throw Error("positive bigint expected, got "+e)}else Zt(e);return e}function zd(e){let t=PZ(e).toString(16);return t.length&1?"0"+t:t}function zZ(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?SA:BigInt("0x"+e)}function $i(e){return zZ(Us(e))}function Oi(e){return zZ(Us(jg(Re(e)).reverse()))}function Uc(e,t){Zt(t),e=PZ(e);let r=Ms(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function Nd(e,t){return Uc(e,t).reverse()}function jg(e){return Uint8Array.from(e)}function Ci(e){return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function rce(e,t,r){return Bg(e)&&Bg(t)&&Bg(r)&&t<=e&&e<r}function Dd(e,t,r,o){if(!rce(t,r,o))throw Error("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function vA(e){let t;for(t=0;e>SA;e>>=bA,t+=1);return t}function NZ(e,t,r){if(Zt(e,"hashLen"),Zt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...S)=>r(u,It(l,...S)),h=(S=n)=>{if(u=m(i,S),l=m(),S.length===0)return;u=m(s,S),l=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){l=m();let _=l.slice();x.push(_),S+=l.length}return It(...x)};return(S,x)=>{p(),h(S);let _=void 0;while(!(_=x(b())))h();return p(),_}}function qs(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function o(i,s,a){let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw Error(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}function wA(e){let t=new WeakMap;return(r,...o)=>{let n=t.get(r);if(n!==void 0)return n;let i=e(r,...o);return t.set(r,i),i}}var SA,bA,Bg=(e)=>typeof e==="bigint"&&SA<=e,Ld=(e)=>(bA<<BigInt(e))-bA;var Mc=v(()=>{Zr();Zr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */SA=BigInt(0),bA=BigInt(1)});function gr(e,t){let r=e%t;return r>=yr?r:t+r}function tn(e,t,r){let o=e;while(t-- >yr)o*=o,o%=r;return o}function DZ(e,t){if(e===yr)throw Error("invert: expected non-zero number");if(t<=yr)throw Error("invert: expected positive modulus, got "+t);let r=gr(e,t),o=t,n=yr,i=rr,s=rr,a=yr;while(r!==yr){let u=o/r,d=o%r,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==rr)throw Error("invert: does not exist");return gr(n,t)}function xA(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function qZ(e,t){let r=(e.ORDER+rr)/jZ,o=e.pow(t,r);return xA(e,o,t),o}function ice(e,t){let r=(e.ORDER-ZZ)/UZ,o=e.mul(t,Fs),n=e.pow(o,r),i=e.mul(t,n),s=e.mul(e.mul(i,Fs),n),a=e.mul(i,e.sub(s,e.ONE));return xA(e,a,t),a}function sce(e){let t=Zg(e),r=FZ(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+nce)/MZ;return(a,l)=>{let u=a.pow(l,s),d=a.mul(u,o),p=a.mul(u,n),m=a.mul(u,i),h=a.eql(a.sqr(d),l),b=a.eql(a.sqr(p),l);u=a.cmov(u,d,h),d=a.cmov(m,p,b);let y=a.eql(a.sqr(d),l),S=a.cmov(u,d,y);return xA(a,S,l),S}}function FZ(e){if(e<BZ)throw Error("sqrt is not defined for small field");let t=e-rr,r=0;while(t%Fs===yr)t/=Fs,r++;let o=Fs,n=Zg(e);while(LZ(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return qZ;let i=n.pow(o,t),s=(t+rr)/Fs;return function(l,u){if(l.is0(u))return u;if(LZ(l,u)!==1)throw Error("Cannot find square root");let d=r,p=l.mul(l.ONE,i),m=l.pow(u,t),h=l.pow(u,s);while(!l.eql(m,l.ONE)){if(l.is0(m))return l.ZERO;let b=1,y=l.sqr(m);while(!l.eql(y,l.ONE))if(b++,y=l.sqr(y),b===d)throw Error("Cannot find square root");let S=rr<<BigInt(d-b-1),x=l.pow(p,S);d=b,p=l.sqr(x),m=l.mul(m,p),h=l.mul(h,x)}return h}}function ace(e){if(e%jZ===BZ)return qZ;if(e%UZ===ZZ)return ice;if(e%MZ===oce)return sce(e);return FZ(e)}function _A(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=cce.reduce((o,n)=>(o[n]="function",o),t);return qs(e,r),e}function lce(e,t,r){if(r<yr)throw Error("invalid exponent, negatives unsupported");if(r===yr)return e.ONE;if(r===rr)return t;let o=e.ONE,n=t;while(r>yr){if(r&rr)o=e.mul(o,n);n=e.sqr(n),r>>=rr}return o}function Bd(e,t,r=!1){let o=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,l)=>{if(e.is0(a))return s;return o[l]=s,e.mul(s,a)},e.ONE),i=e.inv(n);return t.reduceRight((s,a,l)=>{if(e.is0(a))return s;return o[l]=e.mul(s,o[l]),e.mul(s,a)},i),o}function LZ(e,t){let r=(e.ORDER-rr)/Fs,o=e.pow(t,r),n=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),s=e.eql(o,e.neg(e.ONE));if(!n&&!i&&!s)throw Error("invalid Legendre symbol result");return n?1:i?0:-1}function uce(e,t){if(t!==void 0)Zt(t);let r=t!==void 0?t:e.toString(2).length,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}class JZ{ORDER;BITS;BYTES;isLE;ZERO=yr;ONE=rr;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=yr)throw Error("invalid field: expected ORDER > 0, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")this.sqrt=t.sqrt;if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=t.allowedLengths?.slice();if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=uce(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return gr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return yr<=e&&e<this.ORDER}is0(e){return e===yr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&rr)===rr}neg(e){return gr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return gr(e*e,this.ORDER)}add(e,t){return gr(e+t,this.ORDER)}sub(e,t){return gr(e-t,this.ORDER)}mul(e,t){return gr(e*t,this.ORDER)}pow(e,t){return lce(this,e,t)}div(e,t){return gr(e*DZ(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 DZ(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=ace(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?Nd(e,this.BYTES):Uc(e,this.BYTES)}fromBytes(e,t=!1){Re(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?Oi(e):$i(e);if(s)a=gr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Bd(this,e)}cmov(e,t,r){return r?t:e}}function Zg(e,t={}){return new JZ(e,t)}function KZ(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function EA(e){let t=KZ(e);return t+Math.ceil(t/2)}function HZ(e,t,r=!1){Re(e);let o=e.length,n=KZ(t),i=EA(t);if(o<16||o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?Oi(e):$i(e),a=gr(s,t-rr)+rr;return r?Nd(a,n):Uc(a,n)}var yr,rr,Fs,BZ,jZ,ZZ,nce,UZ,oce,MZ,cce;var jd=v(()=>{Mc();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */yr=BigInt(0),rr=BigInt(1),Fs=BigInt(2),BZ=BigInt(3),jZ=BigInt(4),ZZ=BigInt(5),nce=BigInt(7),UZ=BigInt(8),oce=BigInt(9),MZ=BigInt(16);cce=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function Zd(e,t){let r=t.negate();return e?r:t}function RA(e,t){let r=Bd(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function QZ(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function IA(e,t){QZ(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=Ld(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function VZ(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=Js;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function AA(e){return YZ.get(e)||1}function WZ(e){if(e!==qc)throw Error("invalid wNAF")}class TA{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>qc){if(t&Js)r=r.add(o);o=o.double(),t>>=Js}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=IA(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=IA(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=VZ(r,s,i);if(r=a,u)n=n.add(Zd(p,t[m]));else o=o.add(Zd(d,t[l]))}return WZ(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=IA(e,this.bits);for(let i=0;i<n.windows;i++){if(r===qc)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=VZ(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return WZ(r),o}getPrecomputes(e,t,r){let o=kA.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);kA.set(t,o)}}return o}cached(e,t,r){let o=AA(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=AA(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){QZ(t,this.bits),YZ.set(e,t),kA.delete(e)}hasCache(e){return AA(e)!==1}}function XZ(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>qc||o>qc){if(r&Js)i=i.add(n);if(o&Js)s=s.add(n);n=n.double(),r>>=Js,o>>=Js}return{p1:i,p2:s}}function GZ(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return _A(t),t}else return Zg(e,{isLE:r})}function eU(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>qc))throw Error(`CURVE.${l} must be positive bigint`)}let n=GZ(t.p,r.Fp,o),i=GZ(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function Ug(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var qc,Js,kA,YZ;var $A=v(()=>{Mc();jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */qc=BigInt(0),Js=BigInt(1);kA=new WeakMap,YZ=new WeakMap});function dce(e){return qs(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function tU(e){let t=dce(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s||Ri,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?Mg**BigInt(254):Mg**BigInt(447),b=a?BigInt(8)*Mg**BigInt(251)-Fc:BigInt(4)*Mg**BigInt(445)-Fc,y=h+b+Fc,S=(I)=>gr(I,r),x=_(p);function _(I){return Nd(S(I),d)}function A(I){let R=jg(Re(I,d,"uCoordinate"));if(a)R[31]&=127;return S(Oi(R))}function O(I){return Oi(n(jg(Re(I,d,"scalar"))))}function L(I,R){let k=ee(A(R),O(I));if(k===Ud)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,R,k){let q=S(I*(R-k));return R=S(R-q),k=S(k+q),{x_2:R,x_3:k}}function ee(I,R){Dd("u",I,Ud,r),Dd("scalar",R,h,y);let k=R,q=I,N=Fc,H=Ud,G=I,re=Fc,ae=Ud;for(let be=BigInt(u-1);be>=Ud;be--){let xe=k>>be&Fc;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let Ae=N+H,ke=S(Ae*Ae),_e=N-H,Ue=S(_e*_e),De=ke-Ue,Qe=G+re,St=G-re,Rt=S(St*Ae),Dt=S(Qe*_e),lt=Rt+Dt,Or=Rt-Dt;G=S(lt*lt),re=S(q*S(Or*Or)),N=S(ke*Ue),H=S(De*(ke+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return S(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(I=l(d))=>(Re(I,j.seed,"seed"),I),B={randomSecretKey:T};return Object.freeze({keygen:Ug(T,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}var Ud,Fc,Mg;var rU=v(()=>{Mc();$A();jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ud=BigInt(0),Fc=BigInt(1),Mg=BigInt(2)});class OA{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(en(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),kr(o)}update(e){return Ro(this),this.iHash.update(e),this}digestInto(e){Ro(this),Re(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Jc=(e,t,r)=>new OA(e,t).update(r).digest();var CA=v(()=>{Zr();Jc.create=(e,t)=>new OA(e,t)});function pce(e,t,r){let[[o,n],[i,s]]=t,a=nU(s*e,r),l=nU(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<To,m=d<To;if(p)u=-u;if(m)d=-d;let h=Ld(Math.ceil(vA(r)/2))+Kc;if(u<To||u>=h||d<To||d>=h)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:u,k2neg:m,k2:d}}function zA(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function PA(e,t){let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(Pd(r.lowS,"lowS"),Pd(r.prehash,"prehash"),r.format!==void 0)zA(r.format);return r}function NA(e,t={}){let r=eU("weierstrass",e,t),{Fp:o,Fn:n}=r,i=r.CURVE,{h:s,n:a}=i;qs(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=aU(o,n);function d(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function p(T,B,I){let{x:R,y:k}=B.toAffine(),q=o.toBytes(R);if(Pd(I,"isCompressed"),I){d();let N=!o.isOdd(k);return It(sU(N),q)}else return It(Uint8Array.of(4),q,o.toBytes(k))}function m(T){Re(T,void 0,"Point");let{publicKey:B,publicKeyUncompressed:I}=u,R=T.length,k=T[0],q=T.subarray(1);if(R===B&&(k===2||k===3)){let N=o.fromBytes(q);if(!o.isValid(N))throw Error("bad point: is not on curve, wrong x");let H=y(N),G;try{G=o.sqrt(H)}catch(me){let be=me instanceof Error?": "+me.message:"";throw Error("bad point: is not on curve, sqrt error"+be)}d();let re=o.isOdd(G);if((k&1)===1!==re)G=o.neg(G);return{x:N,y:G}}else if(R===I&&k===4){let N=o.BYTES,H=o.fromBytes(q.subarray(0,N)),G=o.fromBytes(q.subarray(N,N*2));if(!S(H,G))throw Error("bad point: is not on curve");return{x:H,y:G}}else throw Error(`bad point: got length ${R}, expected compressed=${B} or uncompressed=${I}`)}let h=t.toBytes||p,b=t.fromBytes||m;function y(T){let B=o.sqr(T),I=o.mul(B,T);return o.add(o.add(I,o.mul(T,i.a)),i.b)}function S(T,B){let I=o.sqr(B),R=y(T);return o.eql(I,R)}if(!S(i.Gx,i.Gy))throw Error("bad curve params: generator point");let x=o.mul(o.pow(i.a,qg),fce),_=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(x,_)))throw Error("bad curve params: a or b");function A(T,B,I=!1){if(!o.isValid(B)||I&&o.is0(B))throw Error(`bad point coordinate ${T}`);return B}function O(T){if(!(T instanceof W))throw Error("Weierstrass Point expected")}function L(T){if(!l||!l.basises)throw Error("no endo");return pce(T,l.basises,n.ORDER)}let z=wA((T,B)=>{let{X:I,Y:R,Z:k}=T;if(o.eql(k,o.ONE))return{x:I,y:R};let q=T.is0();if(B==null)B=q?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(R,B),G=o.mul(k,B);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}),K=wA((T)=>{if(T.is0()){if(t.allowInfinityPoint&&!o.is0(T.Y))return;throw Error("bad point: ZERO")}let{x:B,y:I}=T.toAffine();if(!o.isValid(B)||!o.isValid(I))throw Error("bad point: x or y not field elements");if(!S(B,I))throw Error("bad point: equation left != right");if(!T.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function P(T,B,I,R,k){return I=new W(o.mul(I.X,T),I.Y,I.Z),B=Zd(R,B),I=Zd(k,I),B.add(I)}class W{static BASE=new W(i.Gx,i.Gy,o.ONE);static ZERO=new W(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(T,B,I){this.X=A("x",T),this.Y=A("y",B,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(T){let{x:B,y:I}=T||{};if(!T||!o.isValid(B)||!o.isValid(I))throw Error("invalid affine point");if(T instanceof W)throw Error("projective point not allowed");if(o.is0(B)&&o.is0(I))return W.ZERO;return new W(B,I,o.ONE)}static fromBytes(T){let B=W.fromAffine(b(Re(T,void 0,"point")));return B.assertValidity(),B}static fromHex(T){return W.fromBytes(Ms(T))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(T=8,B=!0){if(j.createCache(this,T),!B)this.multiply(qg);return this}assertValidity(){K(this)}hasEvenY(){let{y:T}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(T)}equals(T){O(T);let{X:B,Y:I,Z:R}=this,{X:k,Y:q,Z:N}=T,H=o.eql(o.mul(B,N),o.mul(k,R)),G=o.eql(o.mul(I,N),o.mul(q,R));return H&&G}negate(){return new W(this.X,o.neg(this.Y),this.Z)}double(){let{a:T,b:B}=i,I=o.mul(B,qg),{X:R,Y:k,Z:q}=this,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=o.mul(R,R),ae=o.mul(k,k),me=o.mul(q,q),be=o.mul(R,k);return be=o.add(be,be),G=o.mul(R,q),G=o.add(G,G),N=o.mul(T,G),H=o.mul(I,me),H=o.add(N,H),N=o.sub(ae,H),H=o.add(ae,H),H=o.mul(N,H),N=o.mul(be,N),G=o.mul(I,G),me=o.mul(T,me),be=o.sub(re,me),be=o.mul(T,be),be=o.add(be,G),G=o.add(re,re),re=o.add(G,re),re=o.add(re,me),re=o.mul(re,be),H=o.add(H,re),me=o.mul(k,q),me=o.add(me,me),re=o.mul(me,be),N=o.sub(N,re),G=o.mul(me,ae),G=o.add(G,G),G=o.add(G,G),new W(N,H,G)}add(T){O(T);let{X:B,Y:I,Z:R}=this,{X:k,Y:q,Z:N}=T,H=o.ZERO,G=o.ZERO,re=o.ZERO,ae=i.a,me=o.mul(i.b,qg),be=o.mul(B,k),xe=o.mul(I,q),Ae=o.mul(R,N),ke=o.add(B,I),_e=o.add(k,q);ke=o.mul(ke,_e),_e=o.add(be,xe),ke=o.sub(ke,_e),_e=o.add(B,R);let Ue=o.add(k,N);return _e=o.mul(_e,Ue),Ue=o.add(be,Ae),_e=o.sub(_e,Ue),Ue=o.add(I,R),H=o.add(q,N),Ue=o.mul(Ue,H),H=o.add(xe,Ae),Ue=o.sub(Ue,H),re=o.mul(ae,_e),H=o.mul(me,Ae),re=o.add(H,re),H=o.sub(xe,re),re=o.add(xe,re),G=o.mul(H,re),xe=o.add(be,be),xe=o.add(xe,be),Ae=o.mul(ae,Ae),_e=o.mul(me,_e),xe=o.add(xe,Ae),Ae=o.sub(be,Ae),Ae=o.mul(ae,Ae),_e=o.add(_e,Ae),be=o.mul(xe,_e),G=o.add(G,be),be=o.mul(Ue,_e),H=o.mul(ke,H),H=o.sub(H,be),be=o.mul(ke,xe),re=o.mul(Ue,re),re=o.add(re,be),new W(H,G,re)}subtract(T){return this.add(T.negate())}is0(){return this.equals(W.ZERO)}multiply(T){let{endo:B}=t;if(!n.isValidNot0(T))throw Error("invalid scalar: out of range");let I,R,k=(q)=>j.cached(this,q,(N)=>RA(W,N));if(B){let{k1neg:q,k1:N,k2neg:H,k2:G}=L(T),{p:re,f:ae}=k(N),{p:me,f:be}=k(G);R=ae.add(be),I=P(B.beta,re,me,q,H)}else{let{p:q,f:N}=k(T);I=q,R=N}return RA(W,[I,R])[0]}multiplyUnsafe(T){let{endo:B}=t,I=this;if(!n.isValid(T))throw Error("invalid scalar: out of range");if(T===To||I.is0())return W.ZERO;if(T===Kc)return I;if(j.hasCache(this))return this.multiply(T);if(B){let{k1neg:R,k1:k,k2neg:q,k2:N}=L(T),{p1:H,p2:G}=XZ(W,I,k,N);return P(B.beta,H,G,R,q)}else return j.unsafe(I,T)}toAffine(T){return z(this,T)}isTorsionFree(){let{isTorsionFree:T}=t;if(s===Kc)return!0;if(T)return T(W,this);return j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:T}=t;if(s===Kc)return this;if(T)return T(W,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(T=!0){return Pd(T,"isCompressed"),this.assertValidity(),h(W,this,T)}toHex(T=!0){return Us(this.toBytes(T))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ee=n.BITS,j=new TA(W,t.endo?Math.ceil(ee/2):ee);return W.BASE.precompute(8),W}function sU(e){return Uint8Array.of(e?2:3)}function aU(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function mce(e,t={}){let{Fn:r}=e,o=t.randomBytes||Ri,n=Object.assign(aU(e.Fp,r),{seed:EA(r.ORDER)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h=o(n.seed)){return HZ(Re(h,n.seed,"seed"),r.ORDER)}function l(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n;if(!jc(h))return;if("_lengths"in r&&r._lengths||b===y)return;let x=Re(h,void 0,"key").length;return x===y||x===S}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=Ug(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function DA(e,t,r={}){en(t),qs(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes||Ri,n=r.hmac||((I,R)=>Jc(t,I,R)),{Fp:i,Fn:s}=e,{ORDER:a,BITS:l}=s,{keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h}=mce(e,r),b={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*iU<i.ORDER;function S(I){let R=a>>Kc;return I>R}function x(I,R){if(!s.isValidNot0(R))throw Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return R}function _(){if(y)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(I,R){zA(R);let k=h.signature,q=R==="compact"?k:R==="recovered"?k+1:void 0;return Re(I,q)}class O{r;s;recovery;constructor(I,R,k){if(this.r=x("r",I),this.s=x("s",R),k!=null){if(_(),![0,1,2,3].includes(k))throw Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(I,R=b.format){A(I,R);let k;if(R==="der"){let{r:G,s:re}=Pi.toSig(Re(I));return new O(G,re)}if(R==="recovered")k=I[0],R="compact",I=I.subarray(1);let q=h.signature/2,N=I.subarray(0,q),H=I.subarray(q,q*2);return new O(s.fromBytes(N),s.fromBytes(H),k)}static fromHex(I,R){return this.fromBytes(Ms(I),R)}assertRecovery(){let{recovery:I}=this;if(I==null)throw Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new O(this.r,this.s,I)}recoverPublicKey(I){let{r:R,s:k}=this,q=this.assertRecovery(),N=q===2||q===3?R+a:R;if(!i.isValid(N))throw Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(N),G=e.fromBytes(It(sU((q&1)===0),H)),re=s.inv(N),ae=z(Re(I,void 0,"msgHash")),me=s.create(-ae*re),be=s.create(k*re),xe=e.BASE.multiplyUnsafe(me).add(G.multiplyUnsafe(be));if(xe.is0())throw Error("invalid recovery: point at infinify");return xe.assertValidity(),xe}hasHighS(){return S(this.s)}toBytes(I=b.format){if(zA(I),I==="der")return Ms(Pi.hexFromSig(this));let{r:R,s:k}=this,q=s.toBytes(R),N=s.toBytes(k);if(I==="recovered")return _(),It(Uint8Array.of(this.assertRecovery()),q,N);return It(q,N)}toHex(I){return Us(this.toBytes(I))}}let L=r.bits2int||function(R){if(R.length>8192)throw Error("input is too large");let k=$i(R),q=R.length*8-l;return q>0?k>>BigInt(q):k},z=r.bits2int_modN||function(R){return s.create(L(R))},K=Ld(l);function P(I){return Dd("num < 2^"+l,I,To,K),s.toBytes(I)}function W(I,R){return Re(I,void 0,"message"),R?Re(t(I),void 0,"prehashed message"):I}function ee(I,R,k){let{lowS:q,prehash:N,extraEntropy:H}=PA(k,b);I=W(I,N);let G=z(I),re=s.fromBytes(R);if(!s.isValidNot0(re))throw Error("invalid private key");let ae=[P(re),P(G)];if(H!=null&&H!==!1){let Ae=H===!0?o(h.secretKey):H;ae.push(Re(Ae,void 0,"extraEntropy"))}let me=It(...ae),be=G;function xe(Ae){let ke=L(Ae);if(!s.isValidNot0(ke))return;let _e=s.inv(ke),Ue=e.BASE.multiply(ke).toAffine(),De=s.create(Ue.x);if(De===To)return;let Qe=s.create(_e*s.create(be+De*re));if(Qe===To)return;let St=(Ue.x===De?0:2)|Number(Ue.y&Kc),Rt=Qe;if(q&&S(Qe))Rt=s.neg(Qe),St^=1;return new O(De,Rt,y?void 0:St)}return{seed:me,k2sig:xe}}function j(I,R,k={}){let{seed:q,k2sig:N}=ee(I,R,k);return NZ(t.outputLen,s.BYTES,n)(q,N).toBytes(k.format)}function T(I,R,k,q={}){let{lowS:N,prehash:H,format:G}=PA(q,b);if(k=Re(k,void 0,"publicKey"),R=W(R,H),!jc(I)){let re=I instanceof O?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+re)}A(I,G);try{let re=O.fromBytes(I,G),ae=e.fromBytes(k);if(N&&re.hasHighS())return!1;let{r:me,s:be}=re,xe=z(R),Ae=s.inv(be),ke=s.create(xe*Ae),_e=s.create(me*Ae),Ue=e.BASE.multiplyUnsafe(ke).add(ae.multiplyUnsafe(_e));if(Ue.is0())return!1;return s.create(Ue.x)===me}catch(re){return!1}}function B(I,R,k={}){let{prehash:q}=PA(k,b);return R=W(R,q),O.fromBytes(I,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h,Point:e,sign:j,verify:T,recoverPublicKey:B,Signature:O,hash:t})}var nU=(e,t)=>(e+(e>=0?t:-t)/iU)/t,oU,Pi,To,Kc,iU,qg,fce;var cU=v(()=>{CA();Zr();Mc();$A();jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */oU=class oU extends Error{constructor(e=""){super(e)}};Pi={Err:oU,_tlv:{encode:(e,t)=>{let{Err:r}=Pi;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=zd(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?zd(n.length/2|128):"";return zd(e)+i+n+t},decode(e,t){let{Err:r}=Pi,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=Pi;if(e<To)throw new t("integer: negative integers are not allowed");let r=zd(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}=Pi;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 $i(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=Pi,n=Re(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Pi,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}},To=BigInt(0),Kc=BigInt(1),iU=BigInt(2),qg=BigInt(3),fce=BigInt(4)});function lU(e,t,r){return e&t^~e&r}function uU(e,t,r){return e&t^e&r^t&r}class Fg{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Lg(this.buffer)}update(e){Ro(this),Re(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=Lg(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ro(this),Ng(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,kr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=Lg(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var $o,Ht;var dU=v(()=>{Zr();$o=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ht=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428])});function hce(e,t=!1){if(t)return{h:Number(e&Jg),l:Number(e>>pU&Jg)};return{h:Number(e>>pU&Jg)|0,l:Number(e&Jg)|0}}function Kg(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=hce(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Hn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var Jg,pU,LA=(e,t,r)=>e>>>r,BA=(e,t,r)=>e<<32-r|t>>>r,Ks=(e,t,r)=>e>>>r|t<<32-r,Hs=(e,t,r)=>e<<32-r|t>>>r,Md=(e,t,r)=>e<<64-r|t>>>r-32,qd=(e,t,r)=>e>>>r-32|t<<64-r,fU=(e,t,r)=>e<<r|t>>>32-r,mU=(e,t,r)=>t<<r|e>>>32-r,hU=(e,t,r)=>t<<r-32|e>>>64-r,gU=(e,t,r)=>e<<r-32|t>>>64-r,yU=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),bU=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,SU=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),vU=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,wU=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),xU=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var jA=v(()=>{Jg=BigInt(4294967295),pU=BigInt(32)});var yce,zi,_U,EU,IU,bce,Sce,Ni,Di,kU,AU,Hg,RU;var ZA=v(()=>{dU();jA();Zr();yce=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]),zi=new Uint32Array(64);_U=class _U extends Fg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)zi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=zi[d-15],m=zi[d-2],h=bn(p,7)^bn(p,18)^p>>>3,b=bn(m,17)^bn(m,19)^m>>>10;zi[d]=b+zi[d-7]+h+zi[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=bn(s,6)^bn(s,11)^bn(s,25),m=u+p+lU(s,a,l)+yce[d]+zi[d]|0,b=(bn(r,2)^bn(r,13)^bn(r,22))+uU(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){kr(zi)}destroy(){this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}};EU=class EU extends _U{A=$o[0]|0;B=$o[1]|0;C=$o[2]|0;D=$o[3]|0;E=$o[4]|0;F=$o[5]|0;G=$o[6]|0;H=$o[7]|0;constructor(){super(32)}};IU=(()=>Kg(["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))))(),bce=(()=>IU[0])(),Sce=(()=>IU[1])(),Ni=new Uint32Array(80),Di=new Uint32Array(80);kU=class kU extends Fg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ni[_]=e.getUint32(t),Di[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Ni[_-15]|0,O=Di[_-15]|0,L=Ks(A,O,1)^Ks(A,O,8)^LA(A,O,7),z=Hs(A,O,1)^Hs(A,O,8)^BA(A,O,7),K=Ni[_-2]|0,P=Di[_-2]|0,W=Ks(K,P,19)^Md(K,P,61)^LA(K,P,6),ee=Hs(K,P,19)^qd(K,P,61)^BA(K,P,6),j=SU(z,ee,Di[_-7],Di[_-16]),T=vU(j,L,W,Ni[_-7],Ni[_-16]);Ni[_]=T|0,Di[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=Ks(d,p,14)^Ks(d,p,18)^Md(d,p,41),O=Hs(d,p,14)^Hs(d,p,18)^qd(d,p,41),L=d&m^~d&b,z=p&h^~p&y,K=wU(x,O,z,Sce[_],Di[_]),P=xU(K,S,A,L,bce[_],Ni[_]),W=K|0,ee=Ks(r,o,28)^Md(r,o,34)^Md(r,o,39),j=Hs(r,o,28)^qd(r,o,34)^qd(r,o,39),T=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Hn(l|0,u|0,P|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=yU(W,j,B);r=bU(I,P,ee,T),o=I|0}({h:r,l:o}=Hn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Hn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Hn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Hn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Hn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Hn(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=Hn(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=Hn(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,b,y,S,x)}roundClean(){kr(Ni,Di)}destroy(){kr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};AU=class AU extends kU{Ah=Ht[0]|0;Al=Ht[1]|0;Bh=Ht[2]|0;Bl=Ht[3]|0;Ch=Ht[4]|0;Cl=Ht[5]|0;Dh=Ht[6]|0;Dl=Ht[7]|0;Eh=Ht[8]|0;El=Ht[9]|0;Fh=Ht[10]|0;Fl=Ht[11]|0;Gh=Ht[12]|0;Gl=Ht[13]|0;Hh=Ht[14]|0;Hl=Ht[15]|0;constructor(){super(48)}};Hg=Zc(()=>new EU,Ti(1)),RU=Zc(()=>new AU,Ti(2))});function _ce(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=$U,a=e*e%i*e%i,l=tn(a,TU,i)*a%i,u=tn(l,vce,i)*e%i,d=tn(u,xce,i)*u%i,p=tn(d,t,i)*d%i,m=tn(p,r,i)*p%i,h=tn(m,o,i)*m%i,b=tn(h,n,i)*h%i,y=tn(b,n,i)*h%i,S=tn(y,t,i)*d%i;return{pow_p_5_8:tn(S,TU,i)*e%i,b2:a}}function Ece(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var vce,TU,wce,xce,WCe,$U,OU;var CU=v(()=>{jd();rU();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */vce=BigInt(1),TU=BigInt(2),wce=BigInt(3),xce=BigInt(5),WCe=BigInt(8),$U=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");OU=(()=>{let e=$U;return tU({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=_ce(t);return gr(tn(r,wce,e)*o,e)},adjustScalarBytes:Ece})})()});var Ice,kce,Ace,UA,Rce,PU;var zU=v(()=>{ZA();cU();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ice=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),kce=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))(),Ace=NA(Ice),UA=DA(Ace,Hg),Rce=NA(kce),PU=DA(Rce,RU)});function DU(e,t,r){if(en(e),r===void 0)r=new Uint8Array(e.outputLen);return Jc(e,r,t)}function LU(e,t,r,o=32){en(e),Zt(o,"length");let n=e.outputLen;if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=NU;else Re(r,void 0,"info");let s=new Uint8Array(i*n),a=Jc.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)MA[0]=d+1,l.update(d===0?NU:u).update(r).update(MA).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),kr(u,MA),s.slice(0,o)}var MA,NU;var BU=v(()=>{CA();Zr();MA=Uint8Array.of(0),NU=Uint8Array.of()});function Dce(e,t=24){let r=new Uint32Array(10);for(let o=24-t;o<24;o++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,l=(s+2)%10,u=r[l],d=r[l+1],p=jU(u,d,1)^r[a],m=ZU(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let n=e[2],i=e[3];for(let s=0;s<24;s++){let a=MU[s],l=jU(n,i,a),u=ZU(n,i,a),d=UU[s];n=e[d],i=e[d+1],e[d]=l,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=zce[o],e[1]^=Nce[o]}kr(r)}class Vg{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=n,Zt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Dg(this.state)}clone(){return this._cloneInto()}keccak(){yA(this.state32),Dce(this.state32,this.rounds),yA(this.state32),this.posOut=0,this.pos=0}update(e){Ro(this),Re(e);let{blockLen:t,state:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(t-this.pos,o-n);for(let s=0;s<i;s++)r[this.pos++]^=e[n++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:o}=this;if(e[r]^=t,(t&128)!==0&&r===o-1)this.keccak();e[o-1]^=128,this.keccak()}writeInto(e){Ro(this,!1),Re(e),this.finish();let t=this.state,{blockLen:r}=this;for(let o=0,n=e.length;o<n;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,n-o);e.set(t.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ng(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,kr(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:o,rounds:n,enableXOF:i}=this;return e||=new Vg(t,r,o,i,n),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}var Tce,Fd,$ce,Oce,Cce,Pce,UU,MU,qU,FU,zce,Nce,jU=(e,t,r)=>r>32?hU(e,t,r):fU(e,t,r),ZU=(e,t,r)=>r>32?gU(e,t,r):mU(e,t,r),JU=(e,t,r,o={})=>Zc(()=>new Vg(t,e,r),o),Vs,KU,HU=(e,t,r,o={})=>Zc((n={})=>new Vg(t,e,n.dkLen===void 0?r:n.dkLen,!0),o),VU,Vn;var Wg=v(()=>{jA();Zr();Tce=BigInt(0),Fd=BigInt(1),$ce=BigInt(2),Oce=BigInt(7),Cce=BigInt(256),Pce=BigInt(113),UU=[],MU=[],qU=[];for(let e=0,t=Fd,r=1,o=0;e<24;e++){[r,o]=[o,(2*r+3*o)%5],UU.push(2*(5*o+r)),MU.push((e+1)*(e+2)/2%64);let n=Tce;for(let i=0;i<7;i++)if(t=(t<<Fd^(t>>Oce)*Pce)%Cce,t&$ce)n^=Fd<<(Fd<<BigInt(i))-Fd;qU.push(n)}FU=Kg(qU,!0),zce=FU[0],Nce=FU[1];Vs=JU(6,136,32,Ti(8)),KU=JU(6,72,64,Ti(10)),VU=HU(31,168,16,Ti(11)),Vn=HU(31,136,32,Ti(12))});function qA(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function GU(e){return qA(e),(e&e-1)===0&&e!==0}function FA(e,t){qA(e);let r=0;for(let o=0;o<t;o++,e>>>=1)r=r<<1|e&1;return r}function QU(e){return qA(e),31-Math.clz32(e)}function WU(e){let t=e.length;if(t<2||!GU(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=QU(t);for(let o=0;o<t;o++){let n=FA(o,r);if(o<n){let i=e[o];e[o]=e[n],e[n]=i}}return e}var JA=(e,t)=>{let{N:r,roots:o,dit:n,invertButterflies:i=!1,skipStages:s=0,brp:a=!0}=t,l=QU(r);if(!GU(r))throw Error("FFT: Polynomial size should be power of two");let u=n!==i;return(d)=>{if(d.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)WU(d);for(let p=0,m=1;p<l-s;p++){let h=n?p+1+s:l-p,b=1<<h,y=b>>1,S=r>>h;for(let x=0;x<r;x+=b)for(let _=0,A=m++;_<y;_++){let O=i?n?r-A:A:_*S,L=x+_,z=x+_+y,K=o[O],P=d[z],W=d[L];if(u){let ee=e.mul(P,K);d[L]=e.add(W,ee),d[z]=e.sub(W,ee)}else if(i)d[L]=e.add(P,W),d[z]=e.mul(e.sub(P,W),K);else d[L]=e.add(W,P),d[z]=e.mul(e.sub(W,P),K)}}if(!n&&a)WU(d);return d}};var YU=()=>{};function Gg(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function XU(e){return Uint8Array.from(e)}function Ws(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,o=t.reduce((n,i)=>n+r(i),0);return{bytesLen:o,encode:(n)=>{let i=new Uint8Array(o);for(let s=0,a=0;s<t.length;s++){let l=t[s],u=r(l),d=typeof l==="number"?n[s]:l.encode(n[s]);if(Re(d,u,e),i.set(d,a),typeof l!=="number")d.fill(0);a+=u}return i},decode:(n)=>{Re(n,o,e);let i=[];for(let s of t){let a=r(s),l=n.subarray(0,a);i.push(typeof s==="number"?l:s.decode(l)),n=n.subarray(a)}return i}}}function Qg(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(o)=>{if(o.length!==t)throw Error(`vecCoder.encode: wrong length=${o.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let i=0,s=0;i<o.length;i++){let a=e.encode(o[i]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(o)=>{Re(o,r);let n=[];for(let i=0;i<o.length;i+=e.bytesLen)n.push(e.decode(o.subarray(i,i+e.bytesLen)));return n}}}function Pt(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function KA(e){return(1<<e)-1}var Wn,u1e;var Yg=v(()=>{Zr();Zr();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */Wn=Ri;u1e=Uint8Array.of()});var e6=(e)=>{let{newPoly:t,N:r,Q:o,F:n,ROOT_OF_UNITY:i,brvBits:s,isKyber:a}=e,l=(_,A=o)=>{let O=_%A|0;return(O>=0?O|0:A+O|0)|0},u=(_,A=o)=>{let O=l(_,A)|0;return(O>A>>1?O-A|0:O)|0};function d(){let _=t(r);for(let A=0;A<r;A++){let O=FA(A,s),L=BigInt(i)**BigInt(O)%BigInt(o);_[A]=Number(L)|0}return _}let p=d(),m={add:(_,A)=>l((_|0)+(A|0))|0,sub:(_,A)=>l((_|0)-(A|0))|0,mul:(_,A)=>l((_|0)*(A|0))|0,inv:(_)=>{throw Error("not implemented")}},h={N:r,roots:p,invertButterflies:!0,skipStages:a?1:0,brp:!1},b=JA(m,{dit:!1,...h}),y=JA(m,{dit:!0,...h});return{mod:l,smod:u,nttZetas:p,NTT:{encode:(_)=>b(_),decode:(_)=>{y(_);for(let A=0;A<_.length;A++)_[A]=l(n*_[A]);return _}},bitsCoder:(_,A)=>{let O=KA(_),L=_*(r/8);return{bytesLen:L,encode:(z)=>{let K=new Uint8Array(L);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=(A.encode(z[P])&O)<<ee,ee+=_;for(;ee>=8;ee-=8,W>>=8)K[j++]=W&KA(ee)}return K},decode:(z)=>{let K=t(r);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=z[P]<<ee,ee+=8;for(;ee>=_;ee-=_,W>>=_)K[j++]=A.decode(W&O)}return K}}}}},Lce=(e)=>(t,r)=>{if(!r)r=e.blockLen;let o=new Uint8Array(t.length+2);o.set(t);let n=t.length,i=new Uint8Array(r),s=e.create({}),a=0,l=0;return{stats:()=>({calls:a,xofs:l}),get:(u,d)=>(o[n+0]=u,o[n+1]=d,s.destroy(),s=e.create({}).update(o),a++,()=>(l++,s.xofInto(i))),clean:()=>{s.destroy(),Pt(i,o)}}},t6;var r6=v(()=>{YU();Wg();Yg();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */t6=Lce(VU)});function Qs(e,t){for(let r=0;r<nr;r++)e[r]=Hd(e[r]+t[r])}function qce(e,t){for(let r=0;r<nr;r++)e[r]=Hd(e[r]-t[r])}function Fce(e,t,r,o,n){let i=Hd(t*o*n+e*r),s=Hd(e*o+t*r);return{c0:i,c1:s}}function Xg(e,t){for(let r=0;r<nr/2;r++){let o=Zce[64+(r>>1)];if(r&1)o=-o;let{c0:n,c1:i}=Fce(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],o);e[2*r+0]=n,e[2*r+1]=i}return e}function n6(e){let t=new Uint16Array(nr);for(let r=0;r<nr;){let o=e();if(o.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<nr&&n+3<=o.length;n+=3){let i=(o[n+0]>>0|o[n+1]<<8)&4095,s=(o[n+1]>>4|o[n+2]<<4)&4095;if(i<Oo)t[r++]=i;if(r<nr&&s<Oo)t[r++]=s}}return t}function Kd(e,t,r,o){let n=e(o*nr/4,t,r),i=new Uint16Array(nr),s=Dg(n),a=0;for(let l=0,u=0,d=0,p=0;l<s.length;l++){let m=s[l];for(let h=0;h<32;h++)if(d+=m&1,m>>=1,a+=1,a===o)p=d,d=0;else if(a===2*o)i[u++]=Hd(p-d),d=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return i}function VA(e){let t=Jce(e),{HASH256:r,HASH512:o,KDF:n}=e,{secretCoder:i,lengths:s}=t,a=Ws("secretKey",s.secretKey,s.publicKey,32,32),l=32,u=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(d=Wn(64))=>{Re(d,64,"seed");let{publicKey:p,secretKey:m}=t.keygen(d.subarray(0,32)),h=r(p),b=a.encode([m,p,h,d.subarray(32)]);return Pt(m,h),{publicKey:p,secretKey:b}},getPublicKey:(d)=>{let[p,m,h,b]=a.decode(d);return Uint8Array.from(m)},encapsulate:(d,p=Wn(32))=>{Re(d,s.publicKey,"publicKey"),Re(p,32,"message");let m=d.subarray(0,384*e.K),h=i.encode(i.decode(XU(m)));if(!Gg(h,m))throw Pt(h),Error("ML-KEM.encapsulate: wrong publicKey modulus");Pt(h);let b=o.create().update(p).update(r(d)).digest(),y=t.encrypt(d,p,b.subarray(32,64));return Pt(b.subarray(32)),{cipherText:y,sharedSecret:b.subarray(0,32)}},decapsulate:(d,p)=>{Re(p,a.bytesLen,"secretKey"),Re(d,s.cipherText,"cipherText");let m=a.bytesLen-96,h=m+32,b=r(p.subarray(m/2,h));if(!Gg(b,p.subarray(h,h+32)))throw Error("invalid secretKey: hash check failed");let[y,S,x,_]=a.decode(p),A=t.decrypt(d,y),O=o.create().update(A).update(x).digest(),L=O.subarray(0,32),z=t.encrypt(S,A,O.subarray(32,64)),K=Gg(d,z),P=n.create({dkLen:32}).update(_).update(d).digest();return Pt(A,z,!K?L:P),K?L:P}}}function Kce(e,t,r){return Vn.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var nr=256,Oo=3329,Bce=3303,jce=17,Hd,Zce,Gs,Uce,HA,Mce=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+Oo/2)/Oo,decode:(r)=>r*Oo+t>>>e}},Jd=(e)=>Uce(e,Mce(e)),Jce=(e)=>{let{K:t,PRF:r,XOF:o,HASH512:n,ETA1:i,ETA2:s,du:a,dv:l}=e,u=Jd(1),d=Jd(l),p=Jd(a),m=Ws("publicKey",Qg(Jd(12),t),32),h=Qg(Jd(12),t),b=Ws("ciphertext",Qg(p,t),d),y=Ws("seed",32,32);return{secretCoder:h,lengths:{secretKey:h.bytesLen,publicKey:m.bytesLen,cipherText:b.bytesLen},keygen:(S)=>{Re(S,32,"seed");let x=new Uint8Array(33);x.set(S),x[32]=t;let _=n(x),[A,O]=y.decode(_),L=[],z=[];for(let W=0;W<t;W++)L.push(Gs.encode(Kd(r,O,W,i)));let K=o(A);for(let W=0;W<t;W++){let ee=Gs.encode(Kd(r,O,t+W,i));for(let j=0;j<t;j++){let T=n6(K.get(j,W));Qs(ee,Xg(T,L[j]))}z.push(ee)}K.clean();let P={publicKey:m.encode([z,A]),secretKey:h.encode(L)};return Pt(A,O,L,z,x,_),P},encrypt:(S,x,_)=>{let[A,O]=m.decode(S),L=[];for(let j=0;j<t;j++)L.push(Gs.encode(Kd(r,_,j,i)));let z=o(O),K=new Uint16Array(nr),P=[];for(let j=0;j<t;j++){let T=Kd(r,_,t+j,s),B=new Uint16Array(nr);for(let I=0;I<t;I++){let R=n6(z.get(j,I));Qs(B,Xg(R,L[I]))}Qs(T,Gs.decode(B)),P.push(T),Qs(K,Xg(A[j],L[j])),Pt(B)}z.clean();let W=Kd(r,_,2*t,s);Qs(W,Gs.decode(K));let ee=u.decode(x);return Qs(ee,W),Pt(A,L,K,W),b.encode([P,ee])},decrypt:(S,x)=>{let[_,A]=b.decode(S),O=h.decode(x),L=new Uint16Array(nr);for(let z=0;z<t;z++)Qs(L,Xg(O[z],Gs.encode(_[z])));return qce(A,Gs.decode(L)),Pt(L,O,_),u.encode(A)}}},WA,w1e,Vd,o6;var i6=v(()=>{Wg();Zr();r6();Yg();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */({mod:Hd,nttZetas:Zce,NTT:Gs,bitsCoder:Uce}=e6({N:nr,Q:Oo,F:Bce,ROOT_OF_UNITY:jce,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0})),HA={512:{N:nr,Q:Oo,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:nr,Q:Oo,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:nr,Q:Oo,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}};WA={HASH256:Vs,HASH512:KU,KDF:Vn,XOF:t6,PRF:Kce},w1e=VA({...WA,...HA[512]}),Vd=VA({...WA,...HA[768]}),o6=VA({...WA,...HA[1024]})});function Hce(e,t=!1){let{lengths:r,keygen:o}=e;if(t){let i=e.Point.Fn;if(!i)throw Error("No Point.Fn");o=(s=Wn(r.seed))=>{Re(s,r.seed,"seed");let a=i.isLE?Oi(s):$i(s),l=i.toBytes(i.create(a));return{secretKey:l,publicKey:e.getPublicKey(l)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:o,getPublicKey:(n)=>e.getPublicKey(n)}}function GA(e,t=!1){let r=Hce(e,t);if(!e.getSharedSecret)throw Error("wrong curve");return{lengths:{...r.lengths,msg:r.lengths.seed,cipherText:r.lengths.publicKey},keygen:r.keygen,getPublicKey:r.getPublicKey,encapsulate(o,n=Wn(e.lengths.seed)){let i=this.keygen(n).secretKey,s=this.decapsulate(o,i),a=e.getPublicKey(i);return Pt(i),{sharedSecret:s,cipherText:a}},decapsulate(o,n){let i=e.getSharedSecret(n,o);return e.lengths.publicKeyHasPrefix?i.subarray(1):i}}}function Wd(e,t){return Ws(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function QA(e){return(t,r)=>e(t,{dkLen:r})}function Vce(e,t,...r){let o=Wd(r,"seed"),n=Wd(r,"publicKey");if(e===void 0)e=o.bytesLen;Zt(e);function i(s){Re(s,e);let a=o.decode(t(s,o.bytesLen)),l=r.map((p,m)=>p.keygen(a[m])),u=l.map((p)=>p.secretKey),d=l.map((p)=>p.publicKey);return{secretKey:u,publicKey:d}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Wn(e)){let{publicKey:a,secretKey:l}=i(s),u=n.encode(a);return Pt(a),Pt(l),{secretKey:s,publicKey:u}},expandDecapsulationKey:i,realSeedLen:e}}function ey(e,t,r,o,...n){let i=Vce(e,r,...n),s=Wd(n,"cipherText"),a=Wd(n,"publicKey"),l=Wd(n,"msg");if(t===void 0)t=l.bytesLen;return Zt(t),{lengths:{...i.info.lengths,msg:t,msgRand:l.bytesLen,cipherText:s.bytesLen},getPublicKey:i.getPublicKey,keygen:i.keygen,encapsulate(u,d=Wn(l.bytesLen)){let p=a.decode(u),m=l.decode(d),h=n.map((x,_)=>x.encapsulate(p[_],m[_])),b=h.map((x)=>x.sharedSecret),y=h.map((x)=>x.cipherText),S={sharedSecret:o(p,y,b),cipherText:s.encode(y)};return Pt(b,y),S},decapsulate(u,d){let p=s.decode(u),{publicKey:m,secretKey:h}=i.expandDecapsulationKey(d),b=n.map((y,S)=>y.decapsulate(p[S],h[S]));return o(m,p,b)}}}function s6(e,t,r,o,n){return en(o),en(n),ey(32,32,QA(o),(i,s,a)=>n(It(a[0],a[1],s[1],i[1],Ci(e))),t,r)}function Wce(e,t,r,o,n){return en(o),en(n),ey(32,32,QA(o),(i,s,a)=>{let l=It(a[0],a[1],s[0],i[0],s[1],i[1],Ci(e)),u=32,d=It(Ci("hybrid_prk"),l),p=DU(n,d),m=It(Uc(32,2),Ci("shared_secret"),Ci("")),h=LU(n,p,m,32);return Pt(p,m,d,l),h},t,r)}function Qce(e,t,r,o){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function i(s){let a;for(let d=0,p=t;;d=p,p+=t){if(p>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(d,p),!0),n.isValidNot0(a))break}let l=n.toBytes(n.create(a)),u=e.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}return{lengths:{secretKey:t,publicKey:r,seed:o,msg:o,cipherText:r},keygen(s=Wn(o)){return Re(s,o,"seed"),i(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Wn(o)){Re(a,o,"rand");let{secretKey:l}=i(a),u=this.decapsulate(s,l),d=e.getPublicKey(l,!1);return Pt(l),{sharedSecret:u,cipherText:d}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function Yce(e,t,r,o){let{secretKey:n,publicKeyUncompressed:i}=r.lengths;if(!n||!i)throw Error("wrong curve");let s=Qce(r,n,i,o),a=64,l=a+o;return ey(32,32,(u)=>{Re(u,32);let d=Vn(u,{dkLen:l}),p=d.subarray(0,a),m=d.subarray(a,l);return It(p,m)},(u,d,p)=>Vs(It(p[0],p[1],d[1],u[1],Ci(e))),t,s)}var C1e,P1e,a6,z1e,Gce,Xce,ty,c6;var l6=v(()=>{CU();zU();Mc();BU();ZA();Wg();Zr();i6();Yg();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */C1e=s6("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",Vd,GA(UA,!0),Vn,Vs),P1e=s6("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",o6,GA(PU,!0),Vn,Vs);a6=GA(OU),z1e=Wce("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",Vd,a6,Vn,Hg),Gce=(()=>ey(32,32,QA(Vn),(e,t,r)=>Vs(It(r[0],r[1],t[1],e[1],Ci("\\.//^\\"))),Vd,a6))();Xce=(()=>Yce("MLKEM768-P256",Vd,UA,128))(),ty=Gce,c6=Xce});function Co(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function oy(e){if(typeof e==="bigint"){if(!ry(e))throw RangeError("positive bigint expected, got "+e)}else XA(e);return e}function Gn(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 Gd(e){let t=oy(e).toString(16);return t.length&1?"0"+t:t}function u6(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?ny:BigInt("0x"+e)}function Ys(e){return u6(xg(e))}function Sn(e){return u6(xg(Li(Ft(e)).reverse()))}function iy(e,t){if(vt(t),t===0)throw RangeError("zero length");e=oy(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return _d(r.padStart(t*2,"0"))}function Qd(e,t){return iy(e,t).reverse()}function d6(e,t){if(e=et(e),t=et(t),e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function Li(e){return Uint8Array.from(et(e))}function sy(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function ele(e,t,r){return ry(e)&&ry(t)&&ry(r)&&t<=e&&e<r}function Po(e,t,r,o){if(!ele(t,r,o))throw RangeError("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Qc(e){if(e<ny)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>ny;e>>=YA,t+=1);return t}function p6(e,t,r){if(vt(e,"hashLen"),vt(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...S)=>r(u,Vt(l,...S)),h=(S=n)=>{if(u=m(i,S),l=m(),S.length===0)return;u=m(s,S),l=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){l=m();let _=l.slice();x.push(_),S+=l.length}return Vt(...x)};return(S,x)=>{p(),h(S);let _=void 0;while((_=x(b()))===void 0)h();return p(),_}}function rn(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw TypeError(`param "${i}" is invalid: expected own property`);let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}var et=(e,t,r)=>Ft(e,t,r),XA,Hc,Vt=(...e)=>Gk(...e),Vc=(e)=>_d(e),Wc,Gc=(e)=>Eo(e),ny,YA,ry=(e)=>typeof e==="bigint"&&ny<=e,Yd=(e)=>(YA<<BigInt(e))-YA,eR=()=>{throw Error("not implemented")};var Bi=v(()=>{Qr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */XA=vt,Hc=xg,Wc=Hk,ny=BigInt(0),YA=BigInt(1)});function it(e,t){if(t<=Wt)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Wt?r:t+r}function nn(e,t,r){if(t<Wt)throw Error("pow2: expected non-negative exponent, got "+t);let o=e;while(t-- >Wt)o*=o,o%=r;return o}function f6(e,t){if(e===Wt)throw Error("invert: expected non-zero number");if(t<=Wt)throw Error("invert: expected positive modulus, got "+t);let r=it(e,t),o=t,n=Wt,i=yt,s=yt,a=Wt;while(r!==Wt){let u=o/r,d=o-r*u,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==yt)throw Error("invert: does not exist");return it(n,t)}function tR(e,t,r){let o=e;if(!o.eql(o.sqr(t),r))throw Error("Cannot find square root")}function w6(e,t){let r=e,o=(r.ORDER+yt)/y6,n=r.pow(t,o);return tR(r,n,t),n}function nle(e,t){let r=e,o=(r.ORDER-b6)/S6,n=r.mul(t,Xs),i=r.pow(n,o),s=r.mul(t,i),a=r.mul(r.mul(s,Xs),i),l=r.mul(s,r.sub(a,r.ONE));return tR(r,l,t),l}function ole(e){let t=ay(e),r=x6(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+tle)/v6;return(a,l)=>{let u=a,d=u.pow(l,s),p=u.mul(d,o),m=u.mul(d,n),h=u.mul(d,i),b=u.eql(u.sqr(p),l),y=u.eql(u.sqr(m),l);d=u.cmov(d,p,b),p=u.cmov(h,m,y);let S=u.eql(u.sqr(p),l),x=u.cmov(d,p,S);return tR(u,x,l),x}}function x6(e){if(e<g6)throw Error("sqrt is not defined for small field");let t=e-yt,r=0;while(t%Xs===Wt)t/=Xs,r++;let o=Xs,n=ay(e);while(m6(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return w6;let i=n.pow(o,t),s=(t+yt)/Xs;return function(l,u){let d=l;if(d.is0(u))return u;if(m6(d,u)!==1)throw Error("Cannot find square root");let p=r,m=d.mul(d.ONE,i),h=d.pow(u,t),b=d.pow(u,s);while(!d.eql(h,d.ONE)){if(d.is0(h))return d.ZERO;let y=1,S=d.sqr(h);while(!d.eql(S,d.ONE))if(y++,S=d.sqr(S),y===p)throw Error("Cannot find square root");let x=yt<<BigInt(p-y-1),_=d.pow(m,x);p=y,m=d.sqr(_),h=d.mul(h,m),b=d.mul(b,_)}return b}}function ile(e){if(e%y6===g6)return w6;if(e%S6===b6)return nle;if(e%v6===rle)return ole(e);return x6(e)}function rR(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=sle.reduce((o,n)=>(o[n]="function",o),t);if(rn(e,r),Gn(e.BYTES,"BYTES"),Gn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=yt)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function ale(e,t,r){let o=e;if(r<Wt)throw Error("invalid exponent, negatives unsupported");if(r===Wt)return o.ONE;if(r===yt)return t;let n=o.ONE,i=t;while(r>Wt){if(r&yt)n=o.mul(n,i);i=o.sqr(i),r>>=yt}return n}function Xd(e,t,r=!1){let o=e,n=Array(t.length).fill(r?o.ZERO:void 0),i=t.reduce((a,l,u)=>{if(o.is0(l))return a;return n[u]=a,o.mul(a,l)},o.ONE),s=o.inv(i);return t.reduceRight((a,l,u)=>{if(o.is0(l))return a;return n[u]=o.mul(a,n[u]),o.mul(a,l)},s),n}function m6(e,t){let r=e,o=(r.ORDER-yt)/Xs,n=r.pow(t,o),i=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function cle(e,t){if(t!==void 0)XA(t);if(e<=Wt)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=Qc(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let o=t!==void 0?t:r,n=Math.ceil(o/8);return{nBitLength:o,nByteLength:n}}class nR{ORDER;BITS;BYTES;isLE;ZERO=Wt;ONE=yt;_lengths;_mod;constructor(e,t={}){if(e<=yt)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=cle(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,Object.freeze(this)}create(e){return it(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Wt<=e&&e<this.ORDER}is0(e){return e===Wt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yt)===yt}neg(e){return it(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return it(e*e,this.ORDER)}add(e,t){return it(e+t,this.ORDER)}sub(e,t){return it(e-t,this.ORDER)}mul(e,t){return it(e*t,this.ORDER)}pow(e,t){return ale(this,e,t)}div(e,t){return it(e*f6(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 f6(e,this.ORDER)}sqrt(e){let t=h6.get(this);if(!t)h6.set(this,t=ile(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?Qd(e,this.BYTES):iy(e,this.BYTES)}fromBytes(e,t=!1){et(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?Sn(e):Ys(e);if(s)a=it(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Xd(this,e)}cmov(e,t,r){return Co(r,"condition"),r?t:e}}function ay(e,t={}){return new nR(e,t)}function _6(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=yt)throw Error("field order must be greater than 1");let t=Qc(e-yt);return Math.ceil(t/8)}function oR(e){let t=_6(e);return t+Math.ceil(t/2)}function E6(e,t,r=!1){et(e);let o=e.length,n=_6(t),i=Math.max(oR(t),16);if(o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?Sn(e):Ys(e),a=it(s,t-yt)+yt;return r?Qd(a,n):iy(a,n)}var Wt,yt,Xs,g6,y6,b6,tle,S6,rle,v6,zo=(e,t)=>(it(e,t)&yt)===yt,sle,h6;var ep=v(()=>{Bi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Wt=BigInt(0),yt=BigInt(1),Xs=BigInt(2),g6=BigInt(3),y6=BigInt(4),b6=BigInt(5),tle=BigInt(7),S6=BigInt(8),rle=BigInt(9),v6=BigInt(16);sle=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];h6=new WeakMap;Object.freeze(nR.prototype)});function tp(e,t){let r=t.negate();return e?r:t}function ta(e,t){let r=Xd(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function R6(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function iR(e,t){R6(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=Yd(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function I6(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=ea;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function aR(e){return T6.get(e)||1}function k6(e){if(e!==Yc)throw Error("invalid wNAF")}class rp{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>Yc){if(t&ea)r=r.add(o);o=o.double(),t>>=ea}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=iR(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=iR(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=I6(r,s,i);if(r=a,u)n=n.add(tp(p,t[m]));else o=o.add(tp(d,t[l]))}return k6(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=iR(e,this.bits);for(let i=0;i<n.windows;i++){if(r===Yc)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=I6(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return k6(r),o}getPrecomputes(e,t,r){let o=sR.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);sR.set(t,o)}}return o}cached(e,t,r){let o=aR(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=aR(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){R6(t,this.bits),T6.set(e,t),sR.delete(e)}hasCache(e){return aR(e)!==1}}function $6(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>Yc||o>Yc){if(r&ea)i=i.add(n);if(o&ea)s=s.add(n);n=n.double(),r>>=ea,o>>=ea}return{p1:i,p2:s}}function A6(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return rR(t),t}else return ay(e,{isLE:r})}function cy(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>Yc))throw Error(`CURVE.${l} must be positive bigint`)}let n=A6(t.p,r.Fp,o),i=A6(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function np(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var Yc,ea,sR,T6;var ly=v(()=>{Bi();ep();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Yc=BigInt(0),ea=BigInt(1);sR=new WeakMap,T6=new WeakMap});function op(e,t){if(Gn(e),Gn(t),t<0||t>4)throw Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let o=t-1;o>=0;o--)r[o]=e&255,e>>>=8;return new Uint8Array(r)}function lle(e,t){let r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e[o]^t[o];return r}function ule(e){if(!Wc(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?sy(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function cR(e,t,r,o){if(et(e),Gn(r),t=ule(t),t.length>255)t=o(Vt(sy("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:i}=o,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=Vt(t,op(t.length,1)),l=new Uint8Array(i),u=op(r,2),d=Array(s),p=o(Vt(l,e,u,op(0,1),a));d[0]=o(Vt(p,op(1,1),a));for(let h=1;h<s;h++){let b=[lle(p,d[h-1]),op(h+1,1),a];d[h]=o(Vt(...b))}return Vt(...d).slice(0,r)}var O6="HashToScalar-";var C6=v(()=>{Bi()});function dle(e,t,r){Po("scalar",e,Qn,r);let[[o,n],[i,s]]=t,a=P6(s*e,r),l=P6(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<Qn,m=d<Qn;if(p)u=-u;if(m)d=-d;let h=Yd(Math.ceil(Qc(r)/2))+ji;if(u<Qn||u>=h||d<Qn||d>=h)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:p,k1:u,k2neg:m,k2:d}}function uR(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function lR(e,t){rn(e);let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(Co(r.lowS,"lowS"),Co(r.prehash,"prehash"),r.format!==void 0)uR(r.format);return r}function D6(e,t={}){let r=cy("weierstrass",e,t),o=r.Fp,n=r.Fn,i=r.CURVE,{h:s,n:a}=i;rn(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let d=B6(o,n);function p(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function m(j,T,B){if(u&&T.is0())return Uint8Array.of(0);let{x:I,y:R}=T.toAffine(),k=o.toBytes(I);if(Co(B,"isCompressed"),B){p();let q=!o.isOdd(R);return Vt(L6(q),k)}else return Vt(Uint8Array.of(4),k,o.toBytes(R))}function h(j){et(j,void 0,"Point");let{publicKey:T,publicKeyUncompressed:B}=d,I=j.length,R=j[0],k=j.subarray(1);if(u&&I===1&&R===0)return{x:o.ZERO,y:o.ZERO};if(I===T&&(R===2||R===3)){let q=o.fromBytes(k);if(!o.isValid(q))throw Error("bad point: is not on curve, wrong x");let N=S(q),H;try{H=o.sqrt(N)}catch(ae){let me=ae instanceof Error?": "+ae.message:"";throw Error("bad point: is not on curve, sqrt error"+me)}p();let G=o.isOdd(H);if((R&1)===1!==G)H=o.neg(H);return{x:q,y:H}}else if(I===B&&R===4){let q=o.BYTES,N=o.fromBytes(k.subarray(0,q)),H=o.fromBytes(k.subarray(q,q*2));if(!x(N,H))throw Error("bad point: is not on curve");return{x:N,y:H}}else throw Error(`bad point: got length ${I}, expected compressed=${T} or uncompressed=${B}`)}let b=t.toBytes===void 0?m:t.toBytes,y=t.fromBytes===void 0?h:t.fromBytes;function S(j){let T=o.sqr(j),B=o.mul(T,j);return o.add(o.add(B,o.mul(j,i.a)),i.b)}function x(j,T){let B=o.sqr(T),I=S(j);return o.eql(B,I)}if(!x(i.Gx,i.Gy))throw Error("bad curve params: generator point");let _=o.mul(o.pow(i.a,uy),ple),A=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(_,A)))throw Error("bad curve params: a or b");function O(j,T,B=!1){if(!o.isValid(T)||B&&o.is0(T))throw Error(`bad point coordinate ${j}`);return T}function L(j){if(!(j instanceof P))throw Error("Weierstrass Point expected")}function z(j){if(!l||!l.basises)throw Error("no endo");return dle(j,l.basises,n.ORDER)}function K(j,T,B,I,R){return B=new P(o.mul(B.X,j),B.Y,B.Z),T=tp(I,T),B=tp(R,B),T.add(B)}class P{static BASE=new P(i.Gx,i.Gy,o.ONE);static ZERO=new P(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(j,T,B){this.X=O("x",j),this.Y=O("y",T,!0),this.Z=O("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(j){let{x:T,y:B}=j||{};if(!j||!o.isValid(T)||!o.isValid(B))throw Error("invalid affine point");if(j instanceof P)throw Error("projective point not allowed");if(o.is0(T)&&o.is0(B))return P.ZERO;return new P(T,B,o.ONE)}static fromBytes(j){let T=P.fromAffine(y(et(j,void 0,"point")));return T.assertValidity(),T}static fromHex(j){return P.fromBytes(Vc(j))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,T=!0){if(ee.createCache(this,j),!T)this.multiply(uy);return this}assertValidity(){let j=this;if(j.is0()){if(t.allowInfinityPoint&&o.is0(j.X)&&o.eql(j.Y,o.ONE)&&o.is0(j.Z))return;throw Error("bad point: ZERO")}let{x:T,y:B}=j.toAffine();if(!o.isValid(T)||!o.isValid(B))throw Error("bad point: x or y not field elements");if(!x(T,B))throw Error("bad point: equation left != right");if(!j.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:j}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(j)}equals(j){L(j);let{X:T,Y:B,Z:I}=this,{X:R,Y:k,Z:q}=j,N=o.eql(o.mul(T,q),o.mul(R,I)),H=o.eql(o.mul(B,q),o.mul(k,I));return N&&H}negate(){return new P(this.X,o.neg(this.Y),this.Z)}double(){let{a:j,b:T}=i,B=o.mul(T,uy),{X:I,Y:R,Z:k}=this,q=o.ZERO,N=o.ZERO,H=o.ZERO,G=o.mul(I,I),re=o.mul(R,R),ae=o.mul(k,k),me=o.mul(I,R);return me=o.add(me,me),H=o.mul(I,k),H=o.add(H,H),q=o.mul(j,H),N=o.mul(B,ae),N=o.add(q,N),q=o.sub(re,N),N=o.add(re,N),N=o.mul(q,N),q=o.mul(me,q),H=o.mul(B,H),ae=o.mul(j,ae),me=o.sub(G,ae),me=o.mul(j,me),me=o.add(me,H),H=o.add(G,G),G=o.add(H,G),G=o.add(G,ae),G=o.mul(G,me),N=o.add(N,G),ae=o.mul(R,k),ae=o.add(ae,ae),G=o.mul(ae,me),q=o.sub(q,G),H=o.mul(ae,re),H=o.add(H,H),H=o.add(H,H),new P(q,N,H)}add(j){L(j);let{X:T,Y:B,Z:I}=this,{X:R,Y:k,Z:q}=j,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=i.a,ae=o.mul(i.b,uy),me=o.mul(T,R),be=o.mul(B,k),xe=o.mul(I,q),Ae=o.add(T,B),ke=o.add(R,k);Ae=o.mul(Ae,ke),ke=o.add(me,be),Ae=o.sub(Ae,ke),ke=o.add(T,I);let _e=o.add(R,q);return ke=o.mul(ke,_e),_e=o.add(me,xe),ke=o.sub(ke,_e),_e=o.add(B,I),N=o.add(k,q),_e=o.mul(_e,N),N=o.add(be,xe),_e=o.sub(_e,N),G=o.mul(re,ke),N=o.mul(ae,xe),G=o.add(N,G),N=o.sub(be,G),G=o.add(be,G),H=o.mul(N,G),be=o.add(me,me),be=o.add(be,me),xe=o.mul(re,xe),ke=o.mul(ae,ke),be=o.add(be,xe),xe=o.sub(me,xe),xe=o.mul(re,xe),ke=o.add(ke,xe),me=o.mul(be,ke),H=o.add(H,me),me=o.mul(_e,ke),N=o.mul(Ae,N),N=o.sub(N,me),me=o.mul(Ae,be),G=o.mul(_e,G),G=o.add(G,me),new P(N,H,G)}subtract(j){return L(j),this.add(j.negate())}is0(){return this.equals(P.ZERO)}multiply(j){let{endo:T}=t;if(!n.isValidNot0(j))throw RangeError("invalid scalar: out of range");let B,I,R=(k)=>ee.cached(this,k,(q)=>ta(P,q));if(T){let{k1neg:k,k1:q,k2neg:N,k2:H}=z(j),{p:G,f:re}=R(q),{p:ae,f:me}=R(H);I=re.add(me),B=K(T.beta,G,ae,k,N)}else{let{p:k,f:q}=R(j);B=k,I=q}return ta(P,[B,I])[0]}multiplyUnsafe(j){let{endo:T}=t,B=this,I=j;if(!n.isValid(I))throw RangeError("invalid scalar: out of range");if(I===Qn||B.is0())return P.ZERO;if(I===ji)return B;if(ee.hasCache(this))return this.multiply(I);if(T){let{k1neg:R,k1:k,k2neg:q,k2:N}=z(I),{p1:H,p2:G}=$6(P,B,k,N);return K(T.beta,H,G,R,q)}else return ee.unsafe(B,I)}toAffine(j){let T=this,B=j,{X:I,Y:R,Z:k}=T;if(o.eql(k,o.ONE))return{x:I,y:R};let q=T.is0();if(B==null)B=q?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(R,B),G=o.mul(k,B);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){let{isTorsionFree:j}=t;if(s===ji)return!0;if(j)return j(P,this);return ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:j}=t;if(s===ji)return this;if(j)return j(P,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===ji)return this.is0();return this.clearCofactor().is0()}toBytes(j=!0){return Co(j,"isCompressed"),this.assertValidity(),b(P,this,j)}toHex(j=!0){return Hc(this.toBytes(j))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=n.BITS,ee=new rp(P,t.endo?Math.ceil(W/2):W);if(W>=8)P.BASE.precompute(8);return Object.freeze(P.prototype),Object.freeze(P),P}function L6(e){return Uint8Array.of(e?2:3)}function B6(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function fle(e,t={}){let{Fn:r}=e,o=t.randomBytes===void 0?Gc:t.randomBytes,n=Object.assign(B6(e.Fp,r),{seed:Math.max(oR(r.ORDER),16)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h){return h=h===void 0?o(n.seed):h,E6(et(h,n.seed,"seed"),r.ORDER)}function l(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n,x=r._lengths;if(!Wc(h))return;let _=et(h,void 0,"key").length,A=_===y||_===S,O=_===b||!!x?.includes(_);if(A&&O)return;return A}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=np(a,l);return Object.freeze(p),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function j6(e,t,r={}){let o=t;_o(o),rn(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?Gc:r.randomBytes,i=r.hmac===void 0?(R,k)=>Fn(o,R,k):r.hmac,{Fp:s,Fn:a}=e,{ORDER:l,BITS:u}=a,{keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:b}=fle(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},S=l*N6+ji<s.ORDER;function x(R){let k=l>>ji;return R>k}function _(R,k){if(!a.isValidNot0(k))throw Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return k}function A(){if(S)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(R,k){uR(k);let q=b.signature,N=k==="compact"?q:k==="recovered"?q+1:void 0;return et(R,N)}class L{r;s;recovery;constructor(R,k,q){if(this.r=_("r",R),this.s=_("s",k),q!=null){if(A(),![0,1,2,3].includes(q))throw Error("invalid recovery id");this.recovery=q}Object.freeze(this)}static fromBytes(R,k=y.format){O(R,k);let q;if(k==="der"){let{r:re,s:ae}=vn.toSig(et(R));return new L(re,ae)}if(k==="recovered")q=R[0],k="compact",R=R.subarray(1);let N=b.signature/2,H=R.subarray(0,N),G=R.subarray(N,N*2);return new L(a.fromBytes(H),a.fromBytes(G),q)}static fromHex(R,k){return this.fromBytes(Vc(R),k)}assertRecovery(){let{recovery:R}=this;if(R==null)throw Error("invalid recovery id: must be present");return R}addRecoveryBit(R){return new L(this.r,this.s,R)}recoverPublicKey(R){let{r:k,s:q}=this,N=this.assertRecovery(),H=N===2||N===3?k+l:k;if(!s.isValid(H))throw Error("invalid recovery id: sig.r+curve.n != R.x");let G=s.toBytes(H),re=e.fromBytes(Vt(L6((N&1)===0),G)),ae=a.inv(H),me=K(et(R,void 0,"msgHash")),be=a.create(-me*ae),xe=a.create(q*ae),Ae=e.BASE.multiplyUnsafe(be).add(re.multiplyUnsafe(xe));if(Ae.is0())throw Error("invalid recovery: point at infinify");return Ae.assertValidity(),Ae}hasHighS(){return x(this.s)}toBytes(R=y.format){if(uR(R),R==="der")return Vc(vn.hexFromSig(this));let{r:k,s:q}=this,N=a.toBytes(k),H=a.toBytes(q);if(R==="recovered")return A(),Vt(Uint8Array.of(this.assertRecovery()),N,H);return Vt(N,H)}toHex(R){return Hc(this.toBytes(R))}}Object.freeze(L.prototype),Object.freeze(L);let z=r.bits2int===void 0?function(k){if(k.length>8192)throw Error("input is too large");let q=Ys(k),N=k.length*8-u;return N>0?q>>BigInt(N):q}:r.bits2int,K=r.bits2int_modN===void 0?function(k){return a.create(z(k))}:r.bits2int_modN,P=Yd(u);function W(R){return Po("num < 2^"+u,R,Qn,P),a.toBytes(R)}function ee(R,k){return et(R,void 0,"message"),k?et(o(R),void 0,"prehashed message"):R}function j(R,k,q){let{lowS:N,prehash:H,extraEntropy:G}=lR(q,y);R=ee(R,H);let re=K(R),ae=a.fromBytes(k);if(!a.isValidNot0(ae))throw Error("invalid private key");let me=[W(ae),W(re)];if(G!=null&&G!==!1){let ke=G===!0?n(b.secretKey):G;me.push(et(ke,void 0,"extraEntropy"))}let be=Vt(...me),xe=re;function Ae(ke){let _e=z(ke);if(!a.isValidNot0(_e))return;let Ue=a.inv(_e),De=e.BASE.multiply(_e).toAffine(),Qe=a.create(De.x);if(Qe===Qn)return;let St=a.create(Ue*a.create(xe+Qe*ae));if(St===Qn)return;let Rt=(De.x===Qe?0:2)|Number(De.y&ji),Dt=St;if(N&&x(St))Dt=a.neg(St),Rt^=1;return new L(Qe,Dt,S?void 0:Rt)}return{seed:be,k2sig:Ae}}function T(R,k,q={}){let{seed:N,k2sig:H}=j(R,k,q);return p6(o.outputLen,a.BYTES,i)(N,H).toBytes(q.format)}function B(R,k,q,N={}){let{lowS:H,prehash:G,format:re}=lR(N,y);if(q=et(q,void 0,"publicKey"),k=ee(k,G),!Wc(R)){let ae=R instanceof L?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ae)}O(R,re);try{let ae=L.fromBytes(R,re),me=e.fromBytes(q);if(H&&ae.hasHighS())return!1;let{r:be,s:xe}=ae,Ae=K(k),ke=a.inv(xe),_e=a.create(Ae*ke),Ue=a.create(be*ke),De=e.BASE.multiplyUnsafe(_e).add(me.multiplyUnsafe(Ue));if(De.is0())return!1;return a.create(De.x)===be}catch(ae){return!1}}function I(R,k,q={}){let{prehash:N}=lR(q,y);return k=ee(k,N),L.fromBytes(R,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:b,Point:e,sign:T,verify:B,recoverPublicKey:I,Signature:L,hash:o})}var P6=(e,t)=>(e+(e>=0?t:-t)/N6)/t,z6,vn,Qn,ji,N6,uy,ple;var Z6=v(()=>{Ed();Qr();Bi();ly();ep();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */z6=class z6 extends Error{constructor(e=""){super(e)}};vn={Err:z6,_tlv:{encode:(e,t)=>{let{Err:r}=vn;if(Gn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!=="string")throw TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=Gd(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?Gd(n.length/2|128):"";return Gd(e)+i+n+t},decode(e,t){let{Err:r}=vn;t=et(t,void 0,"DER data");let o=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=vn;if(oy(e),e<Qn)throw new t("integer: negative integers are not allowed");let r=Gd(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}=vn;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 Ys(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=vn,n=et(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=vn,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};Object.freeze(vn._tlv);Object.freeze(vn._int);Object.freeze(vn);Qn=BigInt(0),ji=BigInt(1),N6=BigInt(2),uy=BigInt(3),ple=BigInt(4)});var mle,hle,Xc;var U6=v(()=>{Nc();Z6();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */mle=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),hle=D6(mle),Xc=j6(hle,wt)});function yle(e,t,r,o){let n=e.sqr(r),i=e.sqr(o),s=e.add(e.mul(t.a,n),i),a=e.add(e.ONE,e.mul(t.d,e.mul(n,i)));return e.eql(s,a)}function M6(e,t={}){let r=t,o=cy("edwards",e,r,r.FpFnLE),{Fp:n,Fn:i}=o,s=o.CURVE,{h:a}=s;rn(r,{},{uvRatio:"function"});let l=dR<<BigInt(i.BYTES*8)-Ar,u=(y)=>n.create(y),d=r.uvRatio===void 0?(y,S)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,S))}}catch(x){return{isValid:!1,value:Zi}}}:r.uvRatio;if(!yle(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function p(y,S,x=!1){let _=x?Ar:Zi;return Po("coordinate "+y,S,_,l),S}function m(y){if(!(y instanceof h))throw Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,Ar,u(s.Gx*s.Gy));static ZERO=new h(Zi,Ar,Ar,Zi);static Fp=n;static Fn=i;X;Y;Z;T;constructor(y,S,x,_){this.X=p("x",y),this.Y=p("y",S),this.Z=p("z",x,!0),this.T=p("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw Error("extended point not allowed");let{x:S,y:x}=y||{};return p("x",S),p("y",x),new h(S,x,Ar,u(S*x))}static fromBytes(y,S=!1){let x=n.BYTES,{a:_,d:A}=s;y=Li(et(y,x,"point")),Co(S,"zip215");let O=Li(y),L=y[x-1];O[x-1]=L&-129;let z=Sn(O),K=S?l:n.ORDER;Po("point.y",z,Zi,K);let P=u(z*z),W=u(P-Ar),ee=u(A*P-_),{isValid:j,value:T}=d(W,ee);if(!j)throw Error("bad point: invalid y coordinate");let B=(T&Ar)===Ar,I=(L&128)!==0;if(!S&&T===Zi&&I)throw Error("bad point: x=0 and x_0=1");if(I!==B)T=u(-T);return h.fromAffine({x:T,y:z})}static fromHex(y,S=!1){return h.fromBytes(Vc(y),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,S=!0){if(b.createCache(this,y),!S)this.multiply(dR);return this}assertValidity(){let y=this,{a:S,d:x}=s;if(y.is0())throw Error("bad point: ZERO");let{X:_,Y:A,Z:O,T:L}=y,z=u(_*_),K=u(A*A),P=u(O*O),W=u(P*P),ee=u(z*S),j=u(P*u(ee+K)),T=u(W+u(x*u(z*K)));if(j!==T)throw Error("bad point: equation left != right (1)");let B=u(_*A),I=u(O*L);if(B!==I)throw Error("bad point: equation left != right (2)")}equals(y){m(y);let{X:S,Y:x,Z:_}=this,{X:A,Y:O,Z:L}=y,z=u(S*L),K=u(A*_),P=u(x*L),W=u(O*_);return z===K&&P===W}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:y}=s,{X:S,Y:x,Z:_}=this,A=u(S*S),O=u(x*x),L=u(dR*u(_*_)),z=u(y*A),K=S+x,P=u(u(K*K)-A-O),W=z+O,ee=W-L,j=z-O,T=u(P*ee),B=u(W*j),I=u(P*j),R=u(ee*W);return new h(T,B,R,I)}add(y){m(y);let{a:S,d:x}=s,{X:_,Y:A,Z:O,T:L}=this,{X:z,Y:K,Z:P,T:W}=y,ee=u(_*z),j=u(A*K),T=u(L*x*W),B=u(O*P),I=u((_+A)*(z+K)-ee-j),R=B-T,k=B+T,q=u(j-S*ee),N=u(I*R),H=u(k*q),G=u(I*q),re=u(R*k);return new h(N,H,re,G)}subtract(y){return m(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:x}=b.cached(this,y,(_)=>ta(h,_));return ta(h,[S,x])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(y===Zi)return h.ZERO;if(this.is0()||y===Ar)return this;return b.unsafe(this,y,(S)=>ta(h,S))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(y){let S=this,x=y,{X:_,Y:A,Z:O}=S,L=S.is0();if(x==null)x=L?gle:n.inv(O);let z=u(_*x),K=u(A*x),P=n.mul(O,x);if(L)return{x:Zi,y:Ar};if(P!==Ar)throw Error("invZ was invalid");return{x:z,y:K}}clearCofactor(){if(a===Ar)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:y,y:S}=this.toAffine(),x=n.toBytes(S);return x[x.length-1]|=y&Ar?128:0,x}toHex(){return Hc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new rp(h,i.BITS);if(i.BITS>=8)h.BASE.precompute(8);return Object.freeze(h.prototype),Object.freeze(h),h}class pR{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){eR()}static fromHex(e){eR()}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 Hc(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}}var Zi,Ar,dR,gle;var q6=v(()=>{Bi();ly();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Zi=BigInt(0),Ar=BigInt(1),dR=BigInt(2),gle=BigInt(8)});function ble(e){return rn(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function F6(e){let t=ble(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s===void 0?Gc:s,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?dy**BigInt(254):dy**BigInt(447),b=a?BigInt(8)*dy**BigInt(251)-el:BigInt(4)*dy**BigInt(445)-el,y=h+b+el,S=(I)=>it(I,r),x=_(p);function _(I){return Qd(S(I),d)}function A(I){let R=Li(et(I,d,"uCoordinate"));if(a)R[31]&=127;return S(Sn(R))}function O(I){return Sn(n(Li(et(I,d,"scalar"))))}function L(I,R){let k=ee(A(R),O(I));if(k===ip)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,R,k){let q=S(I*(R-k));return R=S(R-q),k=S(k+q),{x_2:R,x_3:k}}function ee(I,R){Po("u",I,ip,r),Po("scalar",R,h,y);let k=R,q=I,N=el,H=ip,G=I,re=el,ae=ip;for(let be=BigInt(u-1);be>=ip;be--){let xe=k>>be&el;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let Ae=N+H,ke=S(Ae*Ae),_e=N-H,Ue=S(_e*_e),De=ke-Ue,Qe=G+re,St=G-re,Rt=S(St*Ae),Dt=S(Qe*_e),lt=Rt+Dt,Or=Rt-Dt;G=S(lt*lt),re=S(q*S(Or*Or)),N=S(ke*Ue),H=S(De*(ke+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return S(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(I)=>(I=I===void 0?l(d):I,et(I,j.seed,"seed"),I),B={randomSecretKey:T};return Object.freeze(j),Object.freeze(B),Object.freeze({keygen:np(T,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}var ip,el,dy;var J6=v(()=>{Bi();ly();ep();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ip=BigInt(0),el=BigInt(1),dy=BigInt(2)});function W6(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=na,a=e*e%i*e%i,l=nn(a,K6,i)*a%i,u=nn(l,No,i)*e%i,d=nn(u,wle,i)*u%i,p=nn(d,t,i)*d%i,m=nn(p,r,i)*p%i,h=nn(m,o,i)*m%i,b=nn(h,n,i)*h%i,y=nn(b,n,i)*h%i,S=nn(y,t,i)*d%i;return{pow_p_5_8:nn(S,K6,i)*e%i,b2:a}}function _le(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function yR(e,t){let r=na,o=it(t*t*t,r),n=it(o*o*t,r),i=W6(e*n).pow_p_5_8,s=it(e*o*i,r),a=it(t*s*s,r),l=s,u=it(s*fR,r),d=a===e,p=a===it(-e,r),m=a===it(-e*fR,r);if(d)s=l;if(p||m)s=u;if(zo(s,r))s=it(-s,r);return{isValid:d||p,value:s}}function V6(e){let{d:t}=gR,r=na,o=(x)=>Ui.create(x),n=o(mR*e*e),i=o((n+No)*kle),s=BigInt(-1),a=o((s-t*n)*o(n+t)),{isValid:l,value:u}=yR(i,a),d=o(u*e);if(!zo(d,r))d=o(-d);if(!l)u=d;if(!l)s=n;let p=o(s*(n-No)*Ale-a),m=u*u,h=o((u+u)*a),b=o(p*Ele),y=o(No-m),S=o(No+m);return new ra(o(h*S),o(y*b),o(b*S),o(h*y))}var Sle,No,K6,vle,wle,xle,na,gR,fR,ra,Ui,G6,py,mR,Ele,Ile,kle,Ale,H6=(e)=>yR(No,e),Rle,hR=(e)=>Ui.create(Sn(e)&Rle),br,Tle;var Q6=v(()=>{Nc();Qr();q6();C6();ep();J6();Bi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Sle=BigInt(0),No=BigInt(1),K6=BigInt(2),vle=BigInt(3),wle=BigInt(5),xle=BigInt(8),na=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gR=(()=>({p:na,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xle,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();fR=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");ra=M6(gR,{uvRatio:yR}),Ui=(()=>ra.Fp)(),G6=(()=>ra.Fn)(),py=(()=>{let e=na;return F6({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=W6(t);return it(nn(r,vle,e)*o,e)},adjustScalarBytes:_le})})(),mR=fR,Ele=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ile=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kle=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Ale=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Rle=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");br=class br extends pR{static BASE=(()=>new br(ra.BASE))();static ZERO=(()=>new br(ra.ZERO))();static Fp=(()=>Ui)();static Fn=(()=>G6)();constructor(e){super(e)}static fromAffine(e){return new br(ra.fromAffine(e))}assertSame(e){if(!(e instanceof br))throw Error("RistrettoPoint expected")}init(e){return new br(e)}static fromBytes(e){Ft(e,32);let{a:t,d:r}=gR,o=na,n=(A)=>Ui.create(A),i=hR(e);if(!d6(Ui.toBytes(i),e)||zo(i,o))throw Error("invalid ristretto255 encoding 1");let s=n(i*i),a=n(No+t*s),l=n(No-t*s),u=n(a*a),d=n(l*l),p=n(t*r*u-d),{isValid:m,value:h}=H6(n(p*d)),b=n(h*l),y=n(h*b*p),S=n((i+i)*b);if(zo(S,o))S=n(-S);let x=n(a*y),_=n(S*x);if(!m||zo(_,o)||x===Sle)throw Error("invalid ristretto255 encoding 2");return new br(new ra(S,x,No,_))}static fromHex(e){return br.fromBytes(_d(e))}toBytes(){let{X:e,Y:t,Z:r,T:o}=this.ep,n=na,i=(y)=>Ui.create(y),s=i(i(r+t)*i(r-t)),a=i(e*t),l=i(a*a),{value:u}=H6(i(s*l)),d=i(u*s),p=i(u*a),m=i(d*p*o),h;if(zo(o*m,n)){let y=i(t*mR),S=i(e*mR);e=y,t=S,h=i(d*Ile)}else h=p;if(zo(e*m,n))t=i(-t);let b=i((r-t)*h);if(zo(b,n))b=i(-b);return Ui.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:o,Y:n}=e.ep,i=(l)=>Ui.create(l),s=i(t*n)===i(r*o),a=i(r*n)===i(t*o);return s||a}is0(){return this.equals(br.ZERO)}};Object.freeze(br.BASE);Object.freeze(br.ZERO);Object.freeze(br.prototype);Object.freeze(br);Tle=Object.freeze({Point:br,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,o=cR(e,r,64,kg);return Tle.deriveToCurve(o)},hashToScalar(e,t={DST:O6}){let r=cR(e,t.DST,64,kg);return G6.create(Sn(r))},deriveToCurve(e){Ft(e,64);let t=hR(e.subarray(0,32)),r=V6(t),o=hR(e.subarray(32,64)),n=V6(o);return new br(r.add(n))}})});async function X6(e,t){if($le)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 fy(e,t){return await X6(async()=>{let r=bR(e)?e:await Cle(e),o=await crypto.subtle.importKey("raw",Ple(t),{name:"X25519"},Y6,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:o},r,256))},()=>{if(bR(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return py.scalarMult(e,t)})}async function sp(e){return await X6(async()=>fy(e,py.GuBytes),()=>{if(bR(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return py.scalarMultBase(e)})}async function Cle(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...Ole,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},Y6,["deriveBits"])}function bR(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function Ple(e){return e}var Y6=!1,$le=!1,Ole;var eM=v(()=>{Q6();Ole=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32])});class SR{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),Nle(oa(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=oa(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:oa(this.transcript)}}}function Nle(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function oa(e){let t=e.reduce((n,i)=>n+i.length,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function tl(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let o of t)r.enqueue(o)}}))}function my(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function vR(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function tM(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function rM(e,t){let r=e.getReader(),o=[],n=0;while(n<t){let{done:l,value:u}=await r.read();if(l)throw Error("stream ended before reading "+t.toString()+" bytes");o.push(u),n+=u.length}r.releaseLock();let i=oa(o),s=i.subarray(0,t),a=tl(e,i.subarray(t));return{data:s,rest:a}}var wR=()=>{};class Yn{args;body;constructor(e,t){this.args=e,this.body=t}}async function Dle(e){let t=await e.readLine();if(t===null)throw Error("invalid stanza");let r=t.split(" ");if(r.length<2||r.shift()!=="->")return{next:t};for(let i of r)if(i.length===0)throw Error("invalid stanza");let o=[];for(;;){let i=await e.readLine();if(i===null)throw Error("invalid stanza");let s=tr.decode(i);if(s.length>48)throw Error("invalid stanza");if(o.push(s),s.length<48)break}let n=oa(o);return{s:new Yn(r,n)}}async function nM(e){let t=new SR(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let o=[];for(;;){let{s:n,next:i}=await Dle(t);if(n!==void 0){o.push(n);continue}if(!i.startsWith("--- "))throw Error("invalid header");let s=tr.decode(i.slice(4)),{rest:a,transcript:l}=t.close(),u=l.slice(0,l.length-1-i.length+3);return{stanzas:o,headerNoMAC:u,MAC:s,headerSize:l.length,rest:tl(e,a)}}}function xR(e){let t=[];t.push(`age-encryption.org/v1
408
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=gg(e),r=Tc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=gg(e),r=Tc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ise.Parser=yj});var xj=ge(function(mse){var bj=Tk(),ase=fd(),Sd=md(),cse=jI(),lse=qe(),use=jk(),Sj=Zk();function vj(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new use.LineCounter||null,prettyErrors:t}}function dse(e,t={}){let{lineCounter:r,prettyErrors:o}=vj(t),n=new Sj.Parser(r?.addNewLine),i=new bj.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(Sd.prettifyError(e,r)),a.warnings.forEach(Sd.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function wj(e,t={}){let{lineCounter:r,prettyErrors:o}=vj(t),n=new Sj.Parser(r?.addNewLine),i=new bj.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new Sd.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(Sd.prettifyError(e,r)),s.warnings.forEach(Sd.prettifyError(e,r));return s}function pse(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=wj(e,r);if(!n)return null;if(n.warnings.forEach((i)=>cse.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function fse(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(lse.isDocument(e)&&!o)return e.toString(r);return new ase.Document(e,o,r).toString(r)}mse.parse=pse;mse.parseAllDocuments=dse;mse.parseDocument=wj;mse.stringify=fse});var Sse,vse,wse,Uk,xse,xi,_se,Ese,Ise,kse,sOe,Ase,Rse,Tse,bg,_j,$se,Ose,Cse,Pse,zse,Nse,Dse,Lse,Bse,jse,hn,So,Zse,vo,Mk,Use,Mse,qse,Fse,Jse,Kse,Hse,Vse,Wse,Gr,Gse,Qse,Yse;var $c=v(()=>{Sse=Tk(),vse=fd(),wse=fk(),Uk=md(),xse=Xu(),xi=qe(),_se=yi(),Ese=Et(),Ise=Si(),kse=vi(),sOe=mg(),Ase=Bk(),Rse=jk(),Tse=Zk(),bg=xj(),_j=Qu();$se=Sse.Composer,Ose=vse.Document,Cse=wse.Schema,Pse=Uk.YAMLError,zse=Uk.YAMLParseError,Nse=Uk.YAMLWarning,Dse=xse.Alias,Lse=xi.isAlias,Bse=xi.isCollection,jse=xi.isDocument,hn=xi.isMap,So=xi.isNode,Zse=xi.isPair,vo=xi.isScalar,Mk=xi.isSeq,Use=_se.Pair,Mse=Ese.Scalar,qse=Ise.YAMLMap,Fse=kse.YAMLSeq,Jse=Ase.Lexer,Kse=Rse.LineCounter,Hse=Tse.Parser,Vse=bg.parse,Wse=bg.parseAllDocuments,Gr=bg.parseDocument,Gse=bg.stringify,Qse=_j.visit,Yse=_j.visitAsync});var Rj={};Lt(Rj,{assertPilotUsersRemoved:()=>Fk,createPilotOffboardDriver:()=>qk,offboardPilotUsers:()=>Ij});import{readdir as Xse,readFile as eae,rm as vd,writeFile as tae}from"fs/promises";import{basename as rae,join as wo}from"path";async function Ij(e,t){let r=[...new Set(t.handles.map((p)=>mr.parse(p)))].sort((p,m)=>p.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await ut(e),l=r.map((p)=>nae(a,p,i)),u=t.driver??qk({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(l.map(async(p)=>({target:p,inspection:await u.inspect(p)})));if(iae(d),sae(d,o,s),!o){for(let p of d)if(!p.inspection.contentRepoArchived)await u.archiveContentRepo(p.target),s(`[${p.target.handle}] archived ${p.target.contentRepo}`);for(let p of d)for(let m of p.inspection.dnsRecords)await u.deleteDnsRecord(p.target,m),s(`[${p.target.handle}] deleted DNS ${m.name}`);for(let p of d)if(p.inspection.server)await u.deleteServer(p.target,p.inspection.server),s(`[${p.target.handle}] deleted ${p.target.instanceName}`);await oae(l,u,t.sleep??((p)=>new Promise((m)=>setTimeout(m,p)))),await aae(e,r),await mo(e),await Fk(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function nae(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=_I(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??Sg(r,"CF_ZONE_ID"),l=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=l.includes("/")?l:`${e.pilot.githubOrg}/${l}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function oae(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function iae(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function sae(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((l)=>`${l.type} ${l.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function aae(e,t){let r=new Set(t),o=wo(e,"cohorts");for(let n of(await Xse(o)).filter((i)=>i.endsWith(".yaml"))){let i=wo(o,n),s=await eae(i,"utf8"),a=Gr(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let l=a.get("members",!0);if(!Mk(l))throw Error(`${n}: members must be a sequence`);let u=l.items.filter((d)=>!vo(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===l.items.length)continue;if(u.length===0){await vd(i);continue}l.items=u,Kr.parse(a.toJS()),await tae(i,a.toString())}for(let n of t)await Promise.all([vd(wo(e,"users",`${n}.yaml`),{force:!0}),vd(wo(e,"users",`${n}.secrets.yaml`),{force:!0}),vd(wo(e,"users",`${n}.secrets.yaml.age`),{force:!0}),vd(wo(e,"users",n),{recursive:!0,force:!0})])}function qk(e){let t=e.fetchImpl??fetch,r=Sg(e.env,"HCLOUD_TOKEN"),o=Sg(e.env,"CF_API_TOKEN"),n=Sg(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,l]=await Promise.all([cae(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>lae(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),uae(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:l.archived}},async archiveContentRepo(i){await Oc(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:kj(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(Cc(await Oc(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:Aj(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await Oc(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function cae(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=Cc(await Oc(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=Cc(s),l=Ej(a.public_net),u=Ej(l?.ipv4);return{id:dae(a.id,"Hetzner server id"),name:wd(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function lae(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=Cc(await Oc(e,n.toString(),{headers:Aj(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let l=Cc(a),u=wd(l.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:wd(l.id,"Cloudflare record id"),name:wd(l.name,"Cloudflare record name"),type:u,content:wd(l.content,"Cloudflare record content")}})}async function uae(e,t,r){let o=Cc(await Oc(e,`https://api.github.com/repos/${r}`,{headers:kj(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function Oc(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function kj(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function Aj(e){return{Authorization:`Bearer ${e}`}}function Sg(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function Cc(e){if(!ks(e))throw Error("Provider returned an unexpected payload");return e}function Ej(e){return ks(e)?e:void 0}function wd(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function dae(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Fk(e,t){for(let r of t)for(let o of[wo(e,"users",`${r}.yaml`),wo(e,"users",`${r}.secrets.yaml.age`),wo(e,"users",r)])if(await Er(o))throw Error(`Offboarded user state remains: ${rae(o)}`)}var Jk=v(()=>{$c();Hr();EI();fc();Zn();Rs()});function Hk(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function vt(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 Ft(e,t,r=""){let o=Hk(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}function _o(e){if(typeof e!=="function"||typeof e.create!=="function")throw TypeError("Hash must wrapped by utils.createHasher");if(vt(e.outputLen),vt(e.blockLen),e.outputLen<1)throw Error('"outputLen" must be >= 1');if(e.blockLen<1)throw Error('"blockLen" must be >= 1')}function Pc(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 vg(e,t){Ft(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw RangeError('"digestInto() output" expected to be of length >='+r)}function wg(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function hr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function zc(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function gn(e,t){return e<<32-t|e>>>t}function Fe(e,t){return e<<t|e>>>32-t>>>0}function wae(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function xae(e){for(let t=0;t<e.length;t++)e[t]=wae(e[t]);return e}function xg(e){if(Ft(e),Lj)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=_ae[e[r]];return t}function Dj(e){if(e>=xo._0&&e<=xo._9)return e-xo._0;if(e>=xo.A&&e<=xo.F)return e-(xo.A-10);if(e>=xo.a&&e<=xo.f)return e-(xo.a-10);return}function _d(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);if(Lj)try{return Uint8Array.fromHex(e)}catch(n){if(n instanceof SyntaxError)throw RangeError(n.message);throw n}let t=e.length,r=t/2;if(t%2)throw RangeError("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=Dj(e.charCodeAt(i)),a=Dj(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw RangeError('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function Eae(e){if(typeof e!=="string")throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Wk(e,t=""){if(typeof e==="string")return Eae(e);return Ft(e,void 0,t)}function Gk(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Ft(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function _g(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 Qk(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.canXOF=o.canXOF,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Eo(e=32){vt(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 vae,Vk,Lj,_ae,xo,Yk=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Qr=v(()=>{vae=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();Vk=vae?(e)=>e:xae,Lj=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),_ae=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));xo={_0:48,_9:57,A:65,F:70,a:97,f:102}});class Xk{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(_o(e),Ft(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),hr(o)}update(e){return Pc(this),this.iHash.update(e),this}digestInto(e){Pc(this),vg(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Fn;var Ed=v(()=>{Qr();Fn=(()=>{let e=(t,r,o)=>new Xk(t,r).update(o).digest();return e.create=(t,r)=>new Xk(t,r),e})()});function Id(e,t,r){if(_o(e),r===void 0)r=new Uint8Array(e.outputLen);return Fn(e,r,t)}function tA(e,t,r,o=32){_o(e),vt(o,"length"),Ft(t,void 0,"prk");let n=e.outputLen;if(t.length<n)throw Error('"prk" must be at least HashLen octets');if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=Bj;else Ft(r,void 0,"info");let s=new Uint8Array(i*n),a=Fn.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)eA[0]=d+1,l.update(d===0?Bj:u).update(r).update(eA).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),hr(u,eA),s.slice(0,o)}var eA,Bj,_i=(e,t,r,o,n)=>tA(e,Id(e,t,r),o,n);var rA=v(()=>{Ed();Qr();eA=Uint8Array.of(0),Bj=Uint8Array.of()});function jj(e,t,r){return e&t^~e&r}function Zj(e,t,r){return e&t^e&r^t&r}class Eg{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zc(this.buffer)}update(e){Pc(this),Ft(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=zc(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Pc(this),vg(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,hr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=zc(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var Io,Jt;var Uj=v(()=>{Qr();Io=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function Iae(e,t=!1){if(t)return{h:Number(e&Ig),l:Number(e>>Mj&Ig)};return{h:Number(e>>Mj&Ig)|0,l:Number(e&Ig)|0}}function qj(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=Iae(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Jn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var Ig,Mj,nA=(e,t,r)=>e>>>r,oA=(e,t,r)=>e<<32-r|t>>>r,Bs=(e,t,r)=>e>>>r|t<<32-r,js=(e,t,r)=>e<<32-r|t>>>r,kd=(e,t,r)=>e<<64-r|t>>>r-32,Ad=(e,t,r)=>e>>>r-32|t<<64-r,Fj=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Jj=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,Kj=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),Hj=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,Vj=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),Wj=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var Gj=v(()=>{Ig=BigInt(4294967295),Mj=BigInt(32)});var Aae,Ei,Qj,Yj,Xj,Rae,Tae,Ii,ki,eZ,tZ,wt,kg;var Nc=v(()=>{Uj();Gj();Qr();Aae=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]),Ei=new Uint32Array(64);Qj=class Qj extends Eg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Ei[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=Ei[d-15],m=Ei[d-2],h=gn(p,7)^gn(p,18)^p>>>3,b=gn(m,17)^gn(m,19)^m>>>10;Ei[d]=b+Ei[d-7]+h+Ei[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=gn(s,6)^gn(s,11)^gn(s,25),m=u+p+jj(s,a,l)+Aae[d]+Ei[d]|0,b=(gn(r,2)^gn(r,13)^gn(r,22))+Zj(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){hr(Ei)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),hr(this.buffer)}};Yj=class Yj extends Qj{A=Io[0]|0;B=Io[1]|0;C=Io[2]|0;D=Io[3]|0;E=Io[4]|0;F=Io[5]|0;G=Io[6]|0;H=Io[7]|0;constructor(){super(32)}};Xj=(()=>qj(["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))))(),Rae=(()=>Xj[0])(),Tae=(()=>Xj[1])(),Ii=new Uint32Array(80),ki=new Uint32Array(80);eZ=class eZ extends Eg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ii[_]=e.getUint32(t),ki[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Ii[_-15]|0,O=ki[_-15]|0,L=Bs(A,O,1)^Bs(A,O,8)^nA(A,O,7),z=js(A,O,1)^js(A,O,8)^oA(A,O,7),K=Ii[_-2]|0,P=ki[_-2]|0,W=Bs(K,P,19)^kd(K,P,61)^nA(K,P,6),ee=js(K,P,19)^Ad(K,P,61)^oA(K,P,6),j=Kj(z,ee,ki[_-7],ki[_-16]),T=Hj(j,L,W,Ii[_-7],Ii[_-16]);Ii[_]=T|0,ki[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=Bs(d,p,14)^Bs(d,p,18)^kd(d,p,41),O=js(d,p,14)^js(d,p,18)^Ad(d,p,41),L=d&m^~d&b,z=p&h^~p&y,K=Vj(x,O,z,Tae[_],ki[_]),P=Wj(K,S,A,L,Rae[_],Ii[_]),W=K|0,ee=Bs(r,o,28)^kd(r,o,34)^kd(r,o,39),j=js(r,o,28)^Ad(r,o,34)^Ad(r,o,39),T=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Jn(l|0,u|0,P|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=Fj(W,j,B);r=Jj(I,P,ee,T),o=I|0}({h:r,l:o}=Jn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Jn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Jn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Jn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Jn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Jn(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=Jn(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=Jn(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,b,y,S,x)}roundClean(){hr(Ii,ki)}destroy(){this.destroyed=!0,hr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};tZ=class tZ extends eZ{Ah=Jt[0]|0;Al=Jt[1]|0;Bh=Jt[2]|0;Bl=Jt[3]|0;Ch=Jt[4]|0;Cl=Jt[5]|0;Dh=Jt[6]|0;Dl=Jt[7]|0;Eh=Jt[8]|0;El=Jt[9]|0;Fh=Jt[10]|0;Fl=Jt[11]|0;Gh=Jt[12]|0;Gl=Jt[13]|0;Hh=Jt[14]|0;Hl=Jt[15]|0;constructor(){super(64)}};wt=Qk(()=>new Yj,Yk(1)),kg=Qk(()=>new tZ,Yk(3))});function Og(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function aA(e){if(!Og(e))throw TypeError("Uint8Array expected")}function sZ(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 aZ(e){if(typeof e!=="function")throw TypeError("function expected");return!0}function Ai(e,t){if(typeof t!=="string")throw TypeError(`${e}: string expected`);return!0}function Td(e){if(typeof e!=="number")throw TypeError(`number expected, got ${typeof e}`);if(!Number.isSafeInteger(e))throw RangeError(`invalid integer: ${e}`)}function Rg(e){if(!Array.isArray(e))throw TypeError("array expected")}function Tg(e,t){if(!sZ(!0,t))throw TypeError(`${e}: array of strings expected`)}function cA(e,t){if(!sZ(!1,t))throw TypeError(`${e}: array of numbers expected`)}function Dr(...e){let t=(i)=>i,r=(i,s)=>(a)=>i(s(a)),o=e.map((i)=>i.encode).reduceRight(r,t),n=e.map((i)=>i.decode).reduce(r,t);return{encode:o,decode:n}}function Lr(e){let t=typeof e==="string"?e.split(""):e,r=t.length;Tg("alphabet",t);let o=new Map(t.map((n,i)=>[n,i]));return{encode:(n)=>(Rg(n),n.map((i)=>{if(!Number.isSafeInteger(i)||i<0||i>=r)throw Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${e}`);return t[i]})),decode:(n)=>(Rg(n),n.map((i)=>{Ai("alphabet.decode",i);let s=o.get(i);if(s===void 0)throw Error(`Unknown letter: "${i}". Allowed: ${e}`);return s}))}}function Br(e=""){return Ai("join",e),{encode:(t)=>(Tg("join.decode",t),t.join(e)),decode:(t)=>(Ai("join.decode",t),t.split(e))}}function Cg(e,t="="){return Td(e),Ai("padding",t),{encode(r){Tg("padding.encode",r);while(r.length*e%8)r.push(t);return r},decode(r){Tg("padding.decode",r);let o=r.length;if(o*e%8)throw Error("padding: invalid, string should have whole number of bytes");for(;o>0&&r[o-1]===t;o--)if((o-1)*e%8===0)throw Error("padding: invalid, string has too much padding");return r.slice(0,o)}}}function cZ(e){return aZ(e),{encode:(t)=>t,decode:(t)=>e(t)}}function rZ(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(Rg(e),!e.length)return[];let o=0,n=[],i=Array.from(e,(a)=>{if(Td(a),a<0||a>=t)throw Error(`invalid integer: ${a}`);return a}),s=i.length;while(!0){let a=0,l=!0;for(let u=o;u<s;u++){let d=i[u],p=t*a,m=p+d;if(!Number.isSafeInteger(m)||p/t!==a||m-d!==p)throw Error("convertRadix: carry overflow");let h=m/r;a=m%r;let b=Math.floor(h);if(i[u]=b,!Number.isSafeInteger(b)||b*r+a!==m)throw Error("convertRadix: carry overflow");if(!l)continue;else if(!b)o=u;else l=!1}if(n.push(a),l)break}for(let a=0;a<e.length-1&&e[a]===0;a++)n.push(0);return n.reverse()}function iA(e,t,r,o){if(Rg(e),t<=0||t>32)throw RangeError(`convertRadix2: wrong from=${t}`);if(r<=0||r>32)throw RangeError(`convertRadix2: wrong to=${r}`);if($g(t,r)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${r} carryBits=${$g(t,r)}`);let n=0,i=0,s=Ag[t],a=Ag[r]-1,l=[];for(let u of e){if(Td(u),u>=s)throw Error(`convertRadix2: invalid data word=${u} from=${t}`);if(n=n<<t|u,i+t>32)throw Error(`convertRadix2: carry overflow pos=${i} from=${t}`);i+=t;for(;i>=r;i-=r)l.push((n>>i-r&a)>>>0);let d=Ag[i];if(d===void 0)throw Error("invalid carry");n&=d-1}if(n=n<<r-i&a,!o&&i>=t)throw Error("Excess padding");if(!o&&n>0)throw Error(`Non-zero padding: ${n}`);if(o&&i>0)l.push(n>>>0);return l}function $ae(e){Td(e);let t=256;return{encode:(r)=>{if(!Og(r))throw TypeError("radix.encode input should be Uint8Array");return rZ(Array.from(r),t,e)},decode:(r)=>(cA("radix.decode",r),Uint8Array.from(rZ(r,e,t)))}}function Yr(e,t=!1){if(Td(e),e<=0||e>32)throw RangeError("radix2: bits should be in (0..32]");if($g(8,e)>32||$g(e,8)>32)throw RangeError("radix2: carry overflow");return{encode:(r)=>{if(!Og(r))throw TypeError("radix2.encode input should be Uint8Array");return iA(Array.from(r),8,e,!t)},decode:(r)=>(cA("radix2.decode",r),Uint8Array.from(iA(r,e,8,t)))}}function nZ(e){return aZ(e),function(...t){try{return e.apply(null,t)}catch(r){}}}function Rd(e){let t=e>>25,r=(e&33554431)<<5;for(let o=0;o<oZ.length;o++)if((t>>o&1)===1)r^=oZ[o];return r}function iZ(e,t,r=1){let o=e.length,n=1;for(let i=0;i<o;i++){let s=e.charCodeAt(i);if(s<33||s>126)throw Error(`Invalid prefix (${e})`);n=Rd(n)^s>>5}n=Rd(n);for(let i=0;i<o;i++)n=Rd(n)^e.charCodeAt(i)&31;for(let i of t)n=Rd(n)^i;for(let i=0;i<6;i++)n=Rd(n);return n^=r,sA.encode(iA([n%Ag[30]],30,5,!1))}function pZ(e){let t=e==="bech32"?1:734539939,r=Yr(5),o=r.decode,n=r.encode,i=nZ(o);function s(p,m,h=90){if(Ai("bech32.encode prefix",p),Og(m))m=Array.from(m);cA("bech32.encode",m);let b=p.length;if(b===0)throw TypeError(`Invalid prefix length ${b}`);let y=b+7+m.length;if(h!==!1&&y>h)throw TypeError(`Length ${y} exceeds limit ${h}`);let S=p.toLowerCase(),x=iZ(S,m,t);return`${S}1${sA.encode(m)}${x}`}function a(p,m=90){Ai("bech32.decode input",p);let h=p.length;if(h<8||m!==!1&&h>m)throw TypeError(`invalid string length: ${h} (${p}). Expected (8..${m})`);let b=p.toLowerCase();if(p!==b&&p!==p.toUpperCase())throw Error("String must be lowercase or uppercase");let y=b.lastIndexOf("1");if(y===0||y===-1)throw Error('Letter "1" must be present between prefix and data only');let S=b.slice(0,y),x=b.slice(y+1);if(x.length<6)throw Error("Data must be at least 6 characters long");let _=sA.decode(x).slice(0,-6),A=iZ(S,_,t);if(!x.endsWith(A))throw Error(`Invalid checksum in ${p}: expected "${A}"`);return{prefix:S,words:_}}let l=nZ(a);function u(p){let{prefix:m,words:h}=a(p,!1);return{prefix:m,words:h,bytes:o(h)}}function d(p,m){return s(p,n(m))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:l,fromWords:o,fromWordsUnsafe:i,toWords:n}}var lZ=(e,t)=>t===0?e:lZ(t,e%t),$g=(e,t)=>e+(t-lZ(e,t)),Ag,DOe,LOe,BOe,jOe,ZOe,UOe,uZ,Oae,dZ=(e,t)=>{Ai("base64",e);let r=t?"base64url":"base64";if(e.length>0&&Oae.test(e))throw Error("invalid base64");return Uint8Array.fromBase64(e,{alphabet:r,lastChunkHandling:"strict"})},lA,tr,MOe,qOe,uA=(e)=>Dr($ae(58),Lr(e),Br("")),FOe,JOe,KOe,sA,oZ,jr,HOe,Cae,Pae,VOe;var $d=v(()=>{/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ag=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();DOe=Object.freeze(Dr(Yr(4),Lr("0123456789ABCDEF"),Br(""))),LOe=Object.freeze(Dr(Yr(5),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Cg(5),Br(""))),BOe=Object.freeze(Dr(Yr(5),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Br(""))),jOe=Object.freeze(Dr(Yr(5),Lr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Cg(5),Br(""))),ZOe=Object.freeze(Dr(Yr(5),Lr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Br(""))),UOe=Object.freeze(Dr(Yr(5),Lr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Br(""),cZ((e)=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),uZ=(()=>typeof Uint8Array.from([]).toBase64==="function"&&typeof Uint8Array.fromBase64==="function")(),Oae=/[\t\n\f\r ]/,lA=Object.freeze(uZ?{encode(e){return aA(e),e.toBase64()},decode(e){return dZ(e,!1)}}:Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Cg(6),Br(""))),tr=Object.freeze(Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Br(""))),MOe=Object.freeze(uZ?{encode(e){return aA(e),e.toBase64({alphabet:"base64url"})},decode(e){return dZ(e,!0)}}:Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Cg(6),Br(""))),qOe=Object.freeze(Dr(Yr(6),Lr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Br(""))),FOe=Object.freeze(uA("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),JOe=Object.freeze(uA("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ")),KOe=Object.freeze(uA("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz")),sA=Dr(Lr("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Br("")),oZ=[996825010,642813549,513874426,1027748829,705979059];jr=Object.freeze(pZ("bech32")),HOe=Object.freeze(pZ("bech32m")),Cae=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),Pae={encode(e){return aA(e),e.toHex()},decode(e){return Ai("hex",e),Uint8Array.fromHex(e)}},VOe=Object.freeze(Cae?Pae:Dr(Yr(4),Lr("0123456789abcdef"),Br(""),cZ((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 Nae(e,t,r,o){_o(e);let n=_g({dkLen:32,asyncTick:10},o),{c:i,dkLen:s,asyncTick:a}=n;if(vt(i,"c"),vt(s,"dkLen"),vt(a,"asyncTick"),i<1)throw Error("iterations (c) must be >= 1");if(s<1)throw Error('"dkLen" must be >= 1');if(s>4294967295*e.outputLen)throw Error("derived key too long");let l=Wk(t,"password"),u=Wk(r,"salt"),d=new Uint8Array(s),p=Fn.create(e,l),m=p._cloneInto().update(u);return{c:i,dkLen:s,asyncTick:a,DK:d,PRF:p,PRFSalt:m}}function Dae(e,t,r,o,n){if(e.destroy(),t.destroy(),o)o.destroy();return hr(n),r}function dA(e,t,r,o){let{c:n,dkLen:i,DK:s,PRF:a,PRFSalt:l}=Nae(e,t,r,o),u,d=new Uint8Array(4),p=zc(d),m=new Uint8Array(a.outputLen);for(let h=1,b=0;b<i;h++,b+=a.outputLen){let y=s.subarray(b,b+a.outputLen);p.setInt32(0,h,!1),(u=l._cloneInto(u)).update(d).digestInto(m),y.set(m.subarray(0,y.length));for(let S=1;S<n;S++){a._cloneInto(u).update(m).digestInto(m);for(let x=0;x<y.length;x++)y[x]^=m[x]}}return Dae(a,l,s,u,m)}var fZ=v(()=>{Ed();Qr()});function mZ(e,t,r,o,n,i){let s=e[t++]^r[o++],a=e[t++]^r[o++],l=e[t++]^r[o++],u=e[t++]^r[o++],d=e[t++]^r[o++],p=e[t++]^r[o++],m=e[t++]^r[o++],h=e[t++]^r[o++],b=e[t++]^r[o++],y=e[t++]^r[o++],S=e[t++]^r[o++],x=e[t++]^r[o++],_=e[t++]^r[o++],A=e[t++]^r[o++],O=e[t++]^r[o++],L=e[t++]^r[o++],z=s,K=a,P=l,W=u,ee=d,j=p,T=m,B=h,I=b,R=y,k=S,q=x,N=_,H=A,G=O,re=L;for(let ae=0;ae<8;ae+=2)ee^=Fe(z+N|0,7),I^=Fe(ee+z|0,9),N^=Fe(I+ee|0,13),z^=Fe(N+I|0,18),R^=Fe(j+K|0,7),H^=Fe(R+j|0,9),K^=Fe(H+R|0,13),j^=Fe(K+H|0,18),G^=Fe(k+T|0,7),P^=Fe(G+k|0,9),T^=Fe(P+G|0,13),k^=Fe(T+P|0,18),W^=Fe(re+q|0,7),B^=Fe(W+re|0,9),q^=Fe(B+W|0,13),re^=Fe(q+B|0,18),K^=Fe(z+W|0,7),P^=Fe(K+z|0,9),W^=Fe(P+K|0,13),z^=Fe(W+P|0,18),T^=Fe(j+ee|0,7),B^=Fe(T+j|0,9),ee^=Fe(B+T|0,13),j^=Fe(ee+B|0,18),q^=Fe(k+R|0,7),I^=Fe(q+k|0,9),R^=Fe(I+q|0,13),k^=Fe(R+I|0,18),N^=Fe(re+G|0,7),H^=Fe(N+re|0,9),G^=Fe(H+N|0,13),re^=Fe(G+H|0,18);n[i++]=s+z|0,n[i++]=a+K|0,n[i++]=l+P|0,n[i++]=u+W|0,n[i++]=d+ee|0,n[i++]=p+j|0,n[i++]=m+T|0,n[i++]=h+B|0,n[i++]=b+I|0,n[i++]=y+R|0,n[i++]=S+k|0,n[i++]=x+q|0,n[i++]=_+N|0,n[i++]=A+H|0,n[i++]=O+G|0,n[i++]=L+re|0}function pA(e,t,r,o,n){let i=o+0,s=o+16*n;for(let a=0;a<16;a++)r[s+a]=e[t+(2*n-1)*16+a];for(let a=0;a<n;a++,i+=16,t+=16){if(mZ(r,s,e,t,r,i),a>0)s+=16;mZ(r,i,e,t+=16,r,s)}}function Lae(e,t,r){let o=_g({dkLen:32,asyncTick:10,maxmem:1073742848},r),{N:n,r:i,p:s,dkLen:a,asyncTick:l,maxmem:u,onProgress:d}=o;if(vt(n,"N"),vt(i,"r"),vt(s,"p"),vt(a,"dkLen"),vt(l,"asyncTick"),vt(u,"maxmem"),d!==void 0&&typeof d!=="function")throw Error("progressCb must be a function");let p=128*i,m=p/4,h=Math.pow(2,32);if(n<=1||(n&n-1)!==0||n>h)throw Error('"N" expected a power of 2, and 2^1 <= N <= 2^32');if(s<1||s>(h-1)*32/p)throw Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)');if(a<1||a>(h-1)*32)throw Error('"dkLen" expected integer 1..(2^32 - 1) * 32');let b=p*(n+s+1);if(b>u)throw Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))='+b+", maxmem="+u);let y=dA(wt,e,t,{c:1,dkLen:p*s}),S=wg(y),x=wg(new Uint8Array(p*n)),_=wg(new Uint8Array(p)),A=()=>{};if(d){let O=2*n*s,L=Math.max(Math.floor(O/1e4),1),z=0;A=()=>{if(z++,d&&(!(z%L)||z===O))d(z/O)}}return{N:n,r:i,p:s,dkLen:a,blockSize32:m,V:x,B32:S,B:y,tmp:_,blockMixCb:A,asyncTick:l}}function Bae(e,t,r,o,n){let i=dA(wt,e,r,{c:1,dkLen:t});return hr(r,o,n),i}function fA(e,t,r){let{N:o,r:n,p:i,dkLen:s,blockSize32:a,V:l,B32:u,B:d,tmp:p,blockMixCb:m}=Lae(e,t,r);Vk(u);for(let h=0;h<i;h++){let b=a*h;for(let y=0;y<a;y++)l[y]=u[b+y];for(let y=0,S=0;y<o-1;y++)pA(l,S,l,S+=a,n),m();pA(l,(o-1)*a,u,b,n),m();for(let y=0;y<o;y++){let S=(u[b+a-16]&o-1)>>>0;for(let x=0;x<a;x++)p[x]=u[b+x]^l[S*a+x];pA(p,0,u,b,n),m()}}return Vk(u),Bae(e,s,d,l,p)}var hZ=v(()=>{fZ();Nc();Qr()});function jae(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Pg(e){if(typeof e!=="boolean")throw TypeError(`boolean expected, not ${e}`)}function Dc(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 Ct(e,t,r=""){let o=jae(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+l;if(!o)throw TypeError(u);throw RangeError(u)}return e}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 gZ(e,t,r=!1){Ct(e,void 0,"output");let o=t.outputLen;if(e.length<o)throw RangeError("digestInto() expects output buffer of length at least "+o);if(r&&!Lc(e))throw Error("invalid output, must be aligned")}function Kn(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function yn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Zae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function yZ(e,t){if(t==null||typeof t!=="object")throw Error("options must be defined");return Object.assign(e,t)}function bZ(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function SZ(e,t,r){let o=t,n=r||(()=>[]),i=(a,l)=>o(l,...n(a)).update(a).digest(),s=o(new Uint8Array(e),...n(new Uint8Array(0)));return i.outputLen=s.outputLen,i.blockLen=s.blockLen,i.create=(a,...l)=>o(a,...l),i}function Od(e,t,r=!0){if(t===void 0)return new Uint8Array(e);if(Ct(t,void 0,"output"),t.length!==e)throw Error('"output" expected Uint8Array of length '+e+", got: "+t.length);if(r&&!Lc(t))throw Error("invalid output, must be aligned");return t}function wZ(e,t,r){Dc(e),Dc(t),Pg(r);let o=new Uint8Array(16),n=Zae(o);return n.setBigUint64(0,BigInt(t),r),n.setBigUint64(8,BigInt(e),r),o}function Lc(e){return e.byteOffset%4===0}function Bc(e){return Uint8Array.from(Ct(e))}var Zs,Uae=(e)=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,Mae=(e)=>{for(let t=0;t<e.length;t++)e[t]=Uae(e[t]);return e},ko,vZ=(e,t)=>{function r(o,...n){if(Ct(o,void 0,"key"),e.nonceLength!==void 0){let d=n[0];Ct(d,e.varSizeNonce?void 0:e.nonceLength,"nonce")}let i=e.tagLength;if(i&&n[1]!==void 0)Ct(n[1],void 0,"AAD");let s=t(o,...n),a=(d,p)=>{if(p!==void 0){if(d!==2)throw Error("cipher output not supported");Ct(p,void 0,"output")}},l=!1;return{encrypt(d,p){if(l)throw Error("cannot encrypt() twice with same key + nonce");return l=!0,Ct(d),a(s.encrypt.length,p),s.encrypt(d,p)},decrypt(d,p){if(Ct(d),i&&d.length<i)throw Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,p),s.decrypt(d,p)}}}return Object.assign(r,e),r};var zg=v(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Zs=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)(),ko=Zs?(e)=>e:Mae});function Je(e,t){return e<<t|e>>>32-t}function Kae(e,t,r,o,n,i,s,a){let l=n.length,u=new Uint8Array(Cd),d=Kn(u),p=Zs&&Lc(n)&&Lc(i),m=p?Kn(n):xZ,h=p?Kn(i):xZ;if(!Zs){for(let b=0;b<l;s++){if(e(t,r,o,d,s,a),ko(d),s>=hA)throw Error("arx: counter overflow");let y=Math.min(Cd,l-b);for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}return}for(let b=0;b<l;s++){if(e(t,r,o,d,s,a),s>=hA)throw Error("arx: counter overflow");let y=Math.min(Cd,l-b);if(p&&y===Cd){let S=b/4;if(b%4!==0)throw Error("arx: invalid block position");for(let x=0,_;x<Jae;x++)_=S+x,h[_]=m[_]^d[x];b+=Cd;continue}for(let S=0,x;S<y;S++)x=b+S,i[x]=n[x]^u[S];b+=y}}function EZ(e,t){let{allowShortKeys:r,extendNonceFn:o,counterLength:n,counterRight:i,rounds:s}=yZ({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=="function")throw Error("core must be a function");return Dc(n),Dc(s),Pg(i),Pg(r),(a,l,u,d,p=0)=>{Ct(a,void 0,"key"),Ct(l,void 0,"nonce"),Ct(u,void 0,"data");let m=u.length;if(d=Od(m,d,!1),Dc(p),p<0||p>=hA)throw Error("arx: counter overflow");let h=[],b=a.length,y,S;if(b===32)h.push(y=Bc(a)),S=Fae;else if(b===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),S=qae,h.push(y);else throw Ct(a,32,"arx key"),Error("invalid key size");if(!Zs||!Lc(l))h.push(l=Bc(l));let x=Kn(y);if(o){if(l.length!==24)throw Error("arx: extended nonce must be 24 bytes");let O=l.subarray(0,16);if(Zs)o(S,x,Kn(O),x);else{let L=ko(Uint32Array.from(S));o(L,x,Kn(O),x),yn(L),ko(x)}l=l.subarray(16)}else if(!Zs)ko(x);let _=16-n;if(_!==l.length)throw Error(`arx: nonce must be ${_} or 16 bytes`);if(_!==12){let O=new Uint8Array(12);O.set(l,i?0:12-l.length),l=O,h.push(l)}let A=ko(Kn(l));try{return Kae(e,S,x,A,u,d,p,s),d}finally{yn(...h)}}}var _Z=(e)=>Uint8Array.from(e.split(""),(t)=>t.charCodeAt(0)),qae,Fae,Cd=64,Jae=16,hA,xZ;var IZ=v(()=>{zg();qae=(()=>ko(Kn(_Z("expand 16-byte k"))))(),Fae=(()=>ko(Kn(_Z("expand 32-byte k"))))();hA=(()=>4294967295)(),xZ=Uint32Array.of()});function Kt(e,t){return e[t++]&255|(e[t++]&255)<<8}class kZ{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=Bc(Ct(e,32,"key"));let t=Kt(e,0),r=Kt(e,2),o=Kt(e,4),n=Kt(e,6),i=Kt(e,8),s=Kt(e,10),a=Kt(e,12),l=Kt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|n<<9)&8191,this.r[4]=(n>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|s<<2)&8191,this.r[7]=(s>>>11|a<<5)&8065,this.r[8]=(a>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Kt(e,16+2*u)}process(e,t,r=!1){let o=r?0:2048,{h:n,r:i}=this,s=i[0],a=i[1],l=i[2],u=i[3],d=i[4],p=i[5],m=i[6],h=i[7],b=i[8],y=i[9],S=Kt(e,t+0),x=Kt(e,t+2),_=Kt(e,t+4),A=Kt(e,t+6),O=Kt(e,t+8),L=Kt(e,t+10),z=Kt(e,t+12),K=Kt(e,t+14),P=n[0]+(S&8191),W=n[1]+((S>>>13|x<<3)&8191),ee=n[2]+((x>>>10|_<<6)&8191),j=n[3]+((_>>>7|A<<9)&8191),T=n[4]+((A>>>4|O<<12)&8191),B=n[5]+(O>>>1&8191),I=n[6]+((O>>>14|L<<2)&8191),R=n[7]+((L>>>11|z<<5)&8191),k=n[8]+((z>>>8|K<<8)&8191),q=n[9]+(K>>>5|o),N=0,H=N+P*s+W*(5*y)+ee*(5*b)+j*(5*h)+T*(5*m);N=H>>>13,H&=8191,H+=B*(5*p)+I*(5*d)+R*(5*u)+k*(5*l)+q*(5*a),N+=H>>>13,H&=8191;let G=N+P*a+W*s+ee*(5*y)+j*(5*b)+T*(5*h);N=G>>>13,G&=8191,G+=B*(5*m)+I*(5*p)+R*(5*d)+k*(5*u)+q*(5*l),N+=G>>>13,G&=8191;let re=N+P*l+W*a+ee*s+j*(5*y)+T*(5*b);N=re>>>13,re&=8191,re+=B*(5*h)+I*(5*m)+R*(5*p)+k*(5*d)+q*(5*u),N+=re>>>13,re&=8191;let ae=N+P*u+W*l+ee*a+j*s+T*(5*y);N=ae>>>13,ae&=8191,ae+=B*(5*b)+I*(5*h)+R*(5*m)+k*(5*p)+q*(5*d),N+=ae>>>13,ae&=8191;let me=N+P*d+W*u+ee*l+j*a+T*s;N=me>>>13,me&=8191,me+=B*(5*y)+I*(5*b)+R*(5*h)+k*(5*m)+q*(5*p),N+=me>>>13,me&=8191;let be=N+P*p+W*d+ee*u+j*l+T*a;N=be>>>13,be&=8191,be+=B*s+I*(5*y)+R*(5*b)+k*(5*h)+q*(5*m),N+=be>>>13,be&=8191;let xe=N+P*m+W*p+ee*d+j*u+T*l;N=xe>>>13,xe&=8191,xe+=B*a+I*s+R*(5*y)+k*(5*b)+q*(5*h),N+=xe>>>13,xe&=8191;let Ae=N+P*h+W*m+ee*p+j*d+T*u;N=Ae>>>13,Ae&=8191,Ae+=B*l+I*a+R*s+k*(5*y)+q*(5*b),N+=Ae>>>13,Ae&=8191;let ke=N+P*b+W*h+ee*m+j*p+T*d;N=ke>>>13,ke&=8191,ke+=B*u+I*l+R*a+k*s+q*(5*y),N+=ke>>>13,ke&=8191;let _e=N+P*y+W*b+ee*h+j*m+T*p;N=_e>>>13,_e&=8191,_e+=B*d+I*u+R*l+k*a+q*s,N+=_e>>>13,_e&=8191,N=(N<<2)+N|0,N=N+H|0,H=N&8191,N=N>>>13,G+=N,n[0]=H,n[1]=G,n[2]=re,n[3]=ae,n[4]=me,n[5]=be,n[6]=xe,n[7]=Ae,n[8]=ke,n[9]=_e}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let s=2;s<10;s++)e[s]+=o,o=e[s]>>>13,e[s]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let s=1;s<10;s++)r[s]=e[s]+o,o=r[s]>>>13,r[s]&=8191;r[9]-=8192;let n=(o^1)-1;for(let s=0;s<10;s++)r[s]&=n;n=~n;for(let s=0;s<10;s++)e[s]=e[s]&n|r[s];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let s=1;s<8;s++)i=(e[s]+t[s]|0)+(i>>>16)|0,e[s]=i&65535;yn(r)}update(e){mA(this),Ct(e),e=Bc(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(r-this.pos,o-n);if(i===r){for(;r<=o-n;n+=r)this.process(e,n);continue}if(t.set(e.subarray(n,n+i),this.pos),this.pos+=i,n+=i,this.pos===r)this.process(t,0,!1),this.pos=0}return this}destroy(){this.destroyed=!0,yn(this.h,this.r,this.buffer,this.pad)}digestInto(e){mA(this),gZ(e,this),this.finished=!0;let{buffer:t,h:r}=this,{pos:o}=this;if(o){t[o++]=1;for(;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let n=0;for(let i=0;i<8;i++)e[n++]=r[i]>>>0,e[n++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}}var AZ;var RZ=v(()=>{zg();AZ=SZ(32,(e)=>new kZ(e))});function Hae(e,t,r,o,n,i=20){let s=e[0],a=e[1],l=e[2],u=e[3],d=t[0],p=t[1],m=t[2],h=t[3],b=t[4],y=t[5],S=t[6],x=t[7],_=n,A=r[0],O=r[1],L=r[2],z=s,K=a,P=l,W=u,ee=d,j=p,T=m,B=h,I=b,R=y,k=S,q=x,N=_,H=A,G=O,re=L;for(let me=0;me<i;me+=2)z=z+ee|0,N=Je(N^z,16),I=I+N|0,ee=Je(ee^I,12),z=z+ee|0,N=Je(N^z,8),I=I+N|0,ee=Je(ee^I,7),K=K+j|0,H=Je(H^K,16),R=R+H|0,j=Je(j^R,12),K=K+j|0,H=Je(H^K,8),R=R+H|0,j=Je(j^R,7),P=P+T|0,G=Je(G^P,16),k=k+G|0,T=Je(T^k,12),P=P+T|0,G=Je(G^P,8),k=k+G|0,T=Je(T^k,7),W=W+B|0,re=Je(re^W,16),q=q+re|0,B=Je(B^q,12),W=W+B|0,re=Je(re^W,8),q=q+re|0,B=Je(B^q,7),z=z+j|0,re=Je(re^z,16),k=k+re|0,j=Je(j^k,12),z=z+j|0,re=Je(re^z,8),k=k+re|0,j=Je(j^k,7),K=K+T|0,N=Je(N^K,16),q=q+N|0,T=Je(T^q,12),K=K+T|0,N=Je(N^K,8),q=q+N|0,T=Je(T^q,7),P=P+B|0,H=Je(H^P,16),I=I+H|0,B=Je(B^I,12),P=P+B|0,H=Je(H^P,8),I=I+H|0,B=Je(B^I,7),W=W+ee|0,G=Je(G^W,16),R=R+G|0,ee=Je(ee^R,12),W=W+ee|0,G=Je(G^W,8),R=R+G|0,ee=Je(ee^R,7);let ae=0;o[ae++]=s+z|0,o[ae++]=a+K|0,o[ae++]=l+P|0,o[ae++]=u+W|0,o[ae++]=d+ee|0,o[ae++]=p+j|0,o[ae++]=m+T|0,o[ae++]=h+B|0,o[ae++]=b+I|0,o[ae++]=y+R|0,o[ae++]=S+k|0,o[ae++]=x+q|0,o[ae++]=_+N|0,o[ae++]=A+H|0,o[ae++]=O+G|0,o[ae++]=L+re|0}function $Z(e,t,r,o,n){if(n!==void 0)Ct(n,void 0,"AAD");let i=e(t,r,Gae),s=wZ(o.length,n?n.length:0,!0),a=AZ.create(i);if(n)TZ(a,n);TZ(a,o),a.update(s);let l=a.digest();return yn(i,s),l}var Vae,Wae,TZ=(e,t)=>{e.update(t);let r=t.length%16;if(r)e.update(Wae.subarray(r))},Gae,Qae=(e)=>(t,r,o)=>({encrypt(i,s){let a=i.length;s=Od(a+16,s,!1),s.set(i);let l=s.subarray(0,-16);e(t,r,l,l,1);let u=$Z(e,t,r,l,o);return s.set(u,a),yn(u),s},decrypt(i,s){s=Od(i.length-16,s,!1);let a=i.subarray(0,-16),l=i.subarray(-16),u=$Z(e,t,r,a,o);if(!bZ(l,u))throw yn(u),Error("invalid tag");return s.set(i.subarray(0,-16)),e(t,r,s,s,1),yn(u),s}}),Xr;var gA=v(()=>{IZ();RZ();zg();Vae=EZ(Hae,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Wae=new Uint8Array(16),Gae=new Uint8Array(32);Xr=vZ({blockSize:64,nonceLength:12,tagLength:16},Qae(Vae))});function jc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Zt(e,t=""){if(!Number.isSafeInteger(e)||e<0){let r=t&&`"${t}" `;throw Error(`${r}expected integer >= 0, got ${e}`)}}function Re(e,t,r=""){let o=jc(e),n=e?.length,i=t!==void 0;if(!o||i&&n!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",l=o?`length=${n}`:`type=${typeof e}`;throw Error(s+"expected Uint8Array"+a+", got "+l)}return e}function en(e){if(typeof e!=="function"||typeof e.create!=="function")throw Error("Hash must wrapped by utils.createHasher");Zt(e.outputLen),Zt(e.blockLen)}function Ro(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 Ng(e,t){Re(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw Error('"digestInto() output" expected to be of length >='+r)}function Dg(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 Lg(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bn(e,t){return e<<32-t|e>>>t}function Xae(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ece(e){for(let t=0;t<e.length;t++)e[t]=Xae(e[t]);return e}function Us(e){if(Re(e),CZ)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=tce[e[r]];return t}function OZ(e){if(e>=Ao._0&&e<=Ao._9)return e-Ao._0;if(e>=Ao.A&&e<=Ao.F)return e-(Ao.A-10);if(e>=Ao.a&&e<=Ao.f)return e-(Ao.a-10);return}function Ms(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);if(CZ)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw Error("hex string expected, got unpadded hex of length "+t);let o=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){let s=OZ(e.charCodeAt(i)),a=OZ(e.charCodeAt(i+1));if(s===void 0||a===void 0){let l=e[i]+e[i+1];throw Error('hex string expected, got non-hex character "'+l+'" at index '+i)}o[n]=s*16+a}return o}function It(...e){let t=0;for(let o=0;o<e.length;o++){let n=e[o];Re(n),t+=n.length}let r=new Uint8Array(t);for(let o=0,n=0;o<e.length;o++){let i=e[o];r.set(i,n),n+=i.length}return r}function Zc(e,t={}){let r=(n,i)=>e(i).update(n).digest(),o=e(void 0);return r.outputLen=o.outputLen,r.blockLen=o.blockLen,r.create=(n)=>e(n),Object.assign(r,t),Object.freeze(r)}function Ri(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 Yae,yA,CZ,tce,Ao,Ti=(e)=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});var Zr=v(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Yae=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();yA=Yae?(e)=>e:ece,CZ=(()=>typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function")(),tce=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));Ao={_0:48,_9:57,A:65,F:70,a:97,f:102}});function Pd(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw Error(r+"expected boolean, got type="+typeof e)}return e}function PZ(e){if(typeof e==="bigint"){if(!Bg(e))throw Error("positive bigint expected, got "+e)}else Zt(e);return e}function zd(e){let t=PZ(e).toString(16);return t.length&1?"0"+t:t}function zZ(e){if(typeof e!=="string")throw Error("hex string expected, got "+typeof e);return e===""?SA:BigInt("0x"+e)}function $i(e){return zZ(Us(e))}function Oi(e){return zZ(Us(jg(Re(e)).reverse()))}function Uc(e,t){Zt(t),e=PZ(e);let r=Ms(e.toString(16).padStart(t*2,"0"));if(r.length!==t)throw Error("number too large");return r}function Nd(e,t){return Uc(e,t).reverse()}function jg(e){return Uint8Array.from(e)}function Ci(e){return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw Error(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function rce(e,t,r){return Bg(e)&&Bg(t)&&Bg(r)&&t<=e&&e<r}function Dd(e,t,r,o){if(!rce(t,r,o))throw Error("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function vA(e){let t;for(t=0;e>SA;e>>=bA,t+=1);return t}function NZ(e,t,r){if(Zt(e,"hashLen"),Zt(t,"qByteLen"),typeof r!=="function")throw Error("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...S)=>r(u,It(l,...S)),h=(S=n)=>{if(u=m(i,S),l=m(),S.length===0)return;u=m(s,S),l=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){l=m();let _=l.slice();x.push(_),S+=l.length}return It(...x)};return(S,x)=>{p(),h(S);let _=void 0;while(!(_=x(b())))h();return p(),_}}function qs(e,t={},r={}){if(!e||typeof e!=="object")throw Error("expected valid options object");function o(i,s,a){let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw Error(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}function wA(e){let t=new WeakMap;return(r,...o)=>{let n=t.get(r);if(n!==void 0)return n;let i=e(r,...o);return t.set(r,i),i}}var SA,bA,Bg=(e)=>typeof e==="bigint"&&SA<=e,Ld=(e)=>(bA<<BigInt(e))-bA;var Mc=v(()=>{Zr();Zr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */SA=BigInt(0),bA=BigInt(1)});function gr(e,t){let r=e%t;return r>=yr?r:t+r}function tn(e,t,r){let o=e;while(t-- >yr)o*=o,o%=r;return o}function DZ(e,t){if(e===yr)throw Error("invert: expected non-zero number");if(t<=yr)throw Error("invert: expected positive modulus, got "+t);let r=gr(e,t),o=t,n=yr,i=rr,s=rr,a=yr;while(r!==yr){let u=o/r,d=o%r,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==rr)throw Error("invert: does not exist");return gr(n,t)}function xA(e,t,r){if(!e.eql(e.sqr(t),r))throw Error("Cannot find square root")}function qZ(e,t){let r=(e.ORDER+rr)/jZ,o=e.pow(t,r);return xA(e,o,t),o}function ice(e,t){let r=(e.ORDER-ZZ)/UZ,o=e.mul(t,Fs),n=e.pow(o,r),i=e.mul(t,n),s=e.mul(e.mul(i,Fs),n),a=e.mul(i,e.sub(s,e.ONE));return xA(e,a,t),a}function sce(e){let t=Zg(e),r=FZ(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+nce)/MZ;return(a,l)=>{let u=a.pow(l,s),d=a.mul(u,o),p=a.mul(u,n),m=a.mul(u,i),h=a.eql(a.sqr(d),l),b=a.eql(a.sqr(p),l);u=a.cmov(u,d,h),d=a.cmov(m,p,b);let y=a.eql(a.sqr(d),l),S=a.cmov(u,d,y);return xA(a,S,l),S}}function FZ(e){if(e<BZ)throw Error("sqrt is not defined for small field");let t=e-rr,r=0;while(t%Fs===yr)t/=Fs,r++;let o=Fs,n=Zg(e);while(LZ(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return qZ;let i=n.pow(o,t),s=(t+rr)/Fs;return function(l,u){if(l.is0(u))return u;if(LZ(l,u)!==1)throw Error("Cannot find square root");let d=r,p=l.mul(l.ONE,i),m=l.pow(u,t),h=l.pow(u,s);while(!l.eql(m,l.ONE)){if(l.is0(m))return l.ZERO;let b=1,y=l.sqr(m);while(!l.eql(y,l.ONE))if(b++,y=l.sqr(y),b===d)throw Error("Cannot find square root");let S=rr<<BigInt(d-b-1),x=l.pow(p,S);d=b,p=l.sqr(x),m=l.mul(m,p),h=l.mul(h,x)}return h}}function ace(e){if(e%jZ===BZ)return qZ;if(e%UZ===ZZ)return ice;if(e%MZ===oce)return sce(e);return FZ(e)}function _A(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=cce.reduce((o,n)=>(o[n]="function",o),t);return qs(e,r),e}function lce(e,t,r){if(r<yr)throw Error("invalid exponent, negatives unsupported");if(r===yr)return e.ONE;if(r===rr)return t;let o=e.ONE,n=t;while(r>yr){if(r&rr)o=e.mul(o,n);n=e.sqr(n),r>>=rr}return o}function Bd(e,t,r=!1){let o=Array(t.length).fill(r?e.ZERO:void 0),n=t.reduce((s,a,l)=>{if(e.is0(a))return s;return o[l]=s,e.mul(s,a)},e.ONE),i=e.inv(n);return t.reduceRight((s,a,l)=>{if(e.is0(a))return s;return o[l]=e.mul(s,o[l]),e.mul(s,a)},i),o}function LZ(e,t){let r=(e.ORDER-rr)/Fs,o=e.pow(t,r),n=e.eql(o,e.ONE),i=e.eql(o,e.ZERO),s=e.eql(o,e.neg(e.ONE));if(!n&&!i&&!s)throw Error("invalid Legendre symbol result");return n?1:i?0:-1}function uce(e,t){if(t!==void 0)Zt(t);let r=t!==void 0?t:e.toString(2).length,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}class JZ{ORDER;BITS;BYTES;isLE;ZERO=yr;ONE=rr;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=yr)throw Error("invalid field: expected ORDER > 0, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")this.sqrt=t.sqrt;if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=t.allowedLengths?.slice();if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=uce(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return gr(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof e);return yr<=e&&e<this.ORDER}is0(e){return e===yr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&rr)===rr}neg(e){return gr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return gr(e*e,this.ORDER)}add(e,t){return gr(e+t,this.ORDER)}sub(e,t){return gr(e-t,this.ORDER)}mul(e,t){return gr(e*t,this.ORDER)}pow(e,t){return lce(this,e,t)}div(e,t){return gr(e*DZ(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 DZ(e,this.ORDER)}sqrt(e){if(!this._sqrt)this._sqrt=ace(this.ORDER);return this._sqrt(this,e)}toBytes(e){return this.isLE?Nd(e,this.BYTES):Uc(e,this.BYTES)}fromBytes(e,t=!1){Re(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?Oi(e):$i(e);if(s)a=gr(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Bd(this,e)}cmov(e,t,r){return r?t:e}}function Zg(e,t={}){return new JZ(e,t)}function KZ(e){if(typeof e!=="bigint")throw Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function EA(e){let t=KZ(e);return t+Math.ceil(t/2)}function HZ(e,t,r=!1){Re(e);let o=e.length,n=KZ(t),i=EA(t);if(o<16||o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?Oi(e):$i(e),a=gr(s,t-rr)+rr;return r?Nd(a,n):Uc(a,n)}var yr,rr,Fs,BZ,jZ,ZZ,nce,UZ,oce,MZ,cce;var jd=v(()=>{Mc();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */yr=BigInt(0),rr=BigInt(1),Fs=BigInt(2),BZ=BigInt(3),jZ=BigInt(4),ZZ=BigInt(5),nce=BigInt(7),UZ=BigInt(8),oce=BigInt(9),MZ=BigInt(16);cce=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"]});function Zd(e,t){let r=t.negate();return e?r:t}function RA(e,t){let r=Bd(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function QZ(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function IA(e,t){QZ(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=Ld(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function VZ(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=Js;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function AA(e){return YZ.get(e)||1}function WZ(e){if(e!==qc)throw Error("invalid wNAF")}class TA{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>qc){if(t&Js)r=r.add(o);o=o.double(),t>>=Js}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=IA(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=IA(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=VZ(r,s,i);if(r=a,u)n=n.add(Zd(p,t[m]));else o=o.add(Zd(d,t[l]))}return WZ(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=IA(e,this.bits);for(let i=0;i<n.windows;i++){if(r===qc)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=VZ(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return WZ(r),o}getPrecomputes(e,t,r){let o=kA.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);kA.set(t,o)}}return o}cached(e,t,r){let o=AA(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=AA(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){QZ(t,this.bits),YZ.set(e,t),kA.delete(e)}hasCache(e){return AA(e)!==1}}function XZ(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>qc||o>qc){if(r&Js)i=i.add(n);if(o&Js)s=s.add(n);n=n.double(),r>>=Js,o>>=Js}return{p1:i,p2:s}}function GZ(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return _A(t),t}else return Zg(e,{isLE:r})}function eU(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>qc))throw Error(`CURVE.${l} must be positive bigint`)}let n=GZ(t.p,r.Fp,o),i=GZ(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function Ug(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var qc,Js,kA,YZ;var $A=v(()=>{Mc();jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */qc=BigInt(0),Js=BigInt(1);kA=new WeakMap,YZ=new WeakMap});function dce(e){return qs(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function tU(e){let t=dce(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s||Ri,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?Mg**BigInt(254):Mg**BigInt(447),b=a?BigInt(8)*Mg**BigInt(251)-Fc:BigInt(4)*Mg**BigInt(445)-Fc,y=h+b+Fc,S=(I)=>gr(I,r),x=_(p);function _(I){return Nd(S(I),d)}function A(I){let R=jg(Re(I,d,"uCoordinate"));if(a)R[31]&=127;return S(Oi(R))}function O(I){return Oi(n(jg(Re(I,d,"scalar"))))}function L(I,R){let k=ee(A(R),O(I));if(k===Ud)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,R,k){let q=S(I*(R-k));return R=S(R-q),k=S(k+q),{x_2:R,x_3:k}}function ee(I,R){Dd("u",I,Ud,r),Dd("scalar",R,h,y);let k=R,q=I,N=Fc,H=Ud,G=I,re=Fc,ae=Ud;for(let be=BigInt(u-1);be>=Ud;be--){let xe=k>>be&Fc;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let Ae=N+H,ke=S(Ae*Ae),_e=N-H,Ue=S(_e*_e),De=ke-Ue,Qe=G+re,St=G-re,Rt=S(St*Ae),Dt=S(Qe*_e),lt=Rt+Dt,Or=Rt-Dt;G=S(lt*lt),re=S(q*S(Or*Or)),N=S(ke*Ue),H=S(De*(ke+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return S(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(I=l(d))=>(Re(I,j.seed,"seed"),I),B={randomSecretKey:T};return Object.freeze({keygen:Ug(T,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}var Ud,Fc,Mg;var rU=v(()=>{Mc();$A();jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ud=BigInt(0),Fc=BigInt(1),Mg=BigInt(2)});class OA{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(en(e),Re(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?e.create().update(t).digest():t);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),kr(o)}update(e){return Ro(this),this.iHash.update(e),this}digestInto(e){Ro(this),Re(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:o,destroyed:n,blockLen:i,outputLen:s}=this;return e=e,e.finished=o,e.destroyed=n,e.blockLen=i,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Jc=(e,t,r)=>new OA(e,t).update(r).digest();var CA=v(()=>{Zr();Jc.create=(e,t)=>new OA(e,t)});function pce(e,t,r){let[[o,n],[i,s]]=t,a=nU(s*e,r),l=nU(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<To,m=d<To;if(p)u=-u;if(m)d=-d;let h=Ld(Math.ceil(vA(r)/2))+Kc;if(u<To||u>=h||d<To||d>=h)throw Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:u,k2neg:m,k2:d}}function zA(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function PA(e,t){let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(Pd(r.lowS,"lowS"),Pd(r.prehash,"prehash"),r.format!==void 0)zA(r.format);return r}function NA(e,t={}){let r=eU("weierstrass",e,t),{Fp:o,Fn:n}=r,i=r.CURVE,{h:s,n:a}=i;qs(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let u=aU(o,n);function d(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function p(T,B,I){let{x:R,y:k}=B.toAffine(),q=o.toBytes(R);if(Pd(I,"isCompressed"),I){d();let N=!o.isOdd(k);return It(sU(N),q)}else return It(Uint8Array.of(4),q,o.toBytes(k))}function m(T){Re(T,void 0,"Point");let{publicKey:B,publicKeyUncompressed:I}=u,R=T.length,k=T[0],q=T.subarray(1);if(R===B&&(k===2||k===3)){let N=o.fromBytes(q);if(!o.isValid(N))throw Error("bad point: is not on curve, wrong x");let H=y(N),G;try{G=o.sqrt(H)}catch(me){let be=me instanceof Error?": "+me.message:"";throw Error("bad point: is not on curve, sqrt error"+be)}d();let re=o.isOdd(G);if((k&1)===1!==re)G=o.neg(G);return{x:N,y:G}}else if(R===I&&k===4){let N=o.BYTES,H=o.fromBytes(q.subarray(0,N)),G=o.fromBytes(q.subarray(N,N*2));if(!S(H,G))throw Error("bad point: is not on curve");return{x:H,y:G}}else throw Error(`bad point: got length ${R}, expected compressed=${B} or uncompressed=${I}`)}let h=t.toBytes||p,b=t.fromBytes||m;function y(T){let B=o.sqr(T),I=o.mul(B,T);return o.add(o.add(I,o.mul(T,i.a)),i.b)}function S(T,B){let I=o.sqr(B),R=y(T);return o.eql(I,R)}if(!S(i.Gx,i.Gy))throw Error("bad curve params: generator point");let x=o.mul(o.pow(i.a,qg),fce),_=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(x,_)))throw Error("bad curve params: a or b");function A(T,B,I=!1){if(!o.isValid(B)||I&&o.is0(B))throw Error(`bad point coordinate ${T}`);return B}function O(T){if(!(T instanceof W))throw Error("Weierstrass Point expected")}function L(T){if(!l||!l.basises)throw Error("no endo");return pce(T,l.basises,n.ORDER)}let z=wA((T,B)=>{let{X:I,Y:R,Z:k}=T;if(o.eql(k,o.ONE))return{x:I,y:R};let q=T.is0();if(B==null)B=q?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(R,B),G=o.mul(k,B);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}),K=wA((T)=>{if(T.is0()){if(t.allowInfinityPoint&&!o.is0(T.Y))return;throw Error("bad point: ZERO")}let{x:B,y:I}=T.toAffine();if(!o.isValid(B)||!o.isValid(I))throw Error("bad point: x or y not field elements");if(!S(B,I))throw Error("bad point: equation left != right");if(!T.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});function P(T,B,I,R,k){return I=new W(o.mul(I.X,T),I.Y,I.Z),B=Zd(R,B),I=Zd(k,I),B.add(I)}class W{static BASE=new W(i.Gx,i.Gy,o.ONE);static ZERO=new W(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(T,B,I){this.X=A("x",T),this.Y=A("y",B,!0),this.Z=A("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(T){let{x:B,y:I}=T||{};if(!T||!o.isValid(B)||!o.isValid(I))throw Error("invalid affine point");if(T instanceof W)throw Error("projective point not allowed");if(o.is0(B)&&o.is0(I))return W.ZERO;return new W(B,I,o.ONE)}static fromBytes(T){let B=W.fromAffine(b(Re(T,void 0,"point")));return B.assertValidity(),B}static fromHex(T){return W.fromBytes(Ms(T))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(T=8,B=!0){if(j.createCache(this,T),!B)this.multiply(qg);return this}assertValidity(){K(this)}hasEvenY(){let{y:T}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(T)}equals(T){O(T);let{X:B,Y:I,Z:R}=this,{X:k,Y:q,Z:N}=T,H=o.eql(o.mul(B,N),o.mul(k,R)),G=o.eql(o.mul(I,N),o.mul(q,R));return H&&G}negate(){return new W(this.X,o.neg(this.Y),this.Z)}double(){let{a:T,b:B}=i,I=o.mul(B,qg),{X:R,Y:k,Z:q}=this,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=o.mul(R,R),ae=o.mul(k,k),me=o.mul(q,q),be=o.mul(R,k);return be=o.add(be,be),G=o.mul(R,q),G=o.add(G,G),N=o.mul(T,G),H=o.mul(I,me),H=o.add(N,H),N=o.sub(ae,H),H=o.add(ae,H),H=o.mul(N,H),N=o.mul(be,N),G=o.mul(I,G),me=o.mul(T,me),be=o.sub(re,me),be=o.mul(T,be),be=o.add(be,G),G=o.add(re,re),re=o.add(G,re),re=o.add(re,me),re=o.mul(re,be),H=o.add(H,re),me=o.mul(k,q),me=o.add(me,me),re=o.mul(me,be),N=o.sub(N,re),G=o.mul(me,ae),G=o.add(G,G),G=o.add(G,G),new W(N,H,G)}add(T){O(T);let{X:B,Y:I,Z:R}=this,{X:k,Y:q,Z:N}=T,H=o.ZERO,G=o.ZERO,re=o.ZERO,ae=i.a,me=o.mul(i.b,qg),be=o.mul(B,k),xe=o.mul(I,q),Ae=o.mul(R,N),ke=o.add(B,I),_e=o.add(k,q);ke=o.mul(ke,_e),_e=o.add(be,xe),ke=o.sub(ke,_e),_e=o.add(B,R);let Ue=o.add(k,N);return _e=o.mul(_e,Ue),Ue=o.add(be,Ae),_e=o.sub(_e,Ue),Ue=o.add(I,R),H=o.add(q,N),Ue=o.mul(Ue,H),H=o.add(xe,Ae),Ue=o.sub(Ue,H),re=o.mul(ae,_e),H=o.mul(me,Ae),re=o.add(H,re),H=o.sub(xe,re),re=o.add(xe,re),G=o.mul(H,re),xe=o.add(be,be),xe=o.add(xe,be),Ae=o.mul(ae,Ae),_e=o.mul(me,_e),xe=o.add(xe,Ae),Ae=o.sub(be,Ae),Ae=o.mul(ae,Ae),_e=o.add(_e,Ae),be=o.mul(xe,_e),G=o.add(G,be),be=o.mul(Ue,_e),H=o.mul(ke,H),H=o.sub(H,be),be=o.mul(ke,xe),re=o.mul(Ue,re),re=o.add(re,be),new W(H,G,re)}subtract(T){return this.add(T.negate())}is0(){return this.equals(W.ZERO)}multiply(T){let{endo:B}=t;if(!n.isValidNot0(T))throw Error("invalid scalar: out of range");let I,R,k=(q)=>j.cached(this,q,(N)=>RA(W,N));if(B){let{k1neg:q,k1:N,k2neg:H,k2:G}=L(T),{p:re,f:ae}=k(N),{p:me,f:be}=k(G);R=ae.add(be),I=P(B.beta,re,me,q,H)}else{let{p:q,f:N}=k(T);I=q,R=N}return RA(W,[I,R])[0]}multiplyUnsafe(T){let{endo:B}=t,I=this;if(!n.isValid(T))throw Error("invalid scalar: out of range");if(T===To||I.is0())return W.ZERO;if(T===Kc)return I;if(j.hasCache(this))return this.multiply(T);if(B){let{k1neg:R,k1:k,k2neg:q,k2:N}=L(T),{p1:H,p2:G}=XZ(W,I,k,N);return P(B.beta,H,G,R,q)}else return j.unsafe(I,T)}toAffine(T){return z(this,T)}isTorsionFree(){let{isTorsionFree:T}=t;if(s===Kc)return!0;if(T)return T(W,this);return j.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:T}=t;if(s===Kc)return this;if(T)return T(W,this);return this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(T=!0){return Pd(T,"isCompressed"),this.assertValidity(),h(W,this,T)}toHex(T=!0){return Us(this.toBytes(T))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let ee=n.BITS,j=new TA(W,t.endo?Math.ceil(ee/2):ee);return W.BASE.precompute(8),W}function sU(e){return Uint8Array.of(e?2:3)}function aU(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function mce(e,t={}){let{Fn:r}=e,o=t.randomBytes||Ri,n=Object.assign(aU(e.Fp,r),{seed:EA(r.ORDER)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h=o(n.seed)){return HZ(Re(h,n.seed,"seed"),r.ORDER)}function l(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n;if(!jc(h))return;if("_lengths"in r&&r._lengths||b===y)return;let x=Re(h,void 0,"key").length;return x===y||x===S}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=Ug(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function DA(e,t,r={}){en(t),qs(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let o=r.randomBytes||Ri,n=r.hmac||((I,R)=>Jc(t,I,R)),{Fp:i,Fn:s}=e,{ORDER:a,BITS:l}=s,{keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h}=mce(e,r),b={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*iU<i.ORDER;function S(I){let R=a>>Kc;return I>R}function x(I,R){if(!s.isValidNot0(R))throw Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return R}function _(){if(y)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(I,R){zA(R);let k=h.signature,q=R==="compact"?k:R==="recovered"?k+1:void 0;return Re(I,q)}class O{r;s;recovery;constructor(I,R,k){if(this.r=x("r",I),this.s=x("s",R),k!=null){if(_(),![0,1,2,3].includes(k))throw Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(I,R=b.format){A(I,R);let k;if(R==="der"){let{r:G,s:re}=Pi.toSig(Re(I));return new O(G,re)}if(R==="recovered")k=I[0],R="compact",I=I.subarray(1);let q=h.signature/2,N=I.subarray(0,q),H=I.subarray(q,q*2);return new O(s.fromBytes(N),s.fromBytes(H),k)}static fromHex(I,R){return this.fromBytes(Ms(I),R)}assertRecovery(){let{recovery:I}=this;if(I==null)throw Error("invalid recovery id: must be present");return I}addRecoveryBit(I){return new O(this.r,this.s,I)}recoverPublicKey(I){let{r:R,s:k}=this,q=this.assertRecovery(),N=q===2||q===3?R+a:R;if(!i.isValid(N))throw Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(N),G=e.fromBytes(It(sU((q&1)===0),H)),re=s.inv(N),ae=z(Re(I,void 0,"msgHash")),me=s.create(-ae*re),be=s.create(k*re),xe=e.BASE.multiplyUnsafe(me).add(G.multiplyUnsafe(be));if(xe.is0())throw Error("invalid recovery: point at infinify");return xe.assertValidity(),xe}hasHighS(){return S(this.s)}toBytes(I=b.format){if(zA(I),I==="der")return Ms(Pi.hexFromSig(this));let{r:R,s:k}=this,q=s.toBytes(R),N=s.toBytes(k);if(I==="recovered")return _(),It(Uint8Array.of(this.assertRecovery()),q,N);return It(q,N)}toHex(I){return Us(this.toBytes(I))}}let L=r.bits2int||function(R){if(R.length>8192)throw Error("input is too large");let k=$i(R),q=R.length*8-l;return q>0?k>>BigInt(q):k},z=r.bits2int_modN||function(R){return s.create(L(R))},K=Ld(l);function P(I){return Dd("num < 2^"+l,I,To,K),s.toBytes(I)}function W(I,R){return Re(I,void 0,"message"),R?Re(t(I),void 0,"prehashed message"):I}function ee(I,R,k){let{lowS:q,prehash:N,extraEntropy:H}=PA(k,b);I=W(I,N);let G=z(I),re=s.fromBytes(R);if(!s.isValidNot0(re))throw Error("invalid private key");let ae=[P(re),P(G)];if(H!=null&&H!==!1){let Ae=H===!0?o(h.secretKey):H;ae.push(Re(Ae,void 0,"extraEntropy"))}let me=It(...ae),be=G;function xe(Ae){let ke=L(Ae);if(!s.isValidNot0(ke))return;let _e=s.inv(ke),Ue=e.BASE.multiply(ke).toAffine(),De=s.create(Ue.x);if(De===To)return;let Qe=s.create(_e*s.create(be+De*re));if(Qe===To)return;let St=(Ue.x===De?0:2)|Number(Ue.y&Kc),Rt=Qe;if(q&&S(Qe))Rt=s.neg(Qe),St^=1;return new O(De,Rt,y?void 0:St)}return{seed:me,k2sig:xe}}function j(I,R,k={}){let{seed:q,k2sig:N}=ee(I,R,k);return NZ(t.outputLen,s.BYTES,n)(q,N).toBytes(k.format)}function T(I,R,k,q={}){let{lowS:N,prehash:H,format:G}=PA(q,b);if(k=Re(k,void 0,"publicKey"),R=W(R,H),!jc(I)){let re=I instanceof O?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+re)}A(I,G);try{let re=O.fromBytes(I,G),ae=e.fromBytes(k);if(N&&re.hasHighS())return!1;let{r:me,s:be}=re,xe=z(R),Ae=s.inv(be),ke=s.create(xe*Ae),_e=s.create(me*Ae),Ue=e.BASE.multiplyUnsafe(ke).add(ae.multiplyUnsafe(_e));if(Ue.is0())return!1;return s.create(Ue.x)===me}catch(re){return!1}}function B(I,R,k={}){let{prehash:q}=PA(k,b);return R=W(R,q),O.fromBytes(I,"recovered").recoverPublicKey(R).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:p,utils:m,lengths:h,Point:e,sign:j,verify:T,recoverPublicKey:B,Signature:O,hash:t})}var nU=(e,t)=>(e+(e>=0?t:-t)/iU)/t,oU,Pi,To,Kc,iU,qg,fce;var cU=v(()=>{CA();Zr();Mc();$A();jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */oU=class oU extends Error{constructor(e=""){super(e)}};Pi={Err:oU,_tlv:{encode:(e,t)=>{let{Err:r}=Pi;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=zd(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?zd(n.length/2|128):"";return zd(e)+i+n+t},decode(e,t){let{Err:r}=Pi,o=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=Pi;if(e<To)throw new t("integer: negative integers are not allowed");let r=zd(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}=Pi;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 $i(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=Pi,n=Re(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=Pi,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}},To=BigInt(0),Kc=BigInt(1),iU=BigInt(2),qg=BigInt(3),fce=BigInt(4)});function lU(e,t,r){return e&t^~e&r}function uU(e,t,r){return e&t^e&r^t&r}class Fg{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,o){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Lg(this.buffer)}update(e){Ro(this),Re(e);let{view:t,buffer:r,blockLen:o}=this,n=e.length;for(let i=0;i<n;){let s=Math.min(o-this.pos,n-i);if(s===o){let a=Lg(e);for(;o<=n-i;i+=o)this.process(a,i);continue}if(r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===o)this.process(t,0),this.pos=0}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ro(this),Ng(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:o,isLE:n}=this,{pos:i}=this;if(t[i++]=128,kr(this.buffer.subarray(i)),this.padOffset>o-i)this.process(r,0),i=0;for(let d=i;d<o;d++)t[d]=0;r.setBigUint64(o-8,BigInt(this.length*8),n),this.process(r,0);let s=Lg(e),a=this.outputLen;if(a%4)throw Error("_sha2: outputLen must be aligned to 32bit");let l=a/4,u=this.get();if(l>u.length)throw Error("_sha2: outputLen bigger than state");for(let d=0;d<l;d++)s.setUint32(4*d,u[d],n)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:o,finished:n,destroyed:i,pos:s}=this;if(e.destroyed=i,e.finished=n,e.length=o,e.pos=s,o%t)e.buffer.set(r);return e}clone(){return this._cloneInto()}}var $o,Ht;var dU=v(()=>{Zr();$o=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ht=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428])});function hce(e,t=!1){if(t)return{h:Number(e&Jg),l:Number(e>>pU&Jg)};return{h:Number(e>>pU&Jg)|0,l:Number(e&Jg)|0}}function Kg(e,t=!1){let r=e.length,o=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=hce(e[i],t);[o[i],n[i]]=[s,a]}return[o,n]}function Hn(e,t,r,o){let n=(t>>>0)+(o>>>0);return{h:e+r+(n/4294967296|0)|0,l:n|0}}var Jg,pU,LA=(e,t,r)=>e>>>r,BA=(e,t,r)=>e<<32-r|t>>>r,Ks=(e,t,r)=>e>>>r|t<<32-r,Hs=(e,t,r)=>e<<32-r|t>>>r,Md=(e,t,r)=>e<<64-r|t>>>r-32,qd=(e,t,r)=>e>>>r-32|t<<64-r,fU=(e,t,r)=>e<<r|t>>>32-r,mU=(e,t,r)=>t<<r|e>>>32-r,hU=(e,t,r)=>t<<r-32|e>>>64-r,gU=(e,t,r)=>e<<r-32|t>>>64-r,yU=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),bU=(e,t,r,o)=>t+r+o+(e/4294967296|0)|0,SU=(e,t,r,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0),vU=(e,t,r,o,n)=>t+r+o+n+(e/4294967296|0)|0,wU=(e,t,r,o,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(o>>>0)+(n>>>0),xU=(e,t,r,o,n,i)=>t+r+o+n+i+(e/4294967296|0)|0;var jA=v(()=>{Jg=BigInt(4294967295),pU=BigInt(32)});var yce,zi,_U,EU,IU,bce,Sce,Ni,Di,kU,AU,Hg,RU;var ZA=v(()=>{dU();jA();Zr();yce=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]),zi=new Uint32Array(64);_U=class _U extends Fg{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:o,E:n,F:i,G:s,H:a}=this;return[e,t,r,o,n,i,s,a]}set(e,t,r,o,n,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)zi[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=zi[d-15],m=zi[d-2],h=bn(p,7)^bn(p,18)^p>>>3,b=bn(m,17)^bn(m,19)^m>>>10;zi[d]=b+zi[d-7]+h+zi[d-16]|0}let{A:r,B:o,C:n,D:i,E:s,F:a,G:l,H:u}=this;for(let d=0;d<64;d++){let p=bn(s,6)^bn(s,11)^bn(s,25),m=u+p+lU(s,a,l)+yce[d]+zi[d]|0,b=(bn(r,2)^bn(r,13)^bn(r,22))+uU(r,o,n)|0;u=l,l=a,a=s,s=i+m|0,i=n,n=o,o=r,r=m+b|0}r=r+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,o,n,i,s,a,l,u)}roundClean(){kr(zi)}destroy(){this.set(0,0,0,0,0,0,0,0),kr(this.buffer)}};EU=class EU extends _U{A=$o[0]|0;B=$o[1]|0;C=$o[2]|0;D=$o[3]|0;E=$o[4]|0;F=$o[5]|0;G=$o[6]|0;H=$o[7]|0;constructor(){super(32)}};IU=(()=>Kg(["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))))(),bce=(()=>IU[0])(),Sce=(()=>IU[1])(),Ni=new Uint32Array(80),Di=new Uint32Array(80);kU=class kU extends Fg{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:o,Ch:n,Cl:i,Dh:s,Dl:a,Eh:l,El:u,Fh:d,Fl:p,Gh:m,Gl:h,Hh:b,Hl:y}=this;return[e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y]}set(e,t,r,o,n,i,s,a,l,u,d,p,m,h,b,y){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=o|0,this.Ch=n|0,this.Cl=i|0,this.Dh=s|0,this.Dl=a|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=p|0,this.Gh=m|0,this.Gl=h|0,this.Hh=b|0,this.Hl=y|0}process(e,t){for(let _=0;_<16;_++,t+=4)Ni[_]=e.getUint32(t),Di[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Ni[_-15]|0,O=Di[_-15]|0,L=Ks(A,O,1)^Ks(A,O,8)^LA(A,O,7),z=Hs(A,O,1)^Hs(A,O,8)^BA(A,O,7),K=Ni[_-2]|0,P=Di[_-2]|0,W=Ks(K,P,19)^Md(K,P,61)^LA(K,P,6),ee=Hs(K,P,19)^qd(K,P,61)^BA(K,P,6),j=SU(z,ee,Di[_-7],Di[_-16]),T=vU(j,L,W,Ni[_-7],Ni[_-16]);Ni[_]=T|0,Di[_]=j|0}let{Ah:r,Al:o,Bh:n,Bl:i,Ch:s,Cl:a,Dh:l,Dl:u,Eh:d,El:p,Fh:m,Fl:h,Gh:b,Gl:y,Hh:S,Hl:x}=this;for(let _=0;_<80;_++){let A=Ks(d,p,14)^Ks(d,p,18)^Md(d,p,41),O=Hs(d,p,14)^Hs(d,p,18)^qd(d,p,41),L=d&m^~d&b,z=p&h^~p&y,K=wU(x,O,z,Sce[_],Di[_]),P=xU(K,S,A,L,bce[_],Ni[_]),W=K|0,ee=Ks(r,o,28)^Md(r,o,34)^Md(r,o,39),j=Hs(r,o,28)^qd(r,o,34)^qd(r,o,39),T=r&n^r&s^n&s,B=o&i^o&a^i&a;S=b|0,x=y|0,b=m|0,y=h|0,m=d|0,h=p|0,{h:d,l:p}=Hn(l|0,u|0,P|0,W|0),l=s|0,u=a|0,s=n|0,a=i|0,n=r|0,i=o|0;let I=yU(W,j,B);r=bU(I,P,ee,T),o=I|0}({h:r,l:o}=Hn(this.Ah|0,this.Al|0,r|0,o|0)),{h:n,l:i}=Hn(this.Bh|0,this.Bl|0,n|0,i|0),{h:s,l:a}=Hn(this.Ch|0,this.Cl|0,s|0,a|0),{h:l,l:u}=Hn(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:p}=Hn(this.Eh|0,this.El|0,d|0,p|0),{h:m,l:h}=Hn(this.Fh|0,this.Fl|0,m|0,h|0),{h:b,l:y}=Hn(this.Gh|0,this.Gl|0,b|0,y|0),{h:S,l:x}=Hn(this.Hh|0,this.Hl|0,S|0,x|0),this.set(r,o,n,i,s,a,l,u,d,p,m,h,b,y,S,x)}roundClean(){kr(Ni,Di)}destroy(){kr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};AU=class AU extends kU{Ah=Ht[0]|0;Al=Ht[1]|0;Bh=Ht[2]|0;Bl=Ht[3]|0;Ch=Ht[4]|0;Cl=Ht[5]|0;Dh=Ht[6]|0;Dl=Ht[7]|0;Eh=Ht[8]|0;El=Ht[9]|0;Fh=Ht[10]|0;Fl=Ht[11]|0;Gh=Ht[12]|0;Gl=Ht[13]|0;Hh=Ht[14]|0;Hl=Ht[15]|0;constructor(){super(48)}};Hg=Zc(()=>new EU,Ti(1)),RU=Zc(()=>new AU,Ti(2))});function _ce(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=$U,a=e*e%i*e%i,l=tn(a,TU,i)*a%i,u=tn(l,vce,i)*e%i,d=tn(u,xce,i)*u%i,p=tn(d,t,i)*d%i,m=tn(p,r,i)*p%i,h=tn(m,o,i)*m%i,b=tn(h,n,i)*h%i,y=tn(b,n,i)*h%i,S=tn(y,t,i)*d%i;return{pow_p_5_8:tn(S,TU,i)*e%i,b2:a}}function Ece(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var vce,TU,wce,xce,QCe,$U,OU;var CU=v(()=>{jd();rU();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */vce=BigInt(1),TU=BigInt(2),wce=BigInt(3),xce=BigInt(5),QCe=BigInt(8),$U=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");OU=(()=>{let e=$U;return tU({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=_ce(t);return gr(tn(r,wce,e)*o,e)},adjustScalarBytes:Ece})})()});var Ice,kce,Ace,UA,Rce,PU;var zU=v(()=>{ZA();cU();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ice=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),kce=(()=>({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")}))(),Ace=NA(Ice),UA=DA(Ace,Hg),Rce=NA(kce),PU=DA(Rce,RU)});function DU(e,t,r){if(en(e),r===void 0)r=new Uint8Array(e.outputLen);return Jc(e,r,t)}function LU(e,t,r,o=32){en(e),Zt(o,"length");let n=e.outputLen;if(o>255*n)throw Error("Length must be <= 255*HashLen");let i=Math.ceil(o/n);if(r===void 0)r=NU;else Re(r,void 0,"info");let s=new Uint8Array(i*n),a=Jc.create(e,t),l=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)MA[0]=d+1,l.update(d===0?NU:u).update(r).update(MA).digestInto(u),s.set(u,n*d),a._cloneInto(l);return a.destroy(),l.destroy(),kr(u,MA),s.slice(0,o)}var MA,NU;var BU=v(()=>{CA();Zr();MA=Uint8Array.of(0),NU=Uint8Array.of()});function Dce(e,t=24){let r=new Uint32Array(10);for(let o=24-t;o<24;o++){for(let s=0;s<10;s++)r[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,l=(s+2)%10,u=r[l],d=r[l+1],p=jU(u,d,1)^r[a],m=ZU(u,d,1)^r[a+1];for(let h=0;h<50;h+=10)e[s+h]^=p,e[s+h+1]^=m}let n=e[2],i=e[3];for(let s=0;s<24;s++){let a=MU[s],l=jU(n,i,a),u=ZU(n,i,a),d=UU[s];n=e[d],i=e[d+1],e[d]=l,e[d+1]=u}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)r[a]=e[s+a];for(let a=0;a<10;a++)e[s+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=zce[o],e[1]^=Nce[o]}kr(r)}class Vg{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,t,r,o=!1,n=24){if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=o,this.rounds=n,Zt(r,"outputLen"),!(0<e&&e<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Dg(this.state)}clone(){return this._cloneInto()}keccak(){yA(this.state32),Dce(this.state32,this.rounds),yA(this.state32),this.posOut=0,this.pos=0}update(e){Ro(this),Re(e);let{blockLen:t,state:r}=this,o=e.length;for(let n=0;n<o;){let i=Math.min(t-this.pos,o-n);for(let s=0;s<i;s++)r[this.pos++]^=e[n++];if(this.pos===t)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:o}=this;if(e[r]^=t,(t&128)!==0&&r===o-1)this.keccak();e[o-1]^=128,this.keccak()}writeInto(e){Ro(this,!1),Re(e),this.finish();let t=this.state,{blockLen:r}=this;for(let o=0,n=e.length;o<n;){if(this.posOut>=r)this.keccak();let i=Math.min(r-this.posOut,n-o);e.set(t.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ng(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,kr(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:o,rounds:n,enableXOF:i}=this;return e||=new Vg(t,r,o,i,n),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}var Tce,Fd,$ce,Oce,Cce,Pce,UU,MU,qU,FU,zce,Nce,jU=(e,t,r)=>r>32?hU(e,t,r):fU(e,t,r),ZU=(e,t,r)=>r>32?gU(e,t,r):mU(e,t,r),JU=(e,t,r,o={})=>Zc(()=>new Vg(t,e,r),o),Vs,KU,HU=(e,t,r,o={})=>Zc((n={})=>new Vg(t,e,n.dkLen===void 0?r:n.dkLen,!0),o),VU,Vn;var Wg=v(()=>{jA();Zr();Tce=BigInt(0),Fd=BigInt(1),$ce=BigInt(2),Oce=BigInt(7),Cce=BigInt(256),Pce=BigInt(113),UU=[],MU=[],qU=[];for(let e=0,t=Fd,r=1,o=0;e<24;e++){[r,o]=[o,(2*r+3*o)%5],UU.push(2*(5*o+r)),MU.push((e+1)*(e+2)/2%64);let n=Tce;for(let i=0;i<7;i++)if(t=(t<<Fd^(t>>Oce)*Pce)%Cce,t&$ce)n^=Fd<<(Fd<<BigInt(i))-Fd;qU.push(n)}FU=Kg(qU,!0),zce=FU[0],Nce=FU[1];Vs=JU(6,136,32,Ti(8)),KU=JU(6,72,64,Ti(10)),VU=HU(31,168,16,Ti(11)),Vn=HU(31,136,32,Ti(12))});function qA(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Error("wrong u32 integer:"+e);return e}function GU(e){return qA(e),(e&e-1)===0&&e!==0}function FA(e,t){qA(e);let r=0;for(let o=0;o<t;o++,e>>>=1)r=r<<1|e&1;return r}function QU(e){return qA(e),31-Math.clz32(e)}function WU(e){let t=e.length;if(t<2||!GU(t))throw Error("n must be a power of 2 and greater than 1. Got "+t);let r=QU(t);for(let o=0;o<t;o++){let n=FA(o,r);if(o<n){let i=e[o];e[o]=e[n],e[n]=i}}return e}var JA=(e,t)=>{let{N:r,roots:o,dit:n,invertButterflies:i=!1,skipStages:s=0,brp:a=!0}=t,l=QU(r);if(!GU(r))throw Error("FFT: Polynomial size should be power of two");let u=n!==i;return(d)=>{if(d.length!==r)throw Error("FFT: wrong Polynomial length");if(n&&a)WU(d);for(let p=0,m=1;p<l-s;p++){let h=n?p+1+s:l-p,b=1<<h,y=b>>1,S=r>>h;for(let x=0;x<r;x+=b)for(let _=0,A=m++;_<y;_++){let O=i?n?r-A:A:_*S,L=x+_,z=x+_+y,K=o[O],P=d[z],W=d[L];if(u){let ee=e.mul(P,K);d[L]=e.add(W,ee),d[z]=e.sub(W,ee)}else if(i)d[L]=e.add(P,W),d[z]=e.mul(e.sub(P,W),K);else d[L]=e.add(W,P),d[z]=e.mul(e.sub(W,P),K)}}if(!n&&a)WU(d);return d}};var YU=()=>{};function Gg(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function XU(e){return Uint8Array.from(e)}function Ws(e,...t){let r=(n)=>typeof n==="number"?n:n.bytesLen,o=t.reduce((n,i)=>n+r(i),0);return{bytesLen:o,encode:(n)=>{let i=new Uint8Array(o);for(let s=0,a=0;s<t.length;s++){let l=t[s],u=r(l),d=typeof l==="number"?n[s]:l.encode(n[s]);if(Re(d,u,e),i.set(d,a),typeof l!=="number")d.fill(0);a+=u}return i},decode:(n)=>{Re(n,o,e);let i=[];for(let s of t){let a=r(s),l=n.subarray(0,a);i.push(typeof s==="number"?l:s.decode(l)),n=n.subarray(a)}return i}}}function Qg(e,t){let r=t*e.bytesLen;return{bytesLen:r,encode:(o)=>{if(o.length!==t)throw Error(`vecCoder.encode: wrong length=${o.length}. Expected: ${t}`);let n=new Uint8Array(r);for(let i=0,s=0;i<o.length;i++){let a=e.encode(o[i]);n.set(a,s),a.fill(0),s+=a.length}return n},decode:(o)=>{Re(o,r);let n=[];for(let i=0;i<o.length;i+=e.bytesLen)n.push(e.decode(o.subarray(i,i+e.bytesLen)));return n}}}function Pt(...e){for(let t of e)if(Array.isArray(t))for(let r of t)r.fill(0);else t.fill(0)}function KA(e){return(1<<e)-1}var Wn,p1e;var Yg=v(()=>{Zr();Zr();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */Wn=Ri;p1e=Uint8Array.of()});var e6=(e)=>{let{newPoly:t,N:r,Q:o,F:n,ROOT_OF_UNITY:i,brvBits:s,isKyber:a}=e,l=(_,A=o)=>{let O=_%A|0;return(O>=0?O|0:A+O|0)|0},u=(_,A=o)=>{let O=l(_,A)|0;return(O>A>>1?O-A|0:O)|0};function d(){let _=t(r);for(let A=0;A<r;A++){let O=FA(A,s),L=BigInt(i)**BigInt(O)%BigInt(o);_[A]=Number(L)|0}return _}let p=d(),m={add:(_,A)=>l((_|0)+(A|0))|0,sub:(_,A)=>l((_|0)-(A|0))|0,mul:(_,A)=>l((_|0)*(A|0))|0,inv:(_)=>{throw Error("not implemented")}},h={N:r,roots:p,invertButterflies:!0,skipStages:a?1:0,brp:!1},b=JA(m,{dit:!1,...h}),y=JA(m,{dit:!0,...h});return{mod:l,smod:u,nttZetas:p,NTT:{encode:(_)=>b(_),decode:(_)=>{y(_);for(let A=0;A<_.length;A++)_[A]=l(n*_[A]);return _}},bitsCoder:(_,A)=>{let O=KA(_),L=_*(r/8);return{bytesLen:L,encode:(z)=>{let K=new Uint8Array(L);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=(A.encode(z[P])&O)<<ee,ee+=_;for(;ee>=8;ee-=8,W>>=8)K[j++]=W&KA(ee)}return K},decode:(z)=>{let K=t(r);for(let P=0,W=0,ee=0,j=0;P<z.length;P++){W|=z[P]<<ee,ee+=8;for(;ee>=_;ee-=_,W>>=_)K[j++]=A.decode(W&O)}return K}}}}},Lce=(e)=>(t,r)=>{if(!r)r=e.blockLen;let o=new Uint8Array(t.length+2);o.set(t);let n=t.length,i=new Uint8Array(r),s=e.create({}),a=0,l=0;return{stats:()=>({calls:a,xofs:l}),get:(u,d)=>(o[n+0]=u,o[n+1]=d,s.destroy(),s=e.create({}).update(o),a++,()=>(l++,s.xofInto(i))),clean:()=>{s.destroy(),Pt(i,o)}}},t6;var r6=v(()=>{YU();Wg();Yg();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */t6=Lce(VU)});function Qs(e,t){for(let r=0;r<nr;r++)e[r]=Hd(e[r]+t[r])}function qce(e,t){for(let r=0;r<nr;r++)e[r]=Hd(e[r]-t[r])}function Fce(e,t,r,o,n){let i=Hd(t*o*n+e*r),s=Hd(e*o+t*r);return{c0:i,c1:s}}function Xg(e,t){for(let r=0;r<nr/2;r++){let o=Zce[64+(r>>1)];if(r&1)o=-o;let{c0:n,c1:i}=Fce(e[2*r+0],e[2*r+1],t[2*r+0],t[2*r+1],o);e[2*r+0]=n,e[2*r+1]=i}return e}function n6(e){let t=new Uint16Array(nr);for(let r=0;r<nr;){let o=e();if(o.length%3)throw Error("SampleNTT: unaligned block");for(let n=0;r<nr&&n+3<=o.length;n+=3){let i=(o[n+0]>>0|o[n+1]<<8)&4095,s=(o[n+1]>>4|o[n+2]<<4)&4095;if(i<Oo)t[r++]=i;if(r<nr&&s<Oo)t[r++]=s}}return t}function Kd(e,t,r,o){let n=e(o*nr/4,t,r),i=new Uint16Array(nr),s=Dg(n),a=0;for(let l=0,u=0,d=0,p=0;l<s.length;l++){let m=s[l];for(let h=0;h<32;h++)if(d+=m&1,m>>=1,a+=1,a===o)p=d,d=0;else if(a===2*o)i[u++]=Hd(p-d),d=0,a=0}if(a)throw Error(`sampleCBD: leftover bits: ${a}`);return i}function VA(e){let t=Jce(e),{HASH256:r,HASH512:o,KDF:n}=e,{secretCoder:i,lengths:s}=t,a=Ws("secretKey",s.secretKey,s.publicKey,32,32),l=32,u=64;return{info:{type:"ml-kem"},lengths:{...s,seed:64,msg:32,msgRand:32,secretKey:a.bytesLen},keygen:(d=Wn(64))=>{Re(d,64,"seed");let{publicKey:p,secretKey:m}=t.keygen(d.subarray(0,32)),h=r(p),b=a.encode([m,p,h,d.subarray(32)]);return Pt(m,h),{publicKey:p,secretKey:b}},getPublicKey:(d)=>{let[p,m,h,b]=a.decode(d);return Uint8Array.from(m)},encapsulate:(d,p=Wn(32))=>{Re(d,s.publicKey,"publicKey"),Re(p,32,"message");let m=d.subarray(0,384*e.K),h=i.encode(i.decode(XU(m)));if(!Gg(h,m))throw Pt(h),Error("ML-KEM.encapsulate: wrong publicKey modulus");Pt(h);let b=o.create().update(p).update(r(d)).digest(),y=t.encrypt(d,p,b.subarray(32,64));return Pt(b.subarray(32)),{cipherText:y,sharedSecret:b.subarray(0,32)}},decapsulate:(d,p)=>{Re(p,a.bytesLen,"secretKey"),Re(d,s.cipherText,"cipherText");let m=a.bytesLen-96,h=m+32,b=r(p.subarray(m/2,h));if(!Gg(b,p.subarray(h,h+32)))throw Error("invalid secretKey: hash check failed");let[y,S,x,_]=a.decode(p),A=t.decrypt(d,y),O=o.create().update(A).update(x).digest(),L=O.subarray(0,32),z=t.encrypt(S,A,O.subarray(32,64)),K=Gg(d,z),P=n.create({dkLen:32}).update(_).update(d).digest();return Pt(A,z,!K?L:P),K?L:P}}}function Kce(e,t,r){return Vn.create({dkLen:e}).update(t).update(new Uint8Array([r])).digest()}var nr=256,Oo=3329,Bce=3303,jce=17,Hd,Zce,Gs,Uce,HA,Mce=(e)=>{if(e>=12)return{encode:(r)=>r,decode:(r)=>r};let t=2**(e-1);return{encode:(r)=>((r<<e)+Oo/2)/Oo,decode:(r)=>r*Oo+t>>>e}},Jd=(e)=>Uce(e,Mce(e)),Jce=(e)=>{let{K:t,PRF:r,XOF:o,HASH512:n,ETA1:i,ETA2:s,du:a,dv:l}=e,u=Jd(1),d=Jd(l),p=Jd(a),m=Ws("publicKey",Qg(Jd(12),t),32),h=Qg(Jd(12),t),b=Ws("ciphertext",Qg(p,t),d),y=Ws("seed",32,32);return{secretCoder:h,lengths:{secretKey:h.bytesLen,publicKey:m.bytesLen,cipherText:b.bytesLen},keygen:(S)=>{Re(S,32,"seed");let x=new Uint8Array(33);x.set(S),x[32]=t;let _=n(x),[A,O]=y.decode(_),L=[],z=[];for(let W=0;W<t;W++)L.push(Gs.encode(Kd(r,O,W,i)));let K=o(A);for(let W=0;W<t;W++){let ee=Gs.encode(Kd(r,O,t+W,i));for(let j=0;j<t;j++){let T=n6(K.get(j,W));Qs(ee,Xg(T,L[j]))}z.push(ee)}K.clean();let P={publicKey:m.encode([z,A]),secretKey:h.encode(L)};return Pt(A,O,L,z,x,_),P},encrypt:(S,x,_)=>{let[A,O]=m.decode(S),L=[];for(let j=0;j<t;j++)L.push(Gs.encode(Kd(r,_,j,i)));let z=o(O),K=new Uint16Array(nr),P=[];for(let j=0;j<t;j++){let T=Kd(r,_,t+j,s),B=new Uint16Array(nr);for(let I=0;I<t;I++){let R=n6(z.get(j,I));Qs(B,Xg(R,L[I]))}Qs(T,Gs.decode(B)),P.push(T),Qs(K,Xg(A[j],L[j])),Pt(B)}z.clean();let W=Kd(r,_,2*t,s);Qs(W,Gs.decode(K));let ee=u.decode(x);return Qs(ee,W),Pt(A,L,K,W),b.encode([P,ee])},decrypt:(S,x)=>{let[_,A]=b.decode(S),O=h.decode(x),L=new Uint16Array(nr);for(let z=0;z<t;z++)Qs(L,Xg(O[z],Gs.encode(_[z])));return qce(A,Gs.decode(L)),Pt(L,O,_),u.encode(A)}}},WA,_1e,Vd,o6;var i6=v(()=>{Wg();Zr();r6();Yg();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */({mod:Hd,nttZetas:Zce,NTT:Gs,bitsCoder:Uce}=e6({N:nr,Q:Oo,F:Bce,ROOT_OF_UNITY:jce,newPoly:(e)=>new Uint16Array(e),brvBits:7,isKyber:!0})),HA={512:{N:nr,Q:Oo,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:nr,Q:Oo,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:nr,Q:Oo,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}};WA={HASH256:Vs,HASH512:KU,KDF:Vn,XOF:t6,PRF:Kce},_1e=VA({...WA,...HA[512]}),Vd=VA({...WA,...HA[768]}),o6=VA({...WA,...HA[1024]})});function Hce(e,t=!1){let{lengths:r,keygen:o}=e;if(t){let i=e.Point.Fn;if(!i)throw Error("No Point.Fn");o=(s=Wn(r.seed))=>{Re(s,r.seed,"seed");let a=i.isLE?Oi(s):$i(s),l=i.toBytes(i.create(a));return{secretKey:l,publicKey:e.getPublicKey(l)}}}return{lengths:{secretKey:r.secretKey,publicKey:r.publicKey,seed:r.seed},keygen:o,getPublicKey:(n)=>e.getPublicKey(n)}}function GA(e,t=!1){let r=Hce(e,t);if(!e.getSharedSecret)throw Error("wrong curve");return{lengths:{...r.lengths,msg:r.lengths.seed,cipherText:r.lengths.publicKey},keygen:r.keygen,getPublicKey:r.getPublicKey,encapsulate(o,n=Wn(e.lengths.seed)){let i=this.keygen(n).secretKey,s=this.decapsulate(o,i),a=e.getPublicKey(i);return Pt(i),{sharedSecret:s,cipherText:a}},decapsulate(o,n){let i=e.getSharedSecret(n,o);return e.lengths.publicKeyHasPrefix?i.subarray(1):i}}}function Wd(e,t){return Ws(t,...e.map((r)=>{if(typeof r.lengths[t]!=="number")throw Error("wrong length: "+t);return r.lengths[t]}))}function QA(e){return(t,r)=>e(t,{dkLen:r})}function Vce(e,t,...r){let o=Wd(r,"seed"),n=Wd(r,"publicKey");if(e===void 0)e=o.bytesLen;Zt(e);function i(s){Re(s,e);let a=o.decode(t(s,o.bytesLen)),l=r.map((p,m)=>p.keygen(a[m])),u=l.map((p)=>p.secretKey),d=l.map((p)=>p.publicKey);return{secretKey:u,publicKey:d}}return{info:{lengths:{seed:e,publicKey:n.bytesLen,secretKey:e}},getPublicKey(s){return this.keygen(s).publicKey},keygen(s=Wn(e)){let{publicKey:a,secretKey:l}=i(s),u=n.encode(a);return Pt(a),Pt(l),{secretKey:s,publicKey:u}},expandDecapsulationKey:i,realSeedLen:e}}function ey(e,t,r,o,...n){let i=Vce(e,r,...n),s=Wd(n,"cipherText"),a=Wd(n,"publicKey"),l=Wd(n,"msg");if(t===void 0)t=l.bytesLen;return Zt(t),{lengths:{...i.info.lengths,msg:t,msgRand:l.bytesLen,cipherText:s.bytesLen},getPublicKey:i.getPublicKey,keygen:i.keygen,encapsulate(u,d=Wn(l.bytesLen)){let p=a.decode(u),m=l.decode(d),h=n.map((x,_)=>x.encapsulate(p[_],m[_])),b=h.map((x)=>x.sharedSecret),y=h.map((x)=>x.cipherText),S={sharedSecret:o(p,y,b),cipherText:s.encode(y)};return Pt(b,y),S},decapsulate(u,d){let p=s.decode(u),{publicKey:m,secretKey:h}=i.expandDecapsulationKey(d),b=n.map((y,S)=>y.decapsulate(p[S],h[S]));return o(m,p,b)}}}function s6(e,t,r,o,n){return en(o),en(n),ey(32,32,QA(o),(i,s,a)=>n(It(a[0],a[1],s[1],i[1],Ci(e))),t,r)}function Wce(e,t,r,o,n){return en(o),en(n),ey(32,32,QA(o),(i,s,a)=>{let l=It(a[0],a[1],s[0],i[0],s[1],i[1],Ci(e)),u=32,d=It(Ci("hybrid_prk"),l),p=DU(n,d),m=It(Uc(32,2),Ci("shared_secret"),Ci("")),h=LU(n,p,m,32);return Pt(p,m,d,l),h},t,r)}function Qce(e,t,r,o){let n=e.Point.Fn;if(!n)throw Error("no Point.Fn");function i(s){let a;for(let d=0,p=t;;d=p,p+=t){if(p>s.length)throw Error("rejection sampling failed");if(a=n.fromBytes(s.subarray(d,p),!0),n.isValidNot0(a))break}let l=n.toBytes(n.create(a)),u=e.getPublicKey(l,!1);return{secretKey:l,publicKey:u}}return{lengths:{secretKey:t,publicKey:r,seed:o,msg:o,cipherText:r},keygen(s=Wn(o)){return Re(s,o,"seed"),i(s)},getPublicKey(s){return e.getPublicKey(s,!1)},encapsulate(s,a=Wn(o)){Re(a,o,"rand");let{secretKey:l}=i(a),u=this.decapsulate(s,l),d=e.getPublicKey(l,!1);return Pt(l),{sharedSecret:u,cipherText:d}},decapsulate(s,a){return e.getSharedSecret(a,s).subarray(1)}}}function Yce(e,t,r,o){let{secretKey:n,publicKeyUncompressed:i}=r.lengths;if(!n||!i)throw Error("wrong curve");let s=Qce(r,n,i,o),a=64,l=a+o;return ey(32,32,(u)=>{Re(u,32);let d=Vn(u,{dkLen:l}),p=d.subarray(0,a),m=d.subarray(a,l);return It(p,m)},(u,d,p)=>Vs(It(p[0],p[1],d[1],u[1],Ci(e))),t,s)}var z1e,N1e,a6,D1e,Gce,Xce,ty,c6;var l6=v(()=>{CU();zU();Mc();BU();ZA();Wg();Zr();i6();Yg();/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */z1e=s6("QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)",Vd,GA(UA,!0),Vn,Vs),N1e=s6("QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)",o6,GA(PU,!0),Vn,Vs);a6=GA(OU),D1e=Wce("KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)",Vd,a6,Vn,Hg),Gce=(()=>ey(32,32,QA(Vn),(e,t,r)=>Vs(It(r[0],r[1],t[1],e[1],Ci("\\.//^\\"))),Vd,a6))();Xce=(()=>Yce("MLKEM768-P256",Vd,UA,128))(),ty=Gce,c6=Xce});function Co(e,t=""){if(typeof e!=="boolean"){let r=t&&`"${t}" `;throw TypeError(r+"expected boolean, got type="+typeof e)}return e}function oy(e){if(typeof e==="bigint"){if(!ry(e))throw RangeError("positive bigint expected, got "+e)}else XA(e);return e}function Gn(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 Gd(e){let t=oy(e).toString(16);return t.length&1?"0"+t:t}function u6(e){if(typeof e!=="string")throw TypeError("hex string expected, got "+typeof e);return e===""?ny:BigInt("0x"+e)}function Ys(e){return u6(xg(e))}function Sn(e){return u6(xg(Li(Ft(e)).reverse()))}function iy(e,t){if(vt(t),t===0)throw RangeError("zero length");e=oy(e);let r=e.toString(16);if(r.length>t*2)throw RangeError("number too large");return _d(r.padStart(t*2,"0"))}function Qd(e,t){return iy(e,t).reverse()}function d6(e,t){if(e=et(e),t=et(t),e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e[o]^t[o];return r===0}function Li(e){return Uint8Array.from(et(e))}function sy(e){if(typeof e!=="string")throw TypeError("ascii string expected, got "+typeof e);return Uint8Array.from(e,(t,r)=>{let o=t.charCodeAt(0);if(t.length!==1||o>127)throw RangeError(`string contains non-ASCII character "${e[r]}" with code ${o} at position ${r}`);return o})}function ele(e,t,r){return ry(e)&&ry(t)&&ry(r)&&t<=e&&e<r}function Po(e,t,r,o){if(!ele(t,r,o))throw RangeError("expected valid "+e+": "+r+" <= n < "+o+", got "+t)}function Qc(e){if(e<ny)throw Error("expected non-negative bigint, got "+e);let t;for(t=0;e>ny;e>>=YA,t+=1);return t}function p6(e,t,r){if(vt(e,"hashLen"),vt(t,"qByteLen"),typeof r!=="function")throw TypeError("hmacFn must be a function");let o=(S)=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1000,l=o(e),u=o(e),d=0,p=()=>{l.fill(1),u.fill(0),d=0},m=(...S)=>r(u,Vt(l,...S)),h=(S=n)=>{if(u=m(i,S),l=m(),S.length===0)return;u=m(s,S),l=m()},b=()=>{if(d++>=a)throw Error("drbg: tried max amount of iterations");let S=0,x=[];while(S<t){l=m();let _=l.slice();x.push(_),S+=l.length}return Vt(...x)};return(S,x)=>{p(),h(S);let _=void 0;while((_=x(b()))===void 0)h();return p(),_}}function rn(e,t={},r={}){if(Object.prototype.toString.call(e)!=="[object Object]")throw TypeError("expected valid options object");function o(i,s,a){if(!a&&s!=="function"&&!Object.hasOwn(e,i))throw TypeError(`param "${i}" is invalid: expected own property`);let l=e[i];if(a&&l===void 0)return;let u=typeof l;if(u!==s||l===null)throw TypeError(`param "${i}" is invalid: expected ${s}, got ${u}`)}let n=(i,s)=>Object.entries(i).forEach(([a,l])=>o(a,l,s));n(t,!1),n(r,!0)}var et=(e,t,r)=>Ft(e,t,r),XA,Hc,Vt=(...e)=>Gk(...e),Vc=(e)=>_d(e),Wc,Gc=(e)=>Eo(e),ny,YA,ry=(e)=>typeof e==="bigint"&&ny<=e,Yd=(e)=>(YA<<BigInt(e))-YA,eR=()=>{throw Error("not implemented")};var Bi=v(()=>{Qr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */XA=vt,Hc=xg,Wc=Hk,ny=BigInt(0),YA=BigInt(1)});function it(e,t){if(t<=Wt)throw Error("mod: expected positive modulus, got "+t);let r=e%t;return r>=Wt?r:t+r}function nn(e,t,r){if(t<Wt)throw Error("pow2: expected non-negative exponent, got "+t);let o=e;while(t-- >Wt)o*=o,o%=r;return o}function f6(e,t){if(e===Wt)throw Error("invert: expected non-zero number");if(t<=Wt)throw Error("invert: expected positive modulus, got "+t);let r=it(e,t),o=t,n=Wt,i=yt,s=yt,a=Wt;while(r!==Wt){let u=o/r,d=o-r*u,p=n-s*u,m=i-a*u;o=r,r=d,n=s,i=a,s=p,a=m}if(o!==yt)throw Error("invert: does not exist");return it(n,t)}function tR(e,t,r){let o=e;if(!o.eql(o.sqr(t),r))throw Error("Cannot find square root")}function w6(e,t){let r=e,o=(r.ORDER+yt)/y6,n=r.pow(t,o);return tR(r,n,t),n}function nle(e,t){let r=e,o=(r.ORDER-b6)/S6,n=r.mul(t,Xs),i=r.pow(n,o),s=r.mul(t,i),a=r.mul(r.mul(s,Xs),i),l=r.mul(s,r.sub(a,r.ONE));return tR(r,l,t),l}function ole(e){let t=ay(e),r=x6(e),o=r(t,t.neg(t.ONE)),n=r(t,o),i=r(t,t.neg(o)),s=(e+tle)/v6;return(a,l)=>{let u=a,d=u.pow(l,s),p=u.mul(d,o),m=u.mul(d,n),h=u.mul(d,i),b=u.eql(u.sqr(p),l),y=u.eql(u.sqr(m),l);d=u.cmov(d,p,b),p=u.cmov(h,m,y);let S=u.eql(u.sqr(p),l),x=u.cmov(d,p,S);return tR(u,x,l),x}}function x6(e){if(e<g6)throw Error("sqrt is not defined for small field");let t=e-yt,r=0;while(t%Xs===Wt)t/=Xs,r++;let o=Xs,n=ay(e);while(m6(n,o)===1)if(o++>1000)throw Error("Cannot find square root: probably non-prime P");if(r===1)return w6;let i=n.pow(o,t),s=(t+yt)/Xs;return function(l,u){let d=l;if(d.is0(u))return u;if(m6(d,u)!==1)throw Error("Cannot find square root");let p=r,m=d.mul(d.ONE,i),h=d.pow(u,t),b=d.pow(u,s);while(!d.eql(h,d.ONE)){if(d.is0(h))return d.ZERO;let y=1,S=d.sqr(h);while(!d.eql(S,d.ONE))if(y++,S=d.sqr(S),y===p)throw Error("Cannot find square root");let x=yt<<BigInt(p-y-1),_=d.pow(m,x);p=y,m=d.sqr(_),h=d.mul(h,m),b=d.mul(b,_)}return b}}function ile(e){if(e%y6===g6)return w6;if(e%S6===b6)return nle;if(e%v6===rle)return ole(e);return x6(e)}function rR(e){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},r=sle.reduce((o,n)=>(o[n]="function",o),t);if(rn(e,r),Gn(e.BYTES,"BYTES"),Gn(e.BITS,"BITS"),e.BYTES<1||e.BITS<1)throw Error("invalid field: expected BYTES/BITS > 0");if(e.ORDER<=yt)throw Error("invalid field: expected ORDER > 1, got "+e.ORDER);return e}function ale(e,t,r){let o=e;if(r<Wt)throw Error("invalid exponent, negatives unsupported");if(r===Wt)return o.ONE;if(r===yt)return t;let n=o.ONE,i=t;while(r>Wt){if(r&yt)n=o.mul(n,i);i=o.sqr(i),r>>=yt}return n}function Xd(e,t,r=!1){let o=e,n=Array(t.length).fill(r?o.ZERO:void 0),i=t.reduce((a,l,u)=>{if(o.is0(l))return a;return n[u]=a,o.mul(a,l)},o.ONE),s=o.inv(i);return t.reduceRight((a,l,u)=>{if(o.is0(l))return a;return n[u]=o.mul(a,n[u]),o.mul(a,l)},s),n}function m6(e,t){let r=e,o=(r.ORDER-yt)/Xs,n=r.pow(t,o),i=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),a=r.eql(n,r.neg(r.ONE));if(!i&&!s&&!a)throw Error("invalid Legendre symbol result");return i?1:s?0:-1}function cle(e,t){if(t!==void 0)XA(t);if(e<=Wt)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=Qc(e);if(t!==void 0&&t<r)throw Error(`invalid n length: expected bit length (${r}) >= n.length (${t})`);let o=t!==void 0?t:r,n=Math.ceil(o/8);return{nBitLength:o,nByteLength:n}}class nR{ORDER;BITS;BYTES;isLE;ZERO=Wt;ONE=yt;_lengths;_mod;constructor(e,t={}){if(e<=yt)throw Error("invalid field: expected ORDER > 1, got "+e);let r=void 0;if(this.isLE=!1,t!=null&&typeof t==="object"){if(typeof t.BITS==="number")r=t.BITS;if(typeof t.sqrt==="function")Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0});if(typeof t.isLE==="boolean")this.isLE=t.isLE;if(t.allowedLengths)this._lengths=Object.freeze(t.allowedLengths.slice());if(typeof t.modFromBytes==="boolean")this._mod=t.modFromBytes}let{nBitLength:o,nByteLength:n}=cle(e,r);if(n>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,Object.freeze(this)}create(e){return it(e,this.ORDER)}isValid(e){if(typeof e!=="bigint")throw TypeError("invalid field element: expected bigint, got "+typeof e);return Wt<=e&&e<this.ORDER}is0(e){return e===Wt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yt)===yt}neg(e){return it(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return it(e*e,this.ORDER)}add(e,t){return it(e+t,this.ORDER)}sub(e,t){return it(e-t,this.ORDER)}mul(e,t){return it(e*t,this.ORDER)}pow(e,t){return ale(this,e,t)}div(e,t){return it(e*f6(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 f6(e,this.ORDER)}sqrt(e){let t=h6.get(this);if(!t)h6.set(this,t=ile(this.ORDER));return t(this,e)}toBytes(e){return this.isLE?Qd(e,this.BYTES):iy(e,this.BYTES)}fromBytes(e,t=!1){et(e);let{_lengths:r,BYTES:o,isLE:n,ORDER:i,_mod:s}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let a=n?Sn(e):Ys(e);if(s)a=it(a,i);if(!t){if(!this.isValid(a))throw Error("invalid field element: outside of range 0..ORDER")}return a}invertBatch(e){return Xd(this,e)}cmov(e,t,r){return Co(r,"condition"),r?t:e}}function ay(e,t={}){return new nR(e,t)}function _6(e){if(typeof e!=="bigint")throw Error("field order must be bigint");if(e<=yt)throw Error("field order must be greater than 1");let t=Qc(e-yt);return Math.ceil(t/8)}function oR(e){let t=_6(e);return t+Math.ceil(t/2)}function E6(e,t,r=!1){et(e);let o=e.length,n=_6(t),i=Math.max(oR(t),16);if(o<i||o>1024)throw Error("expected "+i+"-1024 bytes of input, got "+o);let s=r?Sn(e):Ys(e),a=it(s,t-yt)+yt;return r?Qd(a,n):iy(a,n)}var Wt,yt,Xs,g6,y6,b6,tle,S6,rle,v6,zo=(e,t)=>(it(e,t)&yt)===yt,sle,h6;var ep=v(()=>{Bi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Wt=BigInt(0),yt=BigInt(1),Xs=BigInt(2),g6=BigInt(3),y6=BigInt(4),b6=BigInt(5),tle=BigInt(7),S6=BigInt(8),rle=BigInt(9),v6=BigInt(16);sle=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];h6=new WeakMap;Object.freeze(nR.prototype)});function tp(e,t){let r=t.negate();return e?r:t}function ta(e,t){let r=Xd(e.Fp,t.map((o)=>o.Z));return t.map((o,n)=>e.fromAffine(o.toAffine(r[n])))}function R6(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error("invalid window size, expected [1.."+t+"], got W="+e)}function iR(e,t){R6(e,t);let r=Math.ceil(t/e)+1,o=2**(e-1),n=2**e,i=Yd(e),s=BigInt(e);return{windows:r,windowSize:o,mask:i,maxNumber:n,shiftBy:s}}function I6(e,t,r){let{windowSize:o,mask:n,maxNumber:i,shiftBy:s}=r,a=Number(e&n),l=e>>s;if(a>o)a-=i,l+=ea;let u=t*o,d=u+Math.abs(a)-1,p=a===0,m=a<0,h=t%2!==0;return{nextN:l,offset:d,isZero:p,isNeg:m,isNegF:h,offsetF:u}}function aR(e){return T6.get(e)||1}function k6(e){if(e!==Yc)throw Error("invalid wNAF")}class rp{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let o=e;while(t>Yc){if(t&ea)r=r.add(o);o=o.double(),t>>=ea}return r}precomputeWindow(e,t){let{windows:r,windowSize:o}=iR(t,this.bits),n=[],i=e,s=i;for(let a=0;a<r;a++){s=i,n.push(s);for(let l=1;l<o;l++)s=s.add(i),n.push(s);i=s.double()}return n}wNAF(e,t,r){if(!this.Fn.isValid(r))throw Error("invalid scalar");let o=this.ZERO,n=this.BASE,i=iR(e,this.bits);for(let s=0;s<i.windows;s++){let{nextN:a,offset:l,isZero:u,isNeg:d,isNegF:p,offsetF:m}=I6(r,s,i);if(r=a,u)n=n.add(tp(p,t[m]));else o=o.add(tp(d,t[l]))}return k6(r),{p:o,f:n}}wNAFUnsafe(e,t,r,o=this.ZERO){let n=iR(e,this.bits);for(let i=0;i<n.windows;i++){if(r===Yc)break;let{nextN:s,offset:a,isZero:l,isNeg:u}=I6(r,i,n);if(r=s,l)continue;else{let d=t[a];o=o.add(u?d.negate():d)}}return k6(r),o}getPrecomputes(e,t,r){let o=sR.get(t);if(!o){if(o=this.precomputeWindow(t,e),e!==1){if(typeof r==="function")o=r(o);sR.set(t,o)}}return o}cached(e,t,r){let o=aR(e);return this.wNAF(o,this.getPrecomputes(o,e,r),t)}unsafe(e,t,r,o){let n=aR(e);if(n===1)return this._unsafeLadder(e,t,o);return this.wNAFUnsafe(n,this.getPrecomputes(n,e,r),t,o)}createCache(e,t){R6(t,this.bits),T6.set(e,t),sR.delete(e)}hasCache(e){return aR(e)!==1}}function $6(e,t,r,o){let n=t,i=e.ZERO,s=e.ZERO;while(r>Yc||o>Yc){if(r&ea)i=i.add(n);if(o&ea)s=s.add(n);n=n.double(),r>>=ea,o>>=ea}return{p1:i,p2:s}}function A6(e,t,r){if(t){if(t.ORDER!==e)throw Error("Field.ORDER must match order: Fp == p, Fn == n");return rR(t),t}else return ay(e,{isLE:r})}function cy(e,t,r={},o){if(o===void 0)o=e==="edwards";if(!t||typeof t!=="object")throw Error(`expected valid ${e} CURVE object`);for(let l of["p","n","h"]){let u=t[l];if(!(typeof u==="bigint"&&u>Yc))throw Error(`CURVE.${l} must be positive bigint`)}let n=A6(t.p,r.Fp,o),i=A6(t.n,r.Fn,o),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let l of a)if(!n.isValid(t[l]))throw Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:n,Fn:i}}function np(e,t){return function(o){let n=e(o);return{secretKey:n,publicKey:t(n)}}}var Yc,ea,sR,T6;var ly=v(()=>{Bi();ep();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Yc=BigInt(0),ea=BigInt(1);sR=new WeakMap,T6=new WeakMap});function op(e,t){if(Gn(e),Gn(t),t<0||t>4)throw Error("invalid I2OSP length: "+t);if(e<0||e>2**(8*t)-1)throw Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let o=t-1;o>=0;o--)r[o]=e&255,e>>>=8;return new Uint8Array(r)}function lle(e,t){let r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e[o]^t[o];return r}function ule(e){if(!Wc(e)&&typeof e!=="string")throw Error("DST must be Uint8Array or ascii string");let t=typeof e==="string"?sy(e):e;if(t.length===0)throw Error("DST must be non-empty");return t}function cR(e,t,r,o){if(et(e),Gn(r),t=ule(t),t.length>255)t=o(Vt(sy("H2C-OVERSIZE-DST-"),t));let{outputLen:n,blockLen:i}=o,s=Math.ceil(r/n);if(r>65535||s>255)throw Error("expand_message_xmd: invalid lenInBytes");let a=Vt(t,op(t.length,1)),l=new Uint8Array(i),u=op(r,2),d=Array(s),p=o(Vt(l,e,u,op(0,1),a));d[0]=o(Vt(p,op(1,1),a));for(let h=1;h<s;h++){let b=[lle(p,d[h-1]),op(h+1,1),a];d[h]=o(Vt(...b))}return Vt(...d).slice(0,r)}var O6="HashToScalar-";var C6=v(()=>{Bi()});function dle(e,t,r){Po("scalar",e,Qn,r);let[[o,n],[i,s]]=t,a=P6(s*e,r),l=P6(-n*e,r),u=e-a*o-l*i,d=-a*n-l*s,p=u<Qn,m=d<Qn;if(p)u=-u;if(m)d=-d;let h=Yd(Math.ceil(Qc(r)/2))+ji;if(u<Qn||u>=h||d<Qn||d>=h)throw Error("splitScalar (endomorphism): failed for k");return{k1neg:p,k1:u,k2neg:m,k2:d}}function uR(e){if(!["compact","recovered","der"].includes(e))throw Error('Signature format must be "compact", "recovered", or "der"');return e}function lR(e,t){rn(e);let r={};for(let o of Object.keys(t))r[o]=e[o]===void 0?t[o]:e[o];if(Co(r.lowS,"lowS"),Co(r.prehash,"prehash"),r.format!==void 0)uR(r.format);return r}function D6(e,t={}){let r=cy("weierstrass",e,t),o=r.Fp,n=r.Fn,i=r.CURVE,{h:s,n:a}=i;rn(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:l,allowInfinityPoint:u}=t;if(l){if(!o.is0(i.a)||typeof l.beta!=="bigint"||!Array.isArray(l.basises))throw Error('invalid endo: expected "beta": bigint and "basises": array')}let d=B6(o,n);function p(){if(!o.isOdd)throw Error("compression is not supported: Field does not have .isOdd()")}function m(j,T,B){if(u&&T.is0())return Uint8Array.of(0);let{x:I,y:R}=T.toAffine(),k=o.toBytes(I);if(Co(B,"isCompressed"),B){p();let q=!o.isOdd(R);return Vt(L6(q),k)}else return Vt(Uint8Array.of(4),k,o.toBytes(R))}function h(j){et(j,void 0,"Point");let{publicKey:T,publicKeyUncompressed:B}=d,I=j.length,R=j[0],k=j.subarray(1);if(u&&I===1&&R===0)return{x:o.ZERO,y:o.ZERO};if(I===T&&(R===2||R===3)){let q=o.fromBytes(k);if(!o.isValid(q))throw Error("bad point: is not on curve, wrong x");let N=S(q),H;try{H=o.sqrt(N)}catch(ae){let me=ae instanceof Error?": "+ae.message:"";throw Error("bad point: is not on curve, sqrt error"+me)}p();let G=o.isOdd(H);if((R&1)===1!==G)H=o.neg(H);return{x:q,y:H}}else if(I===B&&R===4){let q=o.BYTES,N=o.fromBytes(k.subarray(0,q)),H=o.fromBytes(k.subarray(q,q*2));if(!x(N,H))throw Error("bad point: is not on curve");return{x:N,y:H}}else throw Error(`bad point: got length ${I}, expected compressed=${T} or uncompressed=${B}`)}let b=t.toBytes===void 0?m:t.toBytes,y=t.fromBytes===void 0?h:t.fromBytes;function S(j){let T=o.sqr(j),B=o.mul(T,j);return o.add(o.add(B,o.mul(j,i.a)),i.b)}function x(j,T){let B=o.sqr(T),I=S(j);return o.eql(B,I)}if(!x(i.Gx,i.Gy))throw Error("bad curve params: generator point");let _=o.mul(o.pow(i.a,uy),ple),A=o.mul(o.sqr(i.b),BigInt(27));if(o.is0(o.add(_,A)))throw Error("bad curve params: a or b");function O(j,T,B=!1){if(!o.isValid(T)||B&&o.is0(T))throw Error(`bad point coordinate ${j}`);return T}function L(j){if(!(j instanceof P))throw Error("Weierstrass Point expected")}function z(j){if(!l||!l.basises)throw Error("no endo");return dle(j,l.basises,n.ORDER)}function K(j,T,B,I,R){return B=new P(o.mul(B.X,j),B.Y,B.Z),T=tp(I,T),B=tp(R,B),T.add(B)}class P{static BASE=new P(i.Gx,i.Gy,o.ONE);static ZERO=new P(o.ZERO,o.ONE,o.ZERO);static Fp=o;static Fn=n;X;Y;Z;constructor(j,T,B){this.X=O("x",j),this.Y=O("y",T,!0),this.Z=O("z",B),Object.freeze(this)}static CURVE(){return i}static fromAffine(j){let{x:T,y:B}=j||{};if(!j||!o.isValid(T)||!o.isValid(B))throw Error("invalid affine point");if(j instanceof P)throw Error("projective point not allowed");if(o.is0(T)&&o.is0(B))return P.ZERO;return new P(T,B,o.ONE)}static fromBytes(j){let T=P.fromAffine(y(et(j,void 0,"point")));return T.assertValidity(),T}static fromHex(j){return P.fromBytes(Vc(j))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(j=8,T=!0){if(ee.createCache(this,j),!T)this.multiply(uy);return this}assertValidity(){let j=this;if(j.is0()){if(t.allowInfinityPoint&&o.is0(j.X)&&o.eql(j.Y,o.ONE)&&o.is0(j.Z))return;throw Error("bad point: ZERO")}let{x:T,y:B}=j.toAffine();if(!o.isValid(T)||!o.isValid(B))throw Error("bad point: x or y not field elements");if(!x(T,B))throw Error("bad point: equation left != right");if(!j.isTorsionFree())throw Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y:j}=this.toAffine();if(!o.isOdd)throw Error("Field doesn't support isOdd");return!o.isOdd(j)}equals(j){L(j);let{X:T,Y:B,Z:I}=this,{X:R,Y:k,Z:q}=j,N=o.eql(o.mul(T,q),o.mul(R,I)),H=o.eql(o.mul(B,q),o.mul(k,I));return N&&H}negate(){return new P(this.X,o.neg(this.Y),this.Z)}double(){let{a:j,b:T}=i,B=o.mul(T,uy),{X:I,Y:R,Z:k}=this,q=o.ZERO,N=o.ZERO,H=o.ZERO,G=o.mul(I,I),re=o.mul(R,R),ae=o.mul(k,k),me=o.mul(I,R);return me=o.add(me,me),H=o.mul(I,k),H=o.add(H,H),q=o.mul(j,H),N=o.mul(B,ae),N=o.add(q,N),q=o.sub(re,N),N=o.add(re,N),N=o.mul(q,N),q=o.mul(me,q),H=o.mul(B,H),ae=o.mul(j,ae),me=o.sub(G,ae),me=o.mul(j,me),me=o.add(me,H),H=o.add(G,G),G=o.add(H,G),G=o.add(G,ae),G=o.mul(G,me),N=o.add(N,G),ae=o.mul(R,k),ae=o.add(ae,ae),G=o.mul(ae,me),q=o.sub(q,G),H=o.mul(ae,re),H=o.add(H,H),H=o.add(H,H),new P(q,N,H)}add(j){L(j);let{X:T,Y:B,Z:I}=this,{X:R,Y:k,Z:q}=j,N=o.ZERO,H=o.ZERO,G=o.ZERO,re=i.a,ae=o.mul(i.b,uy),me=o.mul(T,R),be=o.mul(B,k),xe=o.mul(I,q),Ae=o.add(T,B),ke=o.add(R,k);Ae=o.mul(Ae,ke),ke=o.add(me,be),Ae=o.sub(Ae,ke),ke=o.add(T,I);let _e=o.add(R,q);return ke=o.mul(ke,_e),_e=o.add(me,xe),ke=o.sub(ke,_e),_e=o.add(B,I),N=o.add(k,q),_e=o.mul(_e,N),N=o.add(be,xe),_e=o.sub(_e,N),G=o.mul(re,ke),N=o.mul(ae,xe),G=o.add(N,G),N=o.sub(be,G),G=o.add(be,G),H=o.mul(N,G),be=o.add(me,me),be=o.add(be,me),xe=o.mul(re,xe),ke=o.mul(ae,ke),be=o.add(be,xe),xe=o.sub(me,xe),xe=o.mul(re,xe),ke=o.add(ke,xe),me=o.mul(be,ke),H=o.add(H,me),me=o.mul(_e,ke),N=o.mul(Ae,N),N=o.sub(N,me),me=o.mul(Ae,be),G=o.mul(_e,G),G=o.add(G,me),new P(N,H,G)}subtract(j){return L(j),this.add(j.negate())}is0(){return this.equals(P.ZERO)}multiply(j){let{endo:T}=t;if(!n.isValidNot0(j))throw RangeError("invalid scalar: out of range");let B,I,R=(k)=>ee.cached(this,k,(q)=>ta(P,q));if(T){let{k1neg:k,k1:q,k2neg:N,k2:H}=z(j),{p:G,f:re}=R(q),{p:ae,f:me}=R(H);I=re.add(me),B=K(T.beta,G,ae,k,N)}else{let{p:k,f:q}=R(j);B=k,I=q}return ta(P,[B,I])[0]}multiplyUnsafe(j){let{endo:T}=t,B=this,I=j;if(!n.isValid(I))throw RangeError("invalid scalar: out of range");if(I===Qn||B.is0())return P.ZERO;if(I===ji)return B;if(ee.hasCache(this))return this.multiply(I);if(T){let{k1neg:R,k1:k,k2neg:q,k2:N}=z(I),{p1:H,p2:G}=$6(P,B,k,N);return K(T.beta,H,G,R,q)}else return ee.unsafe(B,I)}toAffine(j){let T=this,B=j,{X:I,Y:R,Z:k}=T;if(o.eql(k,o.ONE))return{x:I,y:R};let q=T.is0();if(B==null)B=q?o.ONE:o.inv(k);let N=o.mul(I,B),H=o.mul(R,B),G=o.mul(k,B);if(q)return{x:o.ZERO,y:o.ZERO};if(!o.eql(G,o.ONE))throw Error("invZ was invalid");return{x:N,y:H}}isTorsionFree(){let{isTorsionFree:j}=t;if(s===ji)return!0;if(j)return j(P,this);return ee.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:j}=t;if(s===ji)return this;if(j)return j(P,this);return this.multiplyUnsafe(s)}isSmallOrder(){if(s===ji)return this.is0();return this.clearCofactor().is0()}toBytes(j=!0){return Co(j,"isCompressed"),this.assertValidity(),b(P,this,j)}toHex(j=!0){return Hc(this.toBytes(j))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let W=n.BITS,ee=new rp(P,t.endo?Math.ceil(W/2):W);if(W>=8)P.BASE.precompute(8);return Object.freeze(P.prototype),Object.freeze(P),P}function L6(e){return Uint8Array.of(e?2:3)}function B6(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function fle(e,t={}){let{Fn:r}=e,o=t.randomBytes===void 0?Gc:t.randomBytes,n=Object.assign(B6(e.Fp,r),{seed:Math.max(oR(r.ORDER),16)});function i(h){try{let b=r.fromBytes(h);return r.isValidNot0(b)}catch(b){return!1}}function s(h,b){let{publicKey:y,publicKeyUncompressed:S}=n;try{let x=h.length;if(b===!0&&x!==y)return!1;if(b===!1&&x!==S)return!1;return!!e.fromBytes(h)}catch(x){return!1}}function a(h){return h=h===void 0?o(n.seed):h,E6(et(h,n.seed,"seed"),r.ORDER)}function l(h,b=!0){return e.BASE.multiply(r.fromBytes(h)).toBytes(b)}function u(h){let{secretKey:b,publicKey:y,publicKeyUncompressed:S}=n,x=r._lengths;if(!Wc(h))return;let _=et(h,void 0,"key").length,A=_===y||_===S,O=_===b||!!x?.includes(_);if(A&&O)return;return A}function d(h,b,y=!0){if(u(h)===!0)throw Error("first arg must be private key");if(u(b)===!1)throw Error("second arg must be public key");let S=r.fromBytes(h);return e.fromBytes(b).multiply(S).toBytes(y)}let p={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},m=np(a,l);return Object.freeze(p),Object.freeze(n),Object.freeze({getPublicKey:l,getSharedSecret:d,keygen:m,Point:e,utils:p,lengths:n})}function j6(e,t,r={}){let o=t;_o(o),rn(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes===void 0?Gc:r.randomBytes,i=r.hmac===void 0?(R,k)=>Fn(o,R,k):r.hmac,{Fp:s,Fn:a}=e,{ORDER:l,BITS:u}=a,{keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:b}=fle(e,r),y={prehash:!0,lowS:typeof r.lowS==="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},S=l*N6+ji<s.ORDER;function x(R){let k=l>>ji;return R>k}function _(R,k){if(!a.isValidNot0(k))throw Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return k}function A(){if(S)throw Error('"recovered" sig type is not supported for cofactor >2 curves')}function O(R,k){uR(k);let q=b.signature,N=k==="compact"?q:k==="recovered"?q+1:void 0;return et(R,N)}class L{r;s;recovery;constructor(R,k,q){if(this.r=_("r",R),this.s=_("s",k),q!=null){if(A(),![0,1,2,3].includes(q))throw Error("invalid recovery id");this.recovery=q}Object.freeze(this)}static fromBytes(R,k=y.format){O(R,k);let q;if(k==="der"){let{r:re,s:ae}=vn.toSig(et(R));return new L(re,ae)}if(k==="recovered")q=R[0],k="compact",R=R.subarray(1);let N=b.signature/2,H=R.subarray(0,N),G=R.subarray(N,N*2);return new L(a.fromBytes(H),a.fromBytes(G),q)}static fromHex(R,k){return this.fromBytes(Vc(R),k)}assertRecovery(){let{recovery:R}=this;if(R==null)throw Error("invalid recovery id: must be present");return R}addRecoveryBit(R){return new L(this.r,this.s,R)}recoverPublicKey(R){let{r:k,s:q}=this,N=this.assertRecovery(),H=N===2||N===3?k+l:k;if(!s.isValid(H))throw Error("invalid recovery id: sig.r+curve.n != R.x");let G=s.toBytes(H),re=e.fromBytes(Vt(L6((N&1)===0),G)),ae=a.inv(H),me=K(et(R,void 0,"msgHash")),be=a.create(-me*ae),xe=a.create(q*ae),Ae=e.BASE.multiplyUnsafe(be).add(re.multiplyUnsafe(xe));if(Ae.is0())throw Error("invalid recovery: point at infinify");return Ae.assertValidity(),Ae}hasHighS(){return x(this.s)}toBytes(R=y.format){if(uR(R),R==="der")return Vc(vn.hexFromSig(this));let{r:k,s:q}=this,N=a.toBytes(k),H=a.toBytes(q);if(R==="recovered")return A(),Vt(Uint8Array.of(this.assertRecovery()),N,H);return Vt(N,H)}toHex(R){return Hc(this.toBytes(R))}}Object.freeze(L.prototype),Object.freeze(L);let z=r.bits2int===void 0?function(k){if(k.length>8192)throw Error("input is too large");let q=Ys(k),N=k.length*8-u;return N>0?q>>BigInt(N):q}:r.bits2int,K=r.bits2int_modN===void 0?function(k){return a.create(z(k))}:r.bits2int_modN,P=Yd(u);function W(R){return Po("num < 2^"+u,R,Qn,P),a.toBytes(R)}function ee(R,k){return et(R,void 0,"message"),k?et(o(R),void 0,"prehashed message"):R}function j(R,k,q){let{lowS:N,prehash:H,extraEntropy:G}=lR(q,y);R=ee(R,H);let re=K(R),ae=a.fromBytes(k);if(!a.isValidNot0(ae))throw Error("invalid private key");let me=[W(ae),W(re)];if(G!=null&&G!==!1){let ke=G===!0?n(b.secretKey):G;me.push(et(ke,void 0,"extraEntropy"))}let be=Vt(...me),xe=re;function Ae(ke){let _e=z(ke);if(!a.isValidNot0(_e))return;let Ue=a.inv(_e),De=e.BASE.multiply(_e).toAffine(),Qe=a.create(De.x);if(Qe===Qn)return;let St=a.create(Ue*a.create(xe+Qe*ae));if(St===Qn)return;let Rt=(De.x===Qe?0:2)|Number(De.y&ji),Dt=St;if(N&&x(St))Dt=a.neg(St),Rt^=1;return new L(Qe,Dt,S?void 0:Rt)}return{seed:be,k2sig:Ae}}function T(R,k,q={}){let{seed:N,k2sig:H}=j(R,k,q);return p6(o.outputLen,a.BYTES,i)(N,H).toBytes(q.format)}function B(R,k,q,N={}){let{lowS:H,prehash:G,format:re}=lR(N,y);if(q=et(q,void 0,"publicKey"),k=ee(k,G),!Wc(R)){let ae=R instanceof L?", use sig.toBytes()":"";throw Error("verify expects Uint8Array signature"+ae)}O(R,re);try{let ae=L.fromBytes(R,re),me=e.fromBytes(q);if(H&&ae.hasHighS())return!1;let{r:be,s:xe}=ae,Ae=K(k),ke=a.inv(xe),_e=a.create(Ae*ke),Ue=a.create(be*ke),De=e.BASE.multiplyUnsafe(_e).add(me.multiplyUnsafe(Ue));if(De.is0())return!1;return a.create(De.x)===be}catch(ae){return!1}}function I(R,k,q={}){let{prehash:N}=lR(q,y);return k=ee(k,N),L.fromBytes(R,"recovered").recoverPublicKey(k).toBytes()}return Object.freeze({keygen:d,getPublicKey:p,getSharedSecret:m,utils:h,lengths:b,Point:e,sign:T,verify:B,recoverPublicKey:I,Signature:L,hash:o})}var P6=(e,t)=>(e+(e>=0?t:-t)/N6)/t,z6,vn,Qn,ji,N6,uy,ple;var Z6=v(()=>{Ed();Qr();Bi();ly();ep();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */z6=class z6 extends Error{constructor(e=""){super(e)}};vn={Err:z6,_tlv:{encode:(e,t)=>{let{Err:r}=vn;if(Gn(e,"tag"),e<0||e>255)throw new r("tlv.encode: wrong tag");if(typeof t!=="string")throw TypeError('"data" expected string, got type='+typeof t);if(t.length&1)throw new r("tlv.encode: unpadded data");let o=t.length/2,n=Gd(o);if(n.length/2&128)throw new r("tlv.encode: long form length too big");let i=o>127?Gd(n.length/2|128):"";return Gd(e)+i+n+t},decode(e,t){let{Err:r}=vn;t=et(t,void 0,"DER data");let o=0;if(e<0||e>255)throw new r("tlv.encode: wrong tag");if(t.length<2||t[o++]!==e)throw new r("tlv.decode: wrong tlv");let n=t[o++],i=!!(n&128),s=0;if(!i)s=n;else{let l=n&127;if(!l)throw new r("tlv.decode(long): indefinite length not supported");if(l>4)throw new r("tlv.decode(long): byte length is too big");let u=t.subarray(o,o+l);if(u.length!==l)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(o+=l,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=t.subarray(o,o+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(o+s)}}},_int:{encode(e){let{Err:t}=vn;if(oy(e),e<Qn)throw new t("integer: negative integers are not allowed");let r=Gd(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}=vn;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 Ys(e)}},toSig(e){let{Err:t,_int:r,_tlv:o}=vn,n=et(e,void 0,"signature"),{v:i,l:s}=o.decode(48,n);if(s.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l}=o.decode(2,i),{v:u,l:d}=o.decode(2,l);if(d.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(e){let{_tlv:t,_int:r}=vn,o=t.encode(2,r.encode(e.r)),n=t.encode(2,r.encode(e.s)),i=o+n;return t.encode(48,i)}};Object.freeze(vn._tlv);Object.freeze(vn._int);Object.freeze(vn);Qn=BigInt(0),ji=BigInt(1),N6=BigInt(2),uy=BigInt(3),ple=BigInt(4)});var mle,hle,Xc;var U6=v(()=>{Nc();Z6();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */mle=(()=>({p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")}))(),hle=D6(mle),Xc=j6(hle,wt)});function yle(e,t,r,o){let n=e.sqr(r),i=e.sqr(o),s=e.add(e.mul(t.a,n),i),a=e.add(e.ONE,e.mul(t.d,e.mul(n,i)));return e.eql(s,a)}function M6(e,t={}){let r=t,o=cy("edwards",e,r,r.FpFnLE),{Fp:n,Fn:i}=o,s=o.CURVE,{h:a}=s;rn(r,{},{uvRatio:"function"});let l=dR<<BigInt(i.BYTES*8)-Ar,u=(y)=>n.create(y),d=r.uvRatio===void 0?(y,S)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,S))}}catch(x){return{isValid:!1,value:Zi}}}:r.uvRatio;if(!yle(n,s,s.Gx,s.Gy))throw Error("bad curve params: generator point");function p(y,S,x=!1){let _=x?Ar:Zi;return Po("coordinate "+y,S,_,l),S}function m(y){if(!(y instanceof h))throw Error("EdwardsPoint expected")}class h{static BASE=new h(s.Gx,s.Gy,Ar,u(s.Gx*s.Gy));static ZERO=new h(Zi,Ar,Ar,Zi);static Fp=n;static Fn=i;X;Y;Z;T;constructor(y,S,x,_){this.X=p("x",y),this.Y=p("y",S),this.Z=p("z",x,!0),this.T=p("t",_),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw Error("extended point not allowed");let{x:S,y:x}=y||{};return p("x",S),p("y",x),new h(S,x,Ar,u(S*x))}static fromBytes(y,S=!1){let x=n.BYTES,{a:_,d:A}=s;y=Li(et(y,x,"point")),Co(S,"zip215");let O=Li(y),L=y[x-1];O[x-1]=L&-129;let z=Sn(O),K=S?l:n.ORDER;Po("point.y",z,Zi,K);let P=u(z*z),W=u(P-Ar),ee=u(A*P-_),{isValid:j,value:T}=d(W,ee);if(!j)throw Error("bad point: invalid y coordinate");let B=(T&Ar)===Ar,I=(L&128)!==0;if(!S&&T===Zi&&I)throw Error("bad point: x=0 and x_0=1");if(I!==B)T=u(-T);return h.fromAffine({x:T,y:z})}static fromHex(y,S=!1){return h.fromBytes(Vc(y),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,S=!0){if(b.createCache(this,y),!S)this.multiply(dR);return this}assertValidity(){let y=this,{a:S,d:x}=s;if(y.is0())throw Error("bad point: ZERO");let{X:_,Y:A,Z:O,T:L}=y,z=u(_*_),K=u(A*A),P=u(O*O),W=u(P*P),ee=u(z*S),j=u(P*u(ee+K)),T=u(W+u(x*u(z*K)));if(j!==T)throw Error("bad point: equation left != right (1)");let B=u(_*A),I=u(O*L);if(B!==I)throw Error("bad point: equation left != right (2)")}equals(y){m(y);let{X:S,Y:x,Z:_}=this,{X:A,Y:O,Z:L}=y,z=u(S*L),K=u(A*_),P=u(x*L),W=u(O*_);return z===K&&P===W}is0(){return this.equals(h.ZERO)}negate(){return new h(u(-this.X),this.Y,this.Z,u(-this.T))}double(){let{a:y}=s,{X:S,Y:x,Z:_}=this,A=u(S*S),O=u(x*x),L=u(dR*u(_*_)),z=u(y*A),K=S+x,P=u(u(K*K)-A-O),W=z+O,ee=W-L,j=z-O,T=u(P*ee),B=u(W*j),I=u(P*j),R=u(ee*W);return new h(T,B,R,I)}add(y){m(y);let{a:S,d:x}=s,{X:_,Y:A,Z:O,T:L}=this,{X:z,Y:K,Z:P,T:W}=y,ee=u(_*z),j=u(A*K),T=u(L*x*W),B=u(O*P),I=u((_+A)*(z+K)-ee-j),R=B-T,k=B+T,q=u(j-S*ee),N=u(I*R),H=u(k*q),G=u(I*q),re=u(R*k);return new h(N,H,re,G)}subtract(y){return m(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:x}=b.cached(this,y,(_)=>ta(h,_));return ta(h,[S,x])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw RangeError("invalid scalar: expected 0 <= sc < curve.n");if(y===Zi)return h.ZERO;if(this.is0()||y===Ar)return this;return b.unsafe(this,y,(S)=>ta(h,S))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.unsafe(this,s.n).is0()}toAffine(y){let S=this,x=y,{X:_,Y:A,Z:O}=S,L=S.is0();if(x==null)x=L?gle:n.inv(O);let z=u(_*x),K=u(A*x),P=n.mul(O,x);if(L)return{x:Zi,y:Ar};if(P!==Ar)throw Error("invZ was invalid");return{x:z,y:K}}clearCofactor(){if(a===Ar)return this;return this.multiplyUnsafe(a)}toBytes(){let{x:y,y:S}=this.toAffine(),x=n.toBytes(S);return x[x.length-1]|=y&Ar?128:0,x}toHex(){return Hc(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=new rp(h,i.BITS);if(i.BITS>=8)h.BASE.precompute(8);return Object.freeze(h.prototype),Object.freeze(h),h}class pR{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){eR()}static fromHex(e){eR()}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 Hc(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}}var Zi,Ar,dR,gle;var q6=v(()=>{Bi();ly();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Zi=BigInt(0),Ar=BigInt(1),dR=BigInt(2),gle=BigInt(8)});function ble(e){return rn(e,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...e})}function F6(e){let t=ble(e),{P:r,type:o,adjustScalarBytes:n,powPminus2:i,randomBytes:s}=t,a=o==="x25519";if(!a&&o!=="x448")throw Error("invalid type");let l=s===void 0?Gc:s,u=a?255:448,d=a?32:56,p=a?BigInt(9):BigInt(5),m=a?BigInt(121665):BigInt(39081),h=a?dy**BigInt(254):dy**BigInt(447),b=a?BigInt(8)*dy**BigInt(251)-el:BigInt(4)*dy**BigInt(445)-el,y=h+b+el,S=(I)=>it(I,r),x=_(p);function _(I){return Qd(S(I),d)}function A(I){let R=Li(et(I,d,"uCoordinate"));if(a)R[31]&=127;return S(Sn(R))}function O(I){return Sn(n(Li(et(I,d,"scalar"))))}function L(I,R){let k=ee(A(R),O(I));if(k===ip)throw Error("invalid private or public key received");return _(k)}function z(I){return L(I,x)}let K=z,P=L;function W(I,R,k){let q=S(I*(R-k));return R=S(R-q),k=S(k+q),{x_2:R,x_3:k}}function ee(I,R){Po("u",I,ip,r),Po("scalar",R,h,y);let k=R,q=I,N=el,H=ip,G=I,re=el,ae=ip;for(let be=BigInt(u-1);be>=ip;be--){let xe=k>>be&el;ae^=xe,{x_2:N,x_3:G}=W(ae,N,G),{x_2:H,x_3:re}=W(ae,H,re),ae=xe;let Ae=N+H,ke=S(Ae*Ae),_e=N-H,Ue=S(_e*_e),De=ke-Ue,Qe=G+re,St=G-re,Rt=S(St*Ae),Dt=S(Qe*_e),lt=Rt+Dt,Or=Rt-Dt;G=S(lt*lt),re=S(q*S(Or*Or)),N=S(ke*Ue),H=S(De*(ke+S(m*De)))}({x_2:N,x_3:G}=W(ae,N,G)),{x_2:H,x_3:re}=W(ae,H,re);let me=i(H);return S(N*me)}let j={secretKey:d,publicKey:d,seed:d},T=(I)=>(I=I===void 0?l(d):I,et(I,j.seed,"seed"),I),B={randomSecretKey:T};return Object.freeze(j),Object.freeze(B),Object.freeze({keygen:np(T,K),getSharedSecret:P,getPublicKey:K,scalarMult:L,scalarMultBase:z,utils:B,GuBytes:x.slice(),lengths:j})}var ip,el,dy;var J6=v(()=>{Bi();ly();ep();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ip=BigInt(0),el=BigInt(1),dy=BigInt(2)});function W6(e){let t=BigInt(10),r=BigInt(20),o=BigInt(40),n=BigInt(80),i=na,a=e*e%i*e%i,l=nn(a,K6,i)*a%i,u=nn(l,No,i)*e%i,d=nn(u,wle,i)*u%i,p=nn(d,t,i)*d%i,m=nn(p,r,i)*p%i,h=nn(m,o,i)*m%i,b=nn(h,n,i)*h%i,y=nn(b,n,i)*h%i,S=nn(y,t,i)*d%i;return{pow_p_5_8:nn(S,K6,i)*e%i,b2:a}}function _le(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function yR(e,t){let r=na,o=it(t*t*t,r),n=it(o*o*t,r),i=W6(e*n).pow_p_5_8,s=it(e*o*i,r),a=it(t*s*s,r),l=s,u=it(s*fR,r),d=a===e,p=a===it(-e,r),m=a===it(-e*fR,r);if(d)s=l;if(p||m)s=u;if(zo(s,r))s=it(-s,r);return{isValid:d||p,value:s}}function V6(e){let{d:t}=gR,r=na,o=(x)=>Ui.create(x),n=o(mR*e*e),i=o((n+No)*kle),s=BigInt(-1),a=o((s-t*n)*o(n+t)),{isValid:l,value:u}=yR(i,a),d=o(u*e);if(!zo(d,r))d=o(-d);if(!l)u=d;if(!l)s=n;let p=o(s*(n-No)*Ale-a),m=u*u,h=o((u+u)*a),b=o(p*Ele),y=o(No-m),S=o(No+m);return new ra(o(h*S),o(y*b),o(b*S),o(h*y))}var Sle,No,K6,vle,wle,xle,na,gR,fR,ra,Ui,G6,py,mR,Ele,Ile,kle,Ale,H6=(e)=>yR(No,e),Rle,hR=(e)=>Ui.create(Sn(e)&Rle),br,Tle;var Q6=v(()=>{Nc();Qr();q6();C6();ep();J6();Bi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Sle=BigInt(0),No=BigInt(1),K6=BigInt(2),vle=BigInt(3),wle=BigInt(5),xle=BigInt(8),na=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gR=(()=>({p:na,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:xle,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();fR=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");ra=M6(gR,{uvRatio:yR}),Ui=(()=>ra.Fp)(),G6=(()=>ra.Fn)(),py=(()=>{let e=na;return F6({P:e,type:"x25519",powPminus2:(t)=>{let{pow_p_5_8:r,b2:o}=W6(t);return it(nn(r,vle,e)*o,e)},adjustScalarBytes:_le})})(),mR=fR,Ele=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Ile=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),kle=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Ale=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Rle=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");br=class br extends pR{static BASE=(()=>new br(ra.BASE))();static ZERO=(()=>new br(ra.ZERO))();static Fp=(()=>Ui)();static Fn=(()=>G6)();constructor(e){super(e)}static fromAffine(e){return new br(ra.fromAffine(e))}assertSame(e){if(!(e instanceof br))throw Error("RistrettoPoint expected")}init(e){return new br(e)}static fromBytes(e){Ft(e,32);let{a:t,d:r}=gR,o=na,n=(A)=>Ui.create(A),i=hR(e);if(!d6(Ui.toBytes(i),e)||zo(i,o))throw Error("invalid ristretto255 encoding 1");let s=n(i*i),a=n(No+t*s),l=n(No-t*s),u=n(a*a),d=n(l*l),p=n(t*r*u-d),{isValid:m,value:h}=H6(n(p*d)),b=n(h*l),y=n(h*b*p),S=n((i+i)*b);if(zo(S,o))S=n(-S);let x=n(a*y),_=n(S*x);if(!m||zo(_,o)||x===Sle)throw Error("invalid ristretto255 encoding 2");return new br(new ra(S,x,No,_))}static fromHex(e){return br.fromBytes(_d(e))}toBytes(){let{X:e,Y:t,Z:r,T:o}=this.ep,n=na,i=(y)=>Ui.create(y),s=i(i(r+t)*i(r-t)),a=i(e*t),l=i(a*a),{value:u}=H6(i(s*l)),d=i(u*s),p=i(u*a),m=i(d*p*o),h;if(zo(o*m,n)){let y=i(t*mR),S=i(e*mR);e=y,t=S,h=i(d*Ile)}else h=p;if(zo(e*m,n))t=i(-t);let b=i((r-t)*h);if(zo(b,n))b=i(-b);return Ui.toBytes(b)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:o,Y:n}=e.ep,i=(l)=>Ui.create(l),s=i(t*n)===i(r*o),a=i(r*n)===i(t*o);return s||a}is0(){return this.equals(br.ZERO)}};Object.freeze(br.BASE);Object.freeze(br.ZERO);Object.freeze(br.prototype);Object.freeze(br);Tle=Object.freeze({Point:br,hashToCurve(e,t){let r=t?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":t.DST,o=cR(e,r,64,kg);return Tle.deriveToCurve(o)},hashToScalar(e,t={DST:O6}){let r=cR(e,t.DST,64,kg);return G6.create(Sn(r))},deriveToCurve(e){Ft(e,64);let t=hR(e.subarray(0,32)),r=V6(t),o=hR(e.subarray(32,64)),n=V6(o);return new br(r.add(n))}})});async function X6(e,t){if($le)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 fy(e,t){return await X6(async()=>{let r=bR(e)?e:await Cle(e),o=await crypto.subtle.importKey("raw",Ple(t),{name:"X25519"},Y6,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:o},r,256))},()=>{if(bR(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return py.scalarMult(e,t)})}async function sp(e){return await X6(async()=>fy(e,py.GuBytes),()=>{if(bR(e))throw Error("CryptoKey provided but X25519 WebCrypto is not supported");return py.scalarMultBase(e)})}async function Cle(e){if(e.length!==32)throw Error("X25519 private key must be 32 bytes");let t=new Uint8Array([...Ole,...e]);return crypto.subtle.importKey("pkcs8",t,{name:"X25519"},Y6,["deriveBits"])}function bR(e){return typeof CryptoKey<"u"&&e instanceof CryptoKey}function Ple(e){return e}var Y6=!1,$le=!1,Ole;var eM=v(()=>{Q6();Ole=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32])});class SR{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),Nle(oa(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=oa(e),null;this.buf=r.value}}close(){return this.s.releaseLock(),{rest:this.buf,transcript:oa(this.transcript)}}}function Nle(e){return e.forEach((t)=>{if(t<32||t>126)throw Error("invalid non-ASCII byte in header")}),new TextDecoder().decode(e)}function oa(e){let t=e.reduce((n,i)=>n+i.length,0),r=new Uint8Array(t),o=0;for(let n of e)r.set(n,o),o+=n.length;return r}function tl(e,...t){return e.pipeThrough(new TransformStream({start(r){for(let o of t)r.enqueue(o)}}))}function my(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}async function vR(e){if(!(e instanceof ReadableStream))throw Error("readAll expects a ReadableStream<Uint8Array>");return new Uint8Array(await new Response(e).arrayBuffer())}async function tM(e){if(!(e instanceof ReadableStream))throw Error("readAllString expects a ReadableStream<Uint8Array>");return await new Response(e).text()}async function rM(e,t){let r=e.getReader(),o=[],n=0;while(n<t){let{done:l,value:u}=await r.read();if(l)throw Error("stream ended before reading "+t.toString()+" bytes");o.push(u),n+=u.length}r.releaseLock();let i=oa(o),s=i.subarray(0,t),a=tl(e,i.subarray(t));return{data:s,rest:a}}var wR=()=>{};class Yn{args;body;constructor(e,t){this.args=e,this.body=t}}async function Dle(e){let t=await e.readLine();if(t===null)throw Error("invalid stanza");let r=t.split(" ");if(r.length<2||r.shift()!=="->")return{next:t};for(let i of r)if(i.length===0)throw Error("invalid stanza");let o=[];for(;;){let i=await e.readLine();if(i===null)throw Error("invalid stanza");let s=tr.decode(i);if(s.length>48)throw Error("invalid stanza");if(o.push(s),s.length<48)break}let n=oa(o);return{s:new Yn(r,n)}}async function nM(e){let t=new SR(e),r=await t.readLine();if(r!=="age-encryption.org/v1")throw Error("invalid version "+(r??"line"));let o=[];for(;;){let{s:n,next:i}=await Dle(t);if(n!==void 0){o.push(n);continue}if(!i.startsWith("--- "))throw Error("invalid header");let s=tr.decode(i.slice(4)),{rest:a,transcript:l}=t.close(),u=l.slice(0,l.length-1-i.length+3);return{stanzas:o,headerNoMAC:u,MAC:s,headerSize:l.length,rest:tl(e,a)}}}function xR(e){let t=[];t.push(`age-encryption.org/v1
409
409
  `);for(let r of e){t.push("-> "+r.args.join(" ")+`
410
410
  `);for(let o=0;o<r.body.length;o+=48){let n=o+48;if(n>r.body.length)n=r.body.length;t.push(tr.encode(r.body.subarray(o,n))+`
411
411
  `)}if(r.body.length%48===0)t.push(`
@@ -425,7 +425,7 @@ agePublicKey: ${t}
425
425
  `;Gue(x,S);let _=jM(S);if(r.dryRun){if(s(`Dry run: would encrypt ${_.length} secrets to ${d}.`),s(_.length>0?`Keys: ${_.join(", ")}`:"Keys: (none \u2014 shared defaults only)"),b)s(`Would remove plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:b,encryptedKeys:_,dryRun:!0}}let A=new ap;A.addRecipient(o.pilot.agePublicKey);let O=await A.encrypt(x),L=qi.encode(O);if(await qM(l,L),await Jue(u,{force:!0}),s(`Encrypted ${_.length} secrets to ${d}.`),b)s(`Removed plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:b,encryptedKeys:_}}function Kue(e,t,r,o,n,i){let s=UM(e,t,r,o,n,"openaiApiKey",i.effectiveOpenaiApiKeySelector,i.sharedOpenaiApiKeySelector),a=UM(e,t,r,o,n,"gitSyncToken",i.effectiveGitSyncTokenSelector,i.sharedGitSyncTokenSelector),l=i.discordEnabled?wy(e,t,r,o,n,"discordBotToken","DISCORD_BOT_TOKEN"):void 0,u=i.discordEnabled?wy(e,t,r,o,n,"discordPublicKey","DISCORD_PUBLIC_KEY"):void 0,d=i.discordEnabled?wy(e,t,r,o,n,"discordApplicationId","DISCORD_APPLICATION_ID"):void 0,p=xy(e,t,r,o,n,"atprotoAppPassword","ATPROTO_APP_PASSWORD"),m=MM(xy(e,t,r,o,n,"certificatePem","CERTIFICATE_PEM")),h=MM(xy(e,t,r,o,n,"privateKeyPem","PRIVATE_KEY_PEM"));return FM.parse({...s?{openaiApiKey:s}:{},...a?{gitSyncToken:a}:{},...l?{discordBotToken:l}:{},...u?{discordPublicKey:u}:{},...d?{discordApplicationId:d}:{},...p?{atprotoAppPassword:p}:{},...m?{certificatePem:m}:{},...h?{privateKeyPem:h}:{}})}function UM(e,t,r,o,n,i,s,a){if(s===a)return;return wy(e,t,r,o,n,i,s)}function wy(e,t,r,o,n,i,s){let a=xy(e,t,r,o,n,i,s);if(a===void 0||a.trim().length===0)throw Error(`Missing required secret value for ${String(i)}. Set it in users/<handle>.secrets.yaml or fall back to ${s}/${s}_FILE before running secrets:encrypt.`);return a}function MM(e){return e?.replace(/\r\n?|\n/g,"\\n")}function xy(e,t,r,o,n,i,s){return Hue(o,n,i,s,t,r,e)}function Hue(e,t,r,o,n,i,s){let a=e?.[r];if(a!==void 0&&a.trim().length>0)return a;let l=Bt(`${o}_FILE`,n,i);if(l&&l.trim().length>0)return fp(Yo(l,s),"utf8");let u=Bt(o,n,i);if(u!==void 0&&u.trim().length>0)return u;let d=t?.[r];if(d!==void 0&&d.trim().length>0)return d;return}function Vue(e){let t;try{t=fp(e,"utf8")}catch{return}try{return KR(t)}catch(r){throw Error(`Unable to parse plaintext secrets file ${e}: ${Ve(r)}`,{cause:r})}}async function Wue(e,t,r,o){if(!await Er(e))return;let n=JR(t,r,o);if(!n)return;let i;try{let s=fp(e,"utf8"),a=qi.decode(s),l=new cp;l.addIdentity(n),i=await l.decrypt(a,"text")}catch{return}try{return KR(i)}catch(s){throw Error(`Unable to parse decrypted secrets from ${e}: ${Ve(s)}`,{cause:s})}}function JR(e,t,r){let o=Bt("AGE_SECRET_KEY_FILE",t,r);if(o&&o.trim().length>0)return nl(fp(Yo(o,e),"utf8"));let n=Bt("AGE_SECRET_KEY",t,r);if(n&&n.trim().length>0)return nl(n);try{return nl(fp(qR(e,".brains-ops","age","identity.txt"),"utf8"))}catch{return}}function KR(e){let t=xC(e),r={};if(t!==null&&typeof t==="object"&&!Array.isArray(t)){for(let[o,n]of Object.entries(t))if(typeof n==="string")r[o]=n}return FM.partial().parse(r)}function Gue(e,t){let r={...t},o={...KR(e)},n=new Set([...Object.keys(r),...Object.keys(o)]);for(let i of n)if(r[i]!==o[i])throw Error(`secrets:encrypt round-trip verification failed for ${i}; refusing to write a corrupted encrypted payload`)}function Que(e){return[...e.effectiveOpenaiApiKeySelector!==e.sharedOpenaiApiKeySelector?["openaiApiKey"]:[],...e.effectiveGitSyncTokenSelector!==e.sharedGitSyncTokenSelector?["gitSyncToken"]:[],...e.discordEnabled?["discordBotToken","discordPublicKey","discordApplicationId"]:[]]}async function Yue(e,t){let r=["# local per-user secret staging file","# fill values, run `bunx brains-ops secrets:encrypt . <handle>`, then the plaintext file will be removed",...t.map((o)=>`${o}: `),""].join(`
426
426
  `);await qM(e,r,{flag:"wx"})}var FM;var _y=v(()=>{Mi();Xo();Pn();pe();vy();Gu();Rs();FM=c.strictObject({gitSyncToken:c.string().min(1).optional(),discordBotToken:c.string().min(1).optional(),discordPublicKey:c.string().min(1).optional(),discordApplicationId:c.string().min(1).optional(),openaiApiKey:c.string().min(1).optional(),atprotoAppPassword:c.string().min(1).optional(),certificatePem:c.string().min(1).optional(),privateKeyPem:c.string().min(1).optional()})});var GM={};Lt(GM,{upgradePilotRepo:()=>_de});import{readFile as Sde}from"fs/promises";import{join as vde}from"path";async function WM(e){let t=vde(e,"package.json"),o=wde.parse(JSON.parse(await Sde(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!o)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return o}async function xde(e,t){let o=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(o!==0)throw Error(`${e.join(" ")} failed with exit ${o}`)}async function _de(e,t={}){let r=t.exec??xde,o=await WM(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let i=await WM(e);return await r(["bun","x","brains-ops","init","."],e),{from:o,to:i}}var wde;var QM=v(()=>{pe();wde=c.object({devDependencies:c.record(c.string(),c.string()).optional()})});var tq={};Lt(tq,{migratePilotDeploySecrets:()=>XM,migratePilotEnvSchema:()=>eq,migratePilotRepoProviderKeys:()=>Ode,migrateProviderKeyFieldsYaml:()=>XR,openaiSelectorFor:()=>eT,renameProviderKeyFields:()=>Ji});import{readdir as Ede,readFile as QR,writeFile as YM}from"fs/promises";import{join as Do}from"path";function XR(e){let t=Gr(e,{keepSourceTokens:!0});return Ji(t)?t.toString({lineWidth:0}):e}function Ji(e){if(!hn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!vo(r.key)||typeof r.key.value!=="string")return!1;let o=Ide[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&vo(r.value)&&r.value.value===Ay)r.value.value=Ry;return r.key.value=o,!0}).length>0}function eT(e){return e===Ay?Ry:e}function XM(e){return e.replace(new RegExp(`^(\\s+- )${Ay}$`,"m"),`$1${Ry}`)}function eq(e){return e.replace(new RegExp(`^${Ay}=`,"m"),`${Ry}=`)}async function ky(e){try{return(await Ede(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function YR(e){try{return await QR(e,"utf8")}catch{return}}async function Tde(e){let t=await ky(Do(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=lr(await QR(Do(e,"cohorts",i),"utf8"),Ade);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await ky(Do(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=lr(await QR(Do(e,"users",i),"utf8"),kde);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function $de(e,t,r,o){let n=Do(e,"users",`${t}.secrets.yaml.age`),i=await YR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new cp;s.addIdentity(r);let a=await s.decrypt(qi.decode(i),"text"),l=XR(a);if(l===a)return!1;let u=new ap;return u.addRecipient(o),await YM(n,qi.encode(await u.encrypt(l))),!0}async function Ode(e,t){let r=["pilot.yaml",...(await ky(Do(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await ky(Do(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await Tde(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:XR})),{file:".env.schema",migrate:eq},{file:"deploy/kamal/deploy.yml",migrate:XM}].map(async({file:l,migrate:u})=>{let d=Do(e,l),p=await YR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await YM(d,m),[l]})),i=lr(await YR(Do(e,"pilot.yaml"))??"",Rde),s=JR(e,t,Cr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await $de(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var Ay="AI_API_KEY",Ry="OPENAI_API_KEY",Ide,kde,Ade,Rde;var Ty=v(()=>{Mi();Xo();Pn();pe();$c();_y();Ide={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};kde=c.looseObject({aiApiKeyOverride:c.string().optional()}),Ade=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),Rde=c.looseObject({agePublicKey:c.string()})});function iq(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"],remove:[...zde]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Nde(e){let t=Cde.parse(e);return fi.parse({brainVersion:t.brainVersion,bundleContract:pi,...iq(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:eT(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function Dde(e){let t=Pde.parse(e),r=t.presetOverride?iq(t.presetOverride):void 0;return Kr.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function sq(e){let t=Gr(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!hn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function tT(e,t){if(!hn(e.contents))return;return e.contents.items.find((r)=>vo(r.key)&&r.key.value===t)}function rq(e,t){if(!So(e)||!So(t))return;if(e.commentBefore!==void 0)t.commentBefore=e.commentBefore;if(e.comment!==void 0)t.comment=e.comment;if(e.spaceBefore!==void 0)t.spaceBefore=e.spaceBefore}function nq(e,t){if(!e||!So(t))return;let r=[So(e.key)?e.key.commentBefore:void 0,So(e.key)?e.key.comment:void 0,So(e.value)?e.value.commentBefore:void 0,So(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
427
427
  `)}function aq(e,t,r,o){if(!hn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>vo(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];rq(s?.key,i.key),rq(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function cq(e){let t=sq(e),r=Nde(t.toJS()),o=tT(t,"schemaVersion"),n=tT(t,"model");nq(o,tT(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",pi);let i=aq(t,"preset","bundles",r.bundles);if(nq(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return Ji(t),fi.parse(t.toJS()),t.toString({lineWidth:0})}function lq(e){let t=sq(e),r=Dde(t.toJS());if(r.bundlesOverride)aq(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return Ji(t),Kr.parse(t.toJS()),t.toString({lineWidth:0})}var oq,mp,Cde,Pde,zde;var uq=v(()=>{Ty();Pn();pe();$c();Zn();oq=c.enum(["core","default","pro"]),mp=c.string().min(1),Cde=c.strictObject({schemaVersion:c.literal(1),brainVersion:$t,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:oq,aiApiKey:mp,gitSyncToken:mp,contentRepoAdminToken:mp,agePublicKey:c.string().startsWith("age1").min(1)}),Pde=c.strictObject({members:c.array(mr).min(1),brainVersionOverride:$t.optional(),presetOverride:oq.optional(),aiApiKeyOverride:mp.optional(),gitSyncTokenOverride:mp.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),zde=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function pq(e,t){let r=Gr(e,{keepSourceTokens:!0});if(r.errors.length>0||!hn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Ude(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function fq(e,t,r){if(!Ude(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function mq(e){let t=lr(e,Zde);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function hq(e,t){let r=pq(e,"pilot desired-state"),o=Bde.parse(r.toJS());return fq("pilot.yaml",o.bundles,t),r.set("bundleContract",pi),r.set("bundles",t.targetBundles),Ji(r),fi.parse(r.toJS()),r.toString({lineWidth:0})}function gq(e,t,r){let o=pq(e,`cohort ${t}`),n=jde.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);fq(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return Ji(o),Kr.parse(o.toJS()),o.toString({lineWidth:0})}var Lde,rT,$y,Bde,jde,dq,Zde;var yq=v(()=>{Ty();Pn();pe();$c();Zn();Lde=c.enum(["core","site","publishing","team"]),rT=c.array(Lde).min(1),$y=c.array(c.string().min(1)),Bde=c.strictObject({brainVersion:$t,bundles:rT,add:$y.optional(),remove:$y.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),jde=c.strictObject({members:c.array(mr).min(1),brainVersionOverride:$t.optional(),bundlesOverride:rT.optional(),addOverride:$y.optional(),removeOverride:$y.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),dq=c.strictObject({sourceBundles:rT,targetBundles:c.array(dh).min(1)}),Zde=c.strictObject({bundleContract:c.literal(pi),pilot:dq,cohorts:c.record(mr,dq)})});var xq={};Lt(xq,{loadCapabilityBundleReview:()=>Gde,loadReviewedSitePins:()=>Wde,parseReviewedSitePins:()=>wq,stageLegacyCrossover:()=>Yde});import{access as Mde,cp as qde,mkdir as bq,readFile as al,readdir as vq,writeFile as sl}from"fs/promises";import{basename as Fde,join as Xn,relative as Oy,resolve as Sq}from"path";import{fileURLToPath as Jde}from"url";function wq(e){let t=lr(e,Kde);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Wde(e){return wq(await al(e,"utf8"))}async function Gde(e){return mq(await al(e,"utf8"))}async function Qde(e,t){let r=Xn(e,"users"),o=(await vq(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Xn(r,s),l=await al(a,"utf8"),u=Gr(l,{keepSourceTokens:!0});if(u.errors.length>0||!hn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Hde.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);ph.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await sl(a,m),i.push(Oy(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Yde(e,t,r={}){let o=Sq(e),n=Sq(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await qde(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=Fde(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Xn(n,"docs","canonical-crossover-record.md");try{await Mde(s)}catch{await bq(Xn(n,"docs"),{recursive:!0}),await sl(s,await al(Vde,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Xn(n,"pilot.yaml"),l=await al(a,"utf8"),d=Gr(l).toJS();if(!Ju(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=hq(l,m.pilot)}else h=cq(l);await sl(a,h),i.push("pilot.yaml");let b=Xn(n,"cohorts"),y=(await vq(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Xn(b,A),L=await al(O,"utf8"),z=A.replace(/\.ya?ml$/,""),K=m?.cohorts[z];if(K)S.delete(z);await sl(O,p?gq(L,z,K):lq(L)),i.push(Oy(n,O))}if(p&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Qde(n,r.sitePins));let x=await ut(n),_=Rh(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Xn(n,"users",A.handle);if(await bq(L,{recursive:!0}),O.brainYaml){let z=Xn(L,"brain.yaml");await sl(z,O.brainYaml),i.push(Oy(n,z))}if(O.envFile){let z=Xn(L,".env");await sl(z,O.envFile),i.push(Oy(n,z))}}return await mo(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var Kde,Hde,Vde;var _q=v(()=>{Pn();Ku();pe();$c();AI();uq();yq();Hr();fc();Zn();Kde=c.strictObject({sites:c.record(mr,eI)}),Hde=c.object({handle:mr,siteOverride:c.object({package:c.string().min(1),version:$t.optional(),theme:c.string().min(1).optional(),themeVersion:$t.optional()}).optional()}).passthrough(),Vde=Jde(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var Eq="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as Iq}from"crypto";function epe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Ki||Ki.length<e)Ki=Buffer.allocUnsafe(e*Xde),Iq.getRandomValues(Ki),cl=0;else if(cl+e>Ki.length)Iq.getRandomValues(Ki),cl=0}catch(t){throw Ki=void 0,t}cl+=e}function kq(e=21){epe(e|=0);let t="";for(let r=cl-e;r<cl;r++)t+=Eq[Ki[r]&63];return t}var Xde=128,Ki,cl;var Aq=()=>{};function Lo(e=12){return kq(e)}var hp=v(()=>{Aq()});import{openSync as tpe,writeSync as rpe}from"fs";function npe(e){return ll?`[${ll}] ${e}`:e}class Rr{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??aa.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=tpe(this.logFile,"a")}catch{}}static getInstance(e){if(!Rr.instance)Rr.instance=new Rr(e);else{if(e?.useStderr!==void 0)Rr.instance.useStderr=e.useStderr;if(e?.level!==void 0)Rr.instance.level=e.level}return Rr.instance}static resetInstance(){Rr.instance=null,ll=void 0}static setProcessRole(e){ll=e}static createFresh(e){return new Rr(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return npe([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{rpe(this.fileHandle,n+`
428
- `)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ll&&{role:ll},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=aa.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=aa.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=aa.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=aa.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<=aa.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=aa.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var aa,ll,k2e;var nT=v(()=>{aa={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};k2e=Rr.getInstance()});var oT,ope,ul,$2e;var gp=v(()=>{Tt();pe();oT=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),ope=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:oT,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:jn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:fo.optional()}),ul=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:oT,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:jn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:fo.optional(),rootJobId:c.string()}),$2e=c.enum(["none","skip","replace","coalesce"])});var ipe,Hi=15000;var yp=v(()=>{gp();pe();ipe=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:ul,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var iT,Rq,Oe,spe,ape,Tq,$q,Oq;var Bo=v(()=>{Tt();pe();gp();iT=c.enum(["pending","processing","completed","failed"]),Rq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},spe=c.object({id:c.string(),type:c.string(),status:iT,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),ape=c.object({jobId:c.string(),type:c.string(),status:Rq,result:c.unknown().optional(),error:c.string().optional()}),Tq=c.object({success:c.literal(!1),error:c.string().optional()}),$q=c.object({id:c.string(),type:c.enum(["job","batch"]),status:iT,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:ul}),Oq=di(WE.progress,$q)});var Ce,Gt;var wn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Gt=class Gt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Cq(e){let t=cpe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?lpe(r.authority):void 0,i=ca(r.path),s=r.query!==void 0?dpe(r.query):void 0,a=r.fragment!==void 0?ca(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function lpe(e){let t=upe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=ca(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:ca(r.username),password:r.password!==void 0?ca(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function dpe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:ca(n.replaceAll("+"," ")),value:ca(i.replaceAll("+"," "))})}return{pairs:r}}function ca(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function bp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=ppe(t.host),i=fpe(t.port),a=`//${mpe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function ppe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function fpe(e){return e!==void 0?`:${e}`:""}function mpe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var cpe,upe;var Cy=v(()=>{wn();cpe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();upe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var pl,Pq,zq,Sp,Py,hpe,Qt,Nq,Bq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),jq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),Zq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Sp[t>>18&63]+Sp[t>>12&63]+Sp[t>>6&63]+Sp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},cT,sT,zy=(e,t=!1)=>t?Bq(sT(e)):sT(e),gpe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Qt(192|t>>>6)+Qt(128|t&63):Qt(224|t>>>12&15)+Qt(128|t>>>6&63)+Qt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Qt(240|t>>>18&7)+Qt(128|t>>>12&63)+Qt(128|t>>>6&63)+Qt(128|t&63)}},ype,Uq=(e)=>e.replace(ype,gpe),Dq,dl=(e,t=!1)=>t?Bq(Dq(e)):Dq(e),Lq=(e)=>dl(e,!0),bpe,Spe=(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 Qt((r>>>10)+55296)+Qt((r&1023)+56320);case 3:return Qt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Qt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Mq=(e)=>e.replace(bpe,Spe),qq=(e)=>{if(e=e.replace(/\s+/g,""),!hpe.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=Py[e.charAt(i++)]<<18|Py[e.charAt(i++)]<<12|(r=Py[e.charAt(i++)])<<6|(o=Py[e.charAt(i++)]),r===64)n.push(Qt(t>>16&255));else if(o===64)n.push(Qt(t>>16&255,t>>8&255));else n.push(Qt(t>>16&255,t>>8&255,t&255));return n.join("")},lT,Fq,Jq=(e)=>Fq(Kq(e)),vpe,Kq=(e)=>jq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),aT=(e)=>vpe(Kq(e)),wpe=(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)},Hq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Vq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Hq(r));e("fromBase64",function(){return aT(this)}),e("toBase64",function(t){return dl(this,t)}),e("toBase64URI",function(){return dl(this,!0)}),e("toBase64URL",function(){return dl(this,!0)}),e("toUint8Array",function(){return Jq(this)})},Wq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Hq(r));e("toBase64",function(t){return zy(this,t)}),e("toBase64URI",function(){return zy(this,!0)}),e("toBase64URL",function(){return zy(this,!0)})},xpe=()=>{Vq(),Wq()},fl;var Ny=v(()=>{pl=typeof Buffer==="function",Pq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,zq=typeof TextEncoder==="function"?new TextEncoder:void 0,Sp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Py=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Sp),hpe=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Qt=String.fromCharCode.bind(String),Nq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),cT=typeof btoa==="function"?(e)=>btoa(e):pl?(e)=>Buffer.from(e,"binary").toString("base64"):Zq,sT=pl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Qt.apply(null,e.subarray(o,o+4096)));return cT(r.join(""))},ype=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Dq=pl?(e)=>Buffer.from(e,"utf8").toString("base64"):zq?(e)=>sT(zq.encode(e)):(e)=>cT(Uq(e)),bpe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,lT=typeof atob==="function"?(e)=>atob(jq(e)):pl?(e)=>Buffer.from(e,"base64").toString("binary"):qq,Fq=pl?(e)=>Nq(Buffer.from(e,"base64")):(e)=>Nq(lT(e).split("").map((t)=>t.charCodeAt(0))),vpe=pl?(e)=>Buffer.from(e,"base64").toString("utf8"):Pq?(e)=>Pq.decode(Fq(e)):(e)=>Mq(lT(e)),fl={version:"3.8.0",VERSION:"3.8.0",atob:lT,atobPolyfill:qq,btoa:cT,btoaPolyfill:Zq,fromBase64:aT,toBase64:dl,encode:dl,encodeURI:Lq,encodeURL:Lq,utob:Uq,btou:Mq,decode:aT,isValid:wpe,fromUint8Array:zy,toUint8Array:Jq,extendString:Vq,extendUint8Array:Wq,extendBuiltins:xpe}});function Vi(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 ml{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(_pe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function _pe(e){return Array.prototype.map.call(e,Epe)}function Epe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return fl.fromUint8Array(new Uint8Array(e));else return e}var eo="https://github.com/libsql/libsql-client-ts#supported-urls";var hl=v(()=>{Ny()});function Qq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function vp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===Gq)r="file::memory:";let l=Cq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===Gq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var Gq=":memory:";var wp=v(()=>{wn();Cy();hl()});var Xq=ge(function(on){var Ipe=on&&on.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),kpe=on&&on.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Yq=on&&on.__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))Ipe(t,e,r)}return kpe(t,e),t};Object.defineProperty(on,"__esModule",{value:!0});on.load=on.currentTarget=void 0;var Ape=Yq(Fr("path")),Rpe=Yq(Fr("fs"));function Tpe(){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 $pe()?`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}`)}on.currentTarget=Tpe;function $pe(){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 Ope(e){let t=Ape.join(e,"index.node");return Rpe.existsSync(t)?Fr(t):null}on.load=Ope});var r4=ge(function(Q2e,t4){var e4=()=>process.platform==="linux",uT=null,Cpe=()=>{if(!uT)uT=e4()&&process.report?process.report.getReport():{};return uT};t4.exports={isLinux:e4,getReport:Cpe}});var i4=ge(function(Y2e,o4){var n4=Fr("fs"),Ppe=(e)=>n4.readFileSync(e,"utf-8"),zpe=(e)=>new Promise((t,r)=>{n4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});o4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Ppe,readFile:zpe}});var x4=ge(function(X2e,w4){var a4=Fr("child_process"),{isLinux:gl,getReport:c4}=r4(),{LDD_PATH:Dy,readFile:l4,readFileSync:u4}=i4(),to,ro,Wi="",d4=()=>{if(!Wi)return new Promise((e)=>{a4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Wi=t?" ":r,e(Wi)})});return Wi},p4=()=>{if(!Wi)try{Wi=a4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Wi=" "}return Wi},jo="glibc",f4=/GLIBC\s(\d+\.\d+)/,la="musl",Npe=jo.toUpperCase(),Dpe=la.toLowerCase(),Lpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),m4=()=>{let e=c4();if(e.header&&e.header.glibcVersionRuntime)return jo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Lpe))return la}return null},h4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return jo;if(r&&r.includes(la))return la;return null},g4=(e)=>{if(e.includes(Dpe))return la;if(e.includes(Npe))return jo;return null},Bpe=async()=>{if(to!==void 0)return to;to=null;try{let e=await l4(Dy);to=g4(e)}catch(e){}return to},jpe=()=>{if(to!==void 0)return to;to=null;try{let e=u4(Dy);to=g4(e)}catch(e){}return to},y4=async()=>{let e=null;if(gl()){if(e=await Bpe(),!e)e=m4();if(!e){let t=await d4();e=h4(t)}}return e},b4=()=>{let e=null;if(gl()){if(e=jpe(),!e)e=m4();if(!e){let t=p4();e=h4(t)}}return e},Zpe=async()=>gl()&&await y4()!==jo,Upe=()=>gl()&&b4()!==jo,Mpe=async()=>{if(ro!==void 0)return ro;ro=null;try{let t=(await l4(Dy)).match(f4);if(t)ro=t[1]}catch(e){}return ro},qpe=()=>{if(ro!==void 0)return ro;ro=null;try{let t=u4(Dy).match(f4);if(t)ro=t[1]}catch(e){}return ro},S4=()=>{let e=c4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},s4=(e)=>e.trim().split(/\s+/)[1],v4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return s4(t);if(r&&o&&r.includes(la))return s4(o);return null},Fpe=async()=>{let e=null;if(gl()){if(e=await Mpe(),!e)e=S4();if(!e){let t=await d4();e=v4(t)}}return e},Jpe=()=>{let e=null;if(gl()){if(e=qpe(),!e)e=S4();if(!e){let t=p4();e=v4(t)}}return e};w4.exports={GLIBC:jo,MUSL:la,family:y4,familySync:b4,isNonGlibcLinux:Zpe,isNonGlibcLinuxSync:Upe,version:Fpe,versionSync:Jpe}});var E4=ge(function(eDe,_4){var Kpe={ALLOW:0,DENY:1};_4.exports=Kpe});var k4=ge(function(tDe,I4){var dT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ua(e,t,r){if(new.target!==ua)return new ua(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),dT.value=""+e,Object.defineProperty(this,"message",dT),Error.captureStackTrace(this,ua),this.code=t,this.rawCode=r}Object.setPrototypeOf(ua,Error);Object.setPrototypeOf(ua.prototype,Error.prototype);Object.defineProperty(ua.prototype,"name",dT);I4.exports=ua});var z4=ge(function(rDe,Ly){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Hpe,currentTarget:Vpe}=Xq(),{familySync:A4,GLIBC:Wpe,MUSL:Gpe}=x4();function Qpe(){if(process.env.LIBSQL_JS_DEV)return Hpe(__dirname);let e=Vpe();if(A4()==Wpe)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"&&A4()==Gpe)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:Ype,databaseOpenWithSync:Xpe,databaseInTransaction:efe,databaseInterrupt:tfe,databaseClose:rfe,databaseSyncSync:nfe,databaseSyncUntilSync:ofe,databaseExecSync:ife,databasePrepareSync:sfe,databaseDefaultSafeIntegers:afe,databaseAuthorizer:cfe,databaseLoadExtension:lfe,databaseMaxWriteReplicationIndex:ufe,statementRaw:dfe,statementIsReader:pfe,statementGet:R4,statementRun:T4,statementInterrupt:ffe,statementRowsSync:$4,statementColumns:mfe,statementSafeIntegers:hfe,rowsNext:gfe}=Qpe(),yfe=E4(),O4=k4();function yl(e){if(e.libsqlError)return new O4(e.message,e.code,e.rawCode);return e}class C4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Xpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Ype(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return efe(n)}}})}sync(){return nfe.call(this.db)}syncUntil(e){return ofe.call(this.db,e)}prepare(e){try{let t=sfe.call(this.db,e);return new P4(t)}catch(t){throw yl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){cfe.call(this.db,e)}loadExtension(...e){lfe.call(this.db,...e)}maxWriteReplicationIndex(){return ufe.call(this.db)}exec(e){try{ife.call(this.db,e)}catch(t){throw yl(t)}}interrupt(){tfe.call(this.db)}close(){rfe.call(this.db),this.open=!1}defaultSafeIntegers(e){return afe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class P4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return dfe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return pfe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return T4.call(this.stmt,e[0]);else return T4.call(this.stmt,e.flat())}catch(t){throw yl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return R4.call(this.stmt,e[0]);else return R4.call(this.stmt,e.flat())}catch(t){throw yl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=$4.call(this.stmt,e[0]);else t=$4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)gfe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw yl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw yl(t)}}interrupt(){ffe.call(this.stmt)}columns(){return mfe.call(this.stmt)}safeIntegers(e){return hfe.call(this.stmt,e??!0),this}}Ly.exports=C4;Ly.exports.Authorization=yfe;Ly.exports.SqliteError=O4});import{Buffer as D4}from"buffer";function L4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${eo}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Qq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new xp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new B4(o,n,i,e.intMode)}class B4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Vi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Gt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Gt)throw i;if(i instanceof Ce)throw new Gt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Vi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Gt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Gt)throw n;if(n instanceof Ce)throw new Gt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Vi(e),this.#n),this.#r=null,new j4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return Z4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new xp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new xp.default(this.#e,this.#t);return this.#r}}class j4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Gt)throw o;if(o instanceof Ce)throw new Gt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),Z4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>N4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=N4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>bfe(m,a,r)),d=0,p=void 0;return new ml(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new ml([],[],[],l,u)}}catch(i){throw U4(i)}}function bfe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=Sfe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Sfe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<vfe||e>wfe)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 D4)return e.buffer;return e}function N4(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<xfe||e>_fe)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 D4.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 Z4(e,t){try{e.exec(t)}catch(r){throw U4(r)}}function U4(e){if(e instanceof xp.default.SqliteError){let t=e.code,r=Efe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function Efe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return Ife[t]??`SQLITE_UNKNOWN_${t.toString()}`}var xp,vfe,wfe=9007199254740991n,xfe,_fe=9223372036854775807n,Ife;var M4=v(()=>{wn();wp();hl();xp=Hl(z4(),1);wn();vfe=-9007199254740991n;xfe=-9223372036854775808n;Ife={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 Gi;var pT=v(()=>{if(typeof WebSocket<"u")Gi=WebSocket;else if(typeof global<"u")Gi=global.WebSocket;else if(typeof window<"u")Gi=window.WebSocket;else if(typeof self<"u")Gi=self.WebSocket});class bl{constructor(){this.intMode="number"}intMode}var Ge,Pe,_p,xt,Ep,Sl,da,xn,or,no;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};_p=class _p extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Ep=class Ep extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};Sl=class Sl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};da=class da extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};no=class no extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw vl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw vl(e,"string or null")}function Zo(e){if(typeof e==="number")return e;throw vl(e,"number")}function Qi(e){if(typeof e==="boolean")return e;throw vl(e,"boolean")}function Ip(e){if(Array.isArray(e))return e;throw vl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw vl(e,"object")}function _n(e,t){return Ip(e).map((r)=>t(kt(r)))}function vl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function pa(e,t){return t(kt(e))}var wl=v(()=>{_t()});class q4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function kp(e,t){let r=[],o=new q4(r);return o.begin(),t(o,e),o.end(),r.join("")}var fa=0,Ap=1,Rp=2,F4=5;class J4{#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 K4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Rp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Yi(this.bytes(),e)}int32(){return this.#r(fa),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(fa),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Ap),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===fa)this.#e.skipVarint();else if(this.#t===Ap)this.#e.skip(8);else if(this.#t===Rp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===F4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Yi(e,t){let r=new J4(e),o=new K4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var fT=v(()=>{_t()});class mT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,Rp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new mT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,fa),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,fa),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Ap),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Tp(e,t){let r=new mT;return t(r,e),r.data()}var H4=()=>{};var hT=v(()=>{wl();fT();H4()});class Xi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var gT=v(()=>{_t()});function Ke(e,t){throw new or(t)}var sn=v(()=>{_t()});function xl(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<Afe||e>Rfe)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 yT(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 no("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var Afe,Rfe=9223372036854775807n;var bT=v(()=>{_t();sn();Afe=-9223372036854775808n});function ma(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function jy(e,t){let r=ma(e),o=e.rows.map((n)=>V4(r.columnNames,n,t));return{...r,rows:o}}function Zy(e,t){let r=ma(e),o;if(e.rows.length>0)o=V4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Uy(e,t){let r=ma(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=yT(e.rows[0][0],t);return{...r,value:o}}function V4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=yT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Uo(e){return new _p(e.message,e)}var $p=v(()=>{_t();bT()});class ha{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new no("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("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 Op(e,t){if(t instanceof ha)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var _l=v(()=>{_t()});class es{#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 Cp{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(xl(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]=xl(t),this}bindName(e,t){return this._namedArgs.set(e,xl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function My(e,t,r){let o,n=[],i=[];if(t instanceof Cp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>xl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:xl(u)}));else o=t;let{sql:s,sqlId:a}=Op(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var qy=v(()=>{_l();bT()});class Fy{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new ST(this)}execute(){if(this.#t)throw new no("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return $fe(this._stream,this._steps,e);else return Tfe(this._stream,this._steps,e)}}function Tfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function $fe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Uo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class ST{_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,jy)}queryRow(e){return this.#t(e,!0,Zy)}queryValue(e){return this.#t(e,!0,Uy)}run(e){return this.#t(e,!1,ma)}#t(e,t,r){if(this._index!==void 0)throw new no("This BatchStep has already been added to the batch");let o=My(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Uo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class dt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new dt(e._batch,{type:"ok",step:W4(e)})}static error(e){return new dt(e._batch,{type:"error",step:W4(e)})}static not(e){return new dt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)G4(e,r);return new dt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)G4(e,r);return new dt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new dt(e,{type:"is_autocommit"})}}function W4(e){if(e._index===void 0)throw new no("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function G4(e,t){if(t._batch!==e)throw new no("Cannot mix BatchCond objects for different Batch objects")}var vT=v(()=>{_t();$p();qy();sn()});function Q4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class El{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,jy)}queryRow(e){return this.#e(e,!0,Zy)}queryValue(e){return this.#e(e,!0,Uy)}run(e){return this.#e(e,!1,ma)}#e(e,t,r){let o=My(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Fy(this,e)}describe(e){let t=Op(this._sqlOwner(),e);return this._describe(t).then(Q4)}sequence(e){let t=Op(this._sqlOwner(),e);return this._sequence(t)}intMode}var Jy=v(()=>{vT();$p();_l();qy()});class Pp{}var Ofe=1000,Cfe=10,wT;var Y4=v(()=>{_t();wT=class wT extends Pp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new es,this.#o=new es,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<Cfe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:Ofe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var zp;var xT=v(()=>{_t();Jy();Y4();zp=class zp extends El{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new zp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new es,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new wT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Np(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,X4),e.arrayObjects("named_args",t.namedArgs,Pfe),e.boolean("want_rows",t.wantRows)}function Pfe(e,t){e.string("name",t.name),e.object("value",t.value,X4)}function Il(e,t){e.arrayObjects("steps",t.steps,zfe)}function zfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,_T);e.object("stmt",t.stmt,Np)}function _T(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,_T);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,_T);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function X4(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",fl.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var ET=v(()=>{Ny();sn()});function eF(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,Nfe);else throw Ke(t,"Impossible type of ClientMsg")}function Nfe(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,Np);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Il);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Il);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var tF=v(()=>{ET();sn()});function Dp(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,nF);for(let r of t.namedArgs)e.message(4,r,Dfe);e.bool(5,t.wantRows)}function Dfe(e,t){e.string(1,t.name),e.message(2,t.value,nF)}function kl(e,t){for(let r of t.steps)e.message(1,r,Lfe)}function Lfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,IT);e.message(2,t.stmt,Dp)}function IT(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,IT);else if(t.type==="and")e.message(4,t.conds,rF);else if(t.type==="or")e.message(5,t.conds,rF);else if(t.type==="is_autocommit")e.message(6,void 0,oF);else throw Ke(t,"Impossible type of BatchCond")}function rF(e,t){for(let r of t)e.message(1,r,IT)}function nF(e,t){if(t===null)e.message(1,void 0,oF);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function oF(e,t){}var kT=v(()=>{sn()});function iF(e,t){if(t.type==="hello")e.message(1,t,Bfe);else if(t.type==="request")e.message(2,t,jfe);else throw Ke(t,"Impossible type of ClientMsg")}function Bfe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function jfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Zfe);else if(r.type==="close_stream")e.message(3,r,Ufe);else if(r.type==="execute")e.message(4,r,Mfe);else if(r.type==="batch")e.message(5,r,qfe);else if(r.type==="open_cursor")e.message(6,r,Ffe);else if(r.type==="close_cursor")e.message(7,r,Jfe);else if(r.type==="fetch_cursor")e.message(8,r,Kfe);else if(r.type==="sequence")e.message(9,r,Hfe);else if(r.type==="describe")e.message(10,r,Vfe);else if(r.type==="store_sql")e.message(11,r,Wfe);else if(r.type==="close_sql")e.message(12,r,Gfe);else if(r.type==="get_autocommit")e.message(13,r,Qfe);else throw Ke(r,"Impossible type of Request")}function Zfe(e,t){e.int32(1,t.streamId)}function Ufe(e,t){e.int32(1,t.streamId)}function Mfe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Dp)}function qfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,kl)}function Ffe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,kl)}function Jfe(e,t){e.int32(1,t.cursorId)}function Kfe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Hfe(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 Vfe(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 Wfe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Gfe(e,t){e.int32(1,t.sqlId)}function Qfe(e,t){e.int32(1,t.streamId)}var sF=v(()=>{kT();sn()});function ts(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Lp(e){let t=_n(e.cols,aF),r=Ip(e.rows).map((s)=>_n(s,cF)),o=Zo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function aF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function Ky(e){let t=new Map;Ip(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Lp(kt(o)))});let r=new Map;return Ip(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,ts(kt(o)))}),{stepResults:t,stepErrors:r}}function Hy(e){let t=Tr(e.type);if(t==="step_begin"){let r=Zo(e.step),o=_n(e.cols,aF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Zo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Zo(e.step),o=ts(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,cF)};else if(t==="error")return{type:"error",error:ts(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function Vy(e){let t=_n(e.params,Yfe),r=_n(e.cols,Xfe),o=Qi(e.is_explain),n=Qi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Yfe(e){return{name:Ur(e.name)}}function Xfe(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function cF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return Zo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return fl.toUint8Array(Tr(e.base64));else throw new Pe("Unexpected type of Value")}var Wy=v(()=>{Ny();_t();wl()});function lF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ts(kt(e.error))};else if(t==="response_ok"){let r=Zo(e.request_id),o=eme(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Zo(e.request_id),o=ts(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function eme(e){let t=Tr(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:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ky(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=_n(e.entries,Hy),o=Qi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Qi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var uF=v(()=>{_t();wl();Wy()});var an,rs,dF,pF,Al,tme,rme,Gy,nme,ome,ime,Rl,sme,ame,cme;var Qy=v(()=>{an={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},rs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(dF))},2(e,t){t.rows.push(e.message(pF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},dF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},pF={default(){return[]},1(e,t){t.push(e.message(cme))}},Al={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(tme);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(rme);t.stepErrors.set(r,o)}},tme={default(){return[0,rs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(rs)}},rme={default(){return[0,an.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(an)}},Gy={default(){return{type:"none"}},1(e){return e.message(nme)},2(e){return e.message(ome)},3(e){return e.message(ime)},4(e){return{type:"row",row:e.message(pF)}},5(e){return{type:"error",error:e.message(an)}}},nme={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(dF))}},ome={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},ime={default(){return{type:"step_error",step:0,error:an.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(an)}},Rl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(sme))},2(e,t){t.cols.push(e.message(ame))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},sme={default(){return{name:void 0}},1(e,t){t.name=e.string()}},ame={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},cme={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 fF,lme,ume,dme,pme,fme,mme,hme,gme;var mF=v(()=>{Qy();fF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(lme)},3(e){return e.message(dme)},4(e){return e.message(ume)}},lme={default(){return{type:"hello_error",error:an.default()}},1(e,t){t.error=e.message(an)}},ume={default(){return{type:"response_error",requestId:0,error:an.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(an)}},dme={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(pme)},5(e,t){t.response=e.message(fme)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(mme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(hme)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(gme)}},pme={default(){return{type:"execute",result:rs.default()}},1(e,t){t.result=e.message(rs)}},fme={default(){return{type:"batch",result:Al.default()}},1(e,t){t.result=e.message(Al)}},mme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Gy))},2(e,t){t.done=e.bool()}},hme={default(){return{type:"describe",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},gme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var hF,AT,Yy;var Xy=v(()=>{hT();_t();gT();$p();_l();sn();xT();tF();sF();uF();mF();hF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),AT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Yy=class Yy extends bl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Xi,this._streamIdAlloc=new Xi,this._cursorIdAlloc=new Xi,this.#l=new Xi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=AT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=kp(e,eF);this.#e.send(r)}else if(t==="protobuf"){let r=Tp(e,iF);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new Sl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new Sl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=pa(JSON.parse(e.data),lF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Yi(new Uint8Array(e.data),fF)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Uo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Uo(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return zp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ha(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ga;var gF=v(()=>{if(typeof queueMicrotask<"u")ga=queueMicrotask;else{let e=Promise.resolve();ga=(t)=>{e.then(t)}}});class RT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function yF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,yme);return{baton:t,baseUrl:r,results:o}}function yme(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:bme(kt(e.response))};else if(t==="error")return{type:"error",error:ts(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function bme(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ky(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Qi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function bF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var TT=v(()=>{_t();wl();Wy()});var SF,Sme,vme,wme,xme,_me,Eme,vF;var $T=v(()=>{Qy();SF={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(Sme))}},Sme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(vme)}},2(e){return{type:"error",error:e.message(an)}}},vme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(wme)},3(e){return e.message(xme)},4(e){return{type:"sequence"}},5(e){return e.message(_me)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Eme)}},wme={default(){return{type:"execute",result:rs.default()}},1(e,t){t.result=e.message(rs)}},xme={default(){return{type:"batch",result:Al.default()}},1(e,t){t.result=e.message(Al)}},_me={default(){return{type:"describe",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Eme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},vF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var OT;var wF=v(()=>{wl();fT();_t();sn();TT();$T();Wy();Qy();OT=class OT extends Pp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new RT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(bF,vF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Hy,Gy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return pa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Yi(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function xF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Ime)}function Ime(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.object("batch",t.batch,Il);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function _F(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Il)}var CT=v(()=>{ET();sn()});function EF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,kme)}function kme(e,t){if(t.type==="close")e.message(1,t,Ame);else if(t.type==="execute")e.message(2,t,Rme);else if(t.type==="batch")e.message(3,t,Tme);else if(t.type==="sequence")e.message(4,t,$me);else if(t.type==="describe")e.message(5,t,Ome);else if(t.type==="store_sql")e.message(6,t,Cme);else if(t.type==="close_sql")e.message(7,t,Pme);else if(t.type==="get_autocommit")e.message(8,t,zme);else throw Ke(t,"Impossible type of StreamRequest")}function Ame(e,t){}function Rme(e,t){e.message(1,t.stmt,Dp)}function Tme(e,t){e.message(1,t.batch,kl)}function $me(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Ome(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Cme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Pme(e,t){e.int32(1,t.sqlId)}function zme(e,t){}function IF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,kl)}var PT=v(()=>{kT();sn()});function Nme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Uo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function Dme(e,t){if(t==="json"){let r=await e.json();return pa(r,yF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Yi(new Uint8Array(r),SF)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Lme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Uo(o);return new da(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new da(r,e.status)}return await e.body?.cancel(),new da(r,e.status)}var eb;var zT=v(()=>{_t();hT();gT();gF();$p();_l();Jy();sn();wF();CT();PT();CT();PT();TT();$T();eb=class eb extends El{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new es,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Xi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ha(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ga(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ga(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ga(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ga(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Dme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Nme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new OT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Lme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,xF,EF)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,_F,IF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=kp(t,o),s="application/json";else if(r==="protobuf")i=Tp(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function jme(e,t){let r=e;for(let o of Bme){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return NT}var Bme,NT,tb;var DT=v(()=>{_t();zT();Bme=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],NT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};tb=class tb extends bl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=jme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(NT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=NT.version)return;else if(this._endpoint===void 0)throw new xn(`${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 xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new eb(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var kF=v(()=>{_t()});function LT(e,t,r=2){if(typeof Gi>"u")throw new Ep("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(AT.keys());else o=Array.from(hF.keys());let n=new Gi(e,o);return new Yy(n,t)}function BT(e,t,r,o,n=2){return new tb(e instanceof URL?e:new URL(e),t,r,o,n)}var rb=v(()=>{pT();Xy();_t();DT();Xy();pT();vT();kF();_l();qy();Jy();DT();zT();Xy();xT();_t()});class Bp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Mo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Vi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(dt.ok(l));if(this.#t>=3)d.condition(dt.not(dt.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(dt.ok(s));if(this.#t>=3)l.condition(dt.not(dt.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Gt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push($l(s))}catch(s){if(s instanceof Gt)throw s;let a=st(s);if(a instanceof Ce)throw new Gt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Vi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Tl(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Vi(e)),a=i,l=o.map((h)=>{let b=r.step().condition(dt.ok(a));if(t>=3)b.condition(dt.not(dt.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(dt.ok(a));if(t>=3)u.condition(dt.not(dt.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(dt.not(dt.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Gt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push($l(b))}catch(b){if(b instanceof Gt)throw b;let y=st(b);if(y instanceof Ce)throw new Gt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Mo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Cp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function $l(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new ml(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=AF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function AF(e){if(e instanceof _p&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?AF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof Sl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof da)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var ZT=v(()=>{rb();wn();hl()});class Ol{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new RF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class RF{#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 UT=ge(function(rje,$F){function Zme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Ume(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function TF(e){return e.queue=0,e.map=Ume,e}$F.exports=function(e){if(e)return TF(Zme(e));else return TF(function(t){return t()})}});function PF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path),r;try{r=LT(t,e.authToken)}catch(o){if(o instanceof Ep){let n=e.scheme==="wss"?"https":"http",i=bp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${eo}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new zF(r,t,e.authToken,e.intMode,e.concurrency)}class zF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=CF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Mo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return $l(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Mo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Tl(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Mo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Tl("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new NF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Mme&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=OF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=LT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ol(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=OF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var CF,Mme=60000,OF=100,NF;var DF=v(()=>{rb();wn();wp();ZT();Cy();hl();CF=Hl(UT(),1);wn();NF=class NF extends Bp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function BF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path);return new ZF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class ZF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=BT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=LF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Mo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return $l(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Mo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Ol(s,jF).apply(o);let u=s.batch(!1);i=Tl(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Mo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Tl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new UF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=BT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var LF,jF=30,UF;var MF=v(()=>{rb();wn();wp();ZT();Cy();hl();LF=Hl(UT(),1);wn();UF=class UF extends Bp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ol(e,jF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Cl(e){return qme(vp(e,!0))}function qme(e){if(e.scheme==="wss"||e.scheme==="ws")return PF(e);else if(e.scheme==="https"||e.scheme==="http")return BF(e);else return L4(e)}var MT=v(()=>{wp();M4();DF();MF();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var En=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var jp;var nb=v(()=>{$e();jp=class jp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Pl=v(()=>{ir=Symbol.for("drizzle:Name")});var qT,qF;var FF=v(()=>{$e();Pl();qT=class qT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new qF(e,this)}};qF=class qF{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function ob(e,...t){return e(...t)}var FT=()=>{};function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var JF,Fme,KF;var HF=v(()=>{$e();Pl();JF=class JF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new KF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Fme=class Fme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new JF(e,this.name)}};KF=class KF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??JT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function VF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function WF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=VF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=WF(e,o+1);r.push(l),o=u;continue}let[s,a]=VF(e,o,!1);r.push(s),o=a}return[r,o]}function GF(e){let[t]=WF(e,1);return t}function KT(e){return`{${e.map((t)=>{if(Array.isArray(t))return KT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var QF=()=>{};var Zp,zl,YF,Jme,XF,HT;var e3=v(()=>{nb();En();$e();FF();FT();HF();QF();Zp=class Zp extends jp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new XF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>ob((n,i)=>{let s=new qT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new YF(e,this.config)}};zl=class zl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};YF=class YF extends zl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Jme=class Jme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};XF=class XF extends Zp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new HT(e,this.config,t)}};HT=class HT extends zl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=GF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,HT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return KT(r)}}});function n3(e){return!!e&&typeof e==="function"&&t3 in e&&e[t3]===!0}var Kme,r3,t3,Hme,o3;var i3=v(()=>{$e();e3();Kme=class Kme extends Zp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new r3(e,this.config)}};r3=class r3 extends zl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};t3=Symbol.for("drizzle:isPgEnum");Hme=class Hme extends Zp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new o3(e,this.config)}};o3=class o3 extends zl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var pt,Up;var In=v(()=>{$e();pt=class pt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Up=class Up extends pt{static[F]="WithSubquery"}});var s3="0.45.2";var a3=()=>{};var VT,WT,c3;var l3=v(()=>{FT();a3();c3={startActiveSpan(e,t){if(!VT)return t();if(!WT)WT=VT.trace.getTracer("drizzle-orm",s3);return ob((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),VT,WT)}}});var ft;var qo=v(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function ns(e){return e[ir]}function ya(e){return`${e[ib]??"public"}.${e[ir]}`}var ib,sb,u3,GT,QT,Mp,d3,Vme,he;var sr=v(()=>{$e();Pl();ib=Symbol.for("drizzle:Schema"),sb=Symbol.for("drizzle:Columns"),u3=Symbol.for("drizzle:ExtraConfigColumns"),GT=Symbol.for("drizzle:OriginalName"),QT=Symbol.for("drizzle:BaseName"),Mp=Symbol.for("drizzle:IsAlias"),d3=Symbol.for("drizzle:ExtraConfigBuilder"),Vme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:ib,OriginalName:GT,Columns:sb,ExtraConfigColumns:u3,BaseName:QT,IsAlias:Mp,ExtraConfigBuilder:d3};[ir];[GT];[ib];[sb];[u3];[QT];[Mp]=!1;[Vme]=!0;[d3]=void 0;constructor(e,t,r){this[ir]=this[GT]=e,this[ib]=t,this[QT]=r}}});function YT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Gme(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 p3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function qp(e,t){return e.map((r)=>{if(oe(r,os)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,os)){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 Wme,Nt,Ee,ab,f3,m3,fZe,Mr,os,Qme,cn;var Yt=v(()=>{$e();i3();In();l3();qo();En();sr();Wme=class Wme{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=f3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return c3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return Gme(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,ab))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Mp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Mp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,cn)){let d=u[ft].schema,p=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,os))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,os))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,pt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new ab(u._.alias)],r)}if(n3(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(YT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.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[F]="Name";brand;getSQL(){return new Ee([this])}};f3={mapFromDriverValue:(e)=>e},m3={mapToDriverValue:(e)=>e},fZe={...f3,...m3};Mr=class Mr{constructor(e,t=m3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new ab(l)}e.identifier=i;function s(l){return new os(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));os=class os{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};Qme=Symbol.for("drizzle:IsDrizzleView");cn=class cn{static[F]="View";[ft];[Qme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};He.prototype.getSQL=function(){return new Ee([this])};he.prototype.getSQL=function(){return new Ee([this])};pt.prototype.getSQL=function(){return new Ee([this])}});function XT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,pt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?ns(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==ns(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function ln(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,pt))r.push({path:i,field:n});else if(oe(n,he))r.push(...ln(n[he.Symbol.Columns],i));else r.push(...ln(n,i));return r},[])}function Fp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function cb(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,He))return[o,n];else return[o,new Mr(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function h3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function lb(e){return e[he.Symbol.Columns]}function Jp(e){return oe(e,pt)?e._.alias:oe(e,cn)?e[ft].name:oe(e,Ee)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function oo(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function g3(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 e$;var Sr=v(()=>{En();$e();Yt();In();sr();qo();e$=typeof TextDecoder>"u"?null:new TextDecoder});var y3,t$,r$;var ub=v(()=>{$e();y3=class y3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};t$=class t${static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new y3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};r$=class r${static[F]="NoopLogger";logQuery(){}}});var b3,S3,n$;var v3=v(()=>{$e();sr();b3=Symbol.for("drizzle:PgInlineForeignKeys"),S3=Symbol.for("drizzle:EnableRLS");n$=class n$ extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:b3,EnableRLS:S3});[b3]=[];[S3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var o$,w3;var x3=v(()=>{$e();v3();o$=class o${static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new w3(e,this.columns,this.name)}};w3=class w3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[n$.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(p3(t)&&!YT(e)&&!oe(e,Mr)&&!oe(e,os)&&!oe(e,He)&&!oe(e,he)&&!oe(e,cn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function un(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function E3(e){return C`not ${e}`}function ss(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function db(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function A3(e){return C`${e} is not null`}function pb(e){return C`exists ${e}`}function as(e){return C`not exists ${e}`}function R3(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function T3(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function $3(e,t){return C`${e} like ${t}`}function O3(e,t){return C`${e} not like ${t}`}function C3(e,t){return C`${e} ilike ${t}`}function P3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,_3=(e,t)=>C`${e} <> ${$r(t,e)}`,kn=(e,t)=>C`${e} > ${$r(t,e)}`,I3=(e,t)=>C`${e} >= ${$r(t,e)}`,k3=(e,t)=>C`${e} < ${$r(t,e)}`,is=(e,t)=>C`${e} <= ${$r(t,e)}`;var z3=v(()=>{En();$e();sr();Yt()});function Fo(e){return C`${e} asc`}function ba(e){return C`${e} desc`}var N3=v(()=>{Yt()});var i$=v(()=>{z3();N3()});function L3(){return{and:tt,between:R3,eq:je,exists:pb,gt:kn,gte:I3,ilike:C3,inArray:ss,isNull:qr,isNotNull:A3,like:$3,lt:k3,lte:is,ne:_3,not:E3,notBetween:T3,notExists:as,notLike:O3,notIlike:P3,notInArray:db,or:un,sql:C}}function B3(){return{sql:C,asc:Fo,desc:ba}}function j3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ya(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,o$))n[i].primaryKey.push(...d.columns)}}else if(oe(s,D3)){let a=ya(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Yme(e){return function(r,o){return new cs(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Xme(e){return function(r,o){return new Kp(e,r,o)}}function Z3(e,t,r){if(oe(r,cs)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ya(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ya(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],cs)&&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 U3(e){return{one:Yme(e),many:Xme(e)}}function fb(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,cs)?d&&fb(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>fb(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var s$,D3,cs,Kp;var Hp=v(()=>{sr();En();$e();x3();i$();Yt();s$=class s${constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};D3=class D3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};cs=class cs extends s${constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new cs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Kp=class Kp extends s${constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Kp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Vp(e,t){return new Proxy(e,new Sa(t,!1))}function io(e,t){return new Proxy(e,new Nl(new Proxy(e.table,new Sa(t,!1))))}function a$(e,t){return new Ee.Aliased(Wp(e.sql,t),e.fieldAlias)}function Wp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return io(r,t);if(oe(r,Ee))return Wp(r,t);if(oe(r,Ee.Aliased))return a$(r,t);return r}))}var Nl,Sa,ehe;var Gp=v(()=>{En();$e();Yt();sr();qo();Nl=class Nl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Sa=class Sa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Nl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Nl(new Proxy(e,this)));return r}};ehe=class ehe{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Vp(e.sourceTable,this.alias);return e[t]}}});var at;var va=v(()=>{Gp();En();$e();Yt();In();qo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,pt)?e._.selectedFields:oe(e,cn)?e[ft].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Nl(new Proxy(o.table,new Sa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Jo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var c$,M3;var l$=v(()=>{$e();Pl();c$=class c${static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new M3(e,this)}};M3=class M3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function u$(e,t){return`${e[ir]}_${t.join("_")}_unique`}var q3,the,F3;var d$=v(()=>{$e();Pl();q3=class q3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new F3(e,this.columns,this.name)}};the=class the{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new q3(e,this.name)}};F3=class F3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??u$(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Ut,bt;var ls=v(()=>{nb();En();$e();l$();d$();Ut=class Ut extends jp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new c$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};bt=class bt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=u$(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function Q3(e,t){let{name:r,config:o}=oo(e,t);if(o?.mode==="json")return new H3(r);if(o?.mode==="bigint")return new J3(r);return new W3(r)}var J3,K3,H3,V3,W3,G3;var p$=v(()=>{$e();Sr();ls();J3=class J3 extends Ut{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new K3(e,this.config)}};K3=class K3 extends bt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(e$.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};H3=class H3 extends Ut{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new V3(e,this.config)}};V3=class V3 extends bt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(e$.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};W3=class W3 extends Ut{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new G3(e,this.config)}};G3=class G3 extends bt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function e5(e){return(t,r)=>{let{name:o,config:n}=oo(t,r);return new Y3(o,n,e)}}var Y3,X3;var f$=v(()=>{$e();Sr();ls();Y3=class Y3 extends Ut{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new X3(e,this.config)}};X3=class X3 extends bt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=oo(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new n5(r,o.mode);if(o?.mode==="boolean")return new i5(r,o.mode);return new t5(r)}var mb,hb,t5,r5,n5,o5,i5,s5;var m$=v(()=>{$e();Yt();Sr();ls();mb=class mb extends Ut{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};hb=class hb extends bt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};t5=class t5 extends mb{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new r5(e,this.config)}};r5=class r5 extends hb{static[F]="SQLiteInteger"};n5=class n5 extends mb{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new o5(e,this.config)}};o5=class o5 extends hb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};i5=class i5 extends mb{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new s5(e,this.config)}};s5=class s5 extends hb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function f5(e,t){let{name:r,config:o}=oo(e,t),n=o?.mode;return n==="number"?new l5(r):n==="bigint"?new d5(r):new a5(r)}var a5,c5,l5,u5,d5,p5;var h$=v(()=>{$e();Sr();ls();a5=class a5 extends Ut{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new c5(e,this.config)}};c5=class c5 extends bt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};l5=class l5 extends Ut{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new u5(e,this.config)}};u5=class u5 extends bt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};d5=class d5 extends Ut{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new p5(e,this.config)}};p5=class p5 extends bt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function g5(e){return new m5(e??"")}var m5,h5;var g$=v(()=>{$e();ls();m5=class m5 extends Ut{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new h5(e,this.config)}};h5=class h5 extends bt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function mt(e,t={}){let{name:r,config:o}=oo(e,t);if(o.mode==="json")return new S5(r);return new y5(r,o)}var y5,b5,S5,v5;var y$=v(()=>{$e();Sr();ls();y5=class y5 extends Ut{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new b5(e,this.config)}};b5=class b5 extends bt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};S5=class S5 extends Ut{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new v5(e,this.config)}};v5=class v5 extends bt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function w5(){return{blob:Q3,customType:e5,integer:ar,numeric:f5,real:g5,text:mt}}var x5=v(()=>{p$();f$();m$();h$();g$();y$()});function rhe(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(w5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[b$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var b$,At,Qp=(e,t,r)=>rhe(e,t,r);var Ko=v(()=>{$e();sr();x5();b$=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:b$});[he.Symbol.Columns];[b$]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var nhe,_5;var E5=v(()=>{$e();nhe=class nhe{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new _5(e,this)}};_5=class _5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ho(e){return new I5(e,!1)}var I5,k5,A5;var R5=v(()=>{$e();I5=class I5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new k5(this.name,e,this.unique)}};k5=class k5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new A5(this.config,e)}};A5=class A5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var ohe,T5;var $5=v(()=>{$e();Ko();ohe=class ohe{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new T5(e,this.columns,this.name)}};T5=class T5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function An(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,pt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var Dl=v(()=>{$e();Yt();In();sr();Ko()});var gb;var O5=v(()=>{$e();Jo();va();Ko();sr();Sr();Dl();gb=class gb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=ln(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:An(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 ihe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function she(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function ahe(e){return e}var S$;var C5=v(()=>{$e();sr();S$=class S${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?ihe:e==="camelCase"?she:ahe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Ll,Vo,v$;var yb=v(()=>{$e();Ll=class Ll extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Vo=class Vo extends Error{constructor(e,t,r){super(`Failed query: ${e}
428
+ `)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...ll&&{role:ll},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=aa.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=aa.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=aa.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=aa.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<=aa.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=aa.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var aa,ll,R2e;var nT=v(()=>{aa={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};R2e=Rr.getInstance()});var oT,ope,ul,C2e;var gp=v(()=>{Tt();pe();oT=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),ope=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:oT,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:jn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:fo.optional()}),ul=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:oT,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:jn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:fo.optional(),rootJobId:c.string()}),C2e=c.enum(["none","skip","replace","coalesce"])});var ipe,Hi=15000;var yp=v(()=>{gp();pe();ipe=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:ul,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var iT,Rq,Oe,spe,ape,Tq,$q,Oq;var Bo=v(()=>{Tt();pe();gp();iT=c.enum(["pending","processing","completed","failed"]),Rq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},spe=c.object({id:c.string(),type:c.string(),status:iT,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),ape=c.object({jobId:c.string(),type:c.string(),status:Rq,result:c.unknown().optional(),error:c.string().optional()}),Tq=c.object({success:c.literal(!1),error:c.string().optional()}),$q=c.object({id:c.string(),type:c.enum(["job","batch"]),status:iT,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:ul}),Oq=di(WE.progress,$q)});var Ce,Gt;var wn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Gt=class Gt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Cq(e){let t=cpe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?lpe(r.authority):void 0,i=ca(r.path),s=r.query!==void 0?dpe(r.query):void 0,a=r.fragment!==void 0?ca(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function lpe(e){let t=upe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=ca(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:ca(r.username),password:r.password!==void 0?ca(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function dpe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:ca(n.replaceAll("+"," ")),value:ca(i.replaceAll("+"," "))})}return{pairs:r}}function ca(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function bp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=ppe(t.host),i=fpe(t.port),a=`//${mpe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function ppe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function fpe(e){return e!==void 0?`:${e}`:""}function mpe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var cpe,upe;var Cy=v(()=>{wn();cpe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();upe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var pl,Pq,zq,Sp,Py,hpe,Qt,Nq,Bq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),jq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),Zq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=Sp[t>>18&63]+Sp[t>>12&63]+Sp[t>>6&63]+Sp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},cT,sT,zy=(e,t=!1)=>t?Bq(sT(e)):sT(e),gpe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Qt(192|t>>>6)+Qt(128|t&63):Qt(224|t>>>12&15)+Qt(128|t>>>6&63)+Qt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Qt(240|t>>>18&7)+Qt(128|t>>>12&63)+Qt(128|t>>>6&63)+Qt(128|t&63)}},ype,Uq=(e)=>e.replace(ype,gpe),Dq,dl=(e,t=!1)=>t?Bq(Dq(e)):Dq(e),Lq=(e)=>dl(e,!0),bpe,Spe=(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 Qt((r>>>10)+55296)+Qt((r&1023)+56320);case 3:return Qt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Qt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Mq=(e)=>e.replace(bpe,Spe),qq=(e)=>{if(e=e.replace(/\s+/g,""),!hpe.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=Py[e.charAt(i++)]<<18|Py[e.charAt(i++)]<<12|(r=Py[e.charAt(i++)])<<6|(o=Py[e.charAt(i++)]),r===64)n.push(Qt(t>>16&255));else if(o===64)n.push(Qt(t>>16&255,t>>8&255));else n.push(Qt(t>>16&255,t>>8&255,t&255));return n.join("")},lT,Fq,Jq=(e)=>Fq(Kq(e)),vpe,Kq=(e)=>jq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),aT=(e)=>vpe(Kq(e)),wpe=(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)},Hq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Vq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Hq(r));e("fromBase64",function(){return aT(this)}),e("toBase64",function(t){return dl(this,t)}),e("toBase64URI",function(){return dl(this,!0)}),e("toBase64URL",function(){return dl(this,!0)}),e("toUint8Array",function(){return Jq(this)})},Wq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Hq(r));e("toBase64",function(t){return zy(this,t)}),e("toBase64URI",function(){return zy(this,!0)}),e("toBase64URL",function(){return zy(this,!0)})},xpe=()=>{Vq(),Wq()},fl;var Ny=v(()=>{pl=typeof Buffer==="function",Pq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,zq=typeof TextEncoder==="function"?new TextEncoder:void 0,Sp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Py=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(Sp),hpe=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Qt=String.fromCharCode.bind(String),Nq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),cT=typeof btoa==="function"?(e)=>btoa(e):pl?(e)=>Buffer.from(e,"binary").toString("base64"):Zq,sT=pl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Qt.apply(null,e.subarray(o,o+4096)));return cT(r.join(""))},ype=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Dq=pl?(e)=>Buffer.from(e,"utf8").toString("base64"):zq?(e)=>sT(zq.encode(e)):(e)=>cT(Uq(e)),bpe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,lT=typeof atob==="function"?(e)=>atob(jq(e)):pl?(e)=>Buffer.from(e,"base64").toString("binary"):qq,Fq=pl?(e)=>Nq(Buffer.from(e,"base64")):(e)=>Nq(lT(e).split("").map((t)=>t.charCodeAt(0))),vpe=pl?(e)=>Buffer.from(e,"base64").toString("utf8"):Pq?(e)=>Pq.decode(Fq(e)):(e)=>Mq(lT(e)),fl={version:"3.8.0",VERSION:"3.8.0",atob:lT,atobPolyfill:qq,btoa:cT,btoaPolyfill:Zq,fromBase64:aT,toBase64:dl,encode:dl,encodeURI:Lq,encodeURL:Lq,utob:Uq,btou:Mq,decode:aT,isValid:wpe,fromUint8Array:zy,toUint8Array:Jq,extendString:Vq,extendUint8Array:Wq,extendBuiltins:xpe}});function Vi(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 ml{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(_pe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function _pe(e){return Array.prototype.map.call(e,Epe)}function Epe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return fl.fromUint8Array(new Uint8Array(e));else return e}var eo="https://github.com/libsql/libsql-client-ts#supported-urls";var hl=v(()=>{Ny()});function Qq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function vp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===Gq)r="file::memory:";let l=Cq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===Gq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var Gq=":memory:";var wp=v(()=>{wn();Cy();hl()});var Xq=ge(function(on){var Ipe=on&&on.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),kpe=on&&on.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Yq=on&&on.__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))Ipe(t,e,r)}return kpe(t,e),t};Object.defineProperty(on,"__esModule",{value:!0});on.load=on.currentTarget=void 0;var Ape=Yq(Fr("path")),Rpe=Yq(Fr("fs"));function Tpe(){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 $pe()?`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}`)}on.currentTarget=Tpe;function $pe(){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 Ope(e){let t=Ape.join(e,"index.node");return Rpe.existsSync(t)?Fr(t):null}on.load=Ope});var r4=ge(function(X2e,t4){var e4=()=>process.platform==="linux",uT=null,Cpe=()=>{if(!uT)uT=e4()&&process.report?process.report.getReport():{};return uT};t4.exports={isLinux:e4,getReport:Cpe}});var i4=ge(function(eDe,o4){var n4=Fr("fs"),Ppe=(e)=>n4.readFileSync(e,"utf-8"),zpe=(e)=>new Promise((t,r)=>{n4.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});o4.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Ppe,readFile:zpe}});var x4=ge(function(tDe,w4){var a4=Fr("child_process"),{isLinux:gl,getReport:c4}=r4(),{LDD_PATH:Dy,readFile:l4,readFileSync:u4}=i4(),to,ro,Wi="",d4=()=>{if(!Wi)return new Promise((e)=>{a4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Wi=t?" ":r,e(Wi)})});return Wi},p4=()=>{if(!Wi)try{Wi=a4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Wi=" "}return Wi},jo="glibc",f4=/GLIBC\s(\d+\.\d+)/,la="musl",Npe=jo.toUpperCase(),Dpe=la.toLowerCase(),Lpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),m4=()=>{let e=c4();if(e.header&&e.header.glibcVersionRuntime)return jo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Lpe))return la}return null},h4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return jo;if(r&&r.includes(la))return la;return null},g4=(e)=>{if(e.includes(Dpe))return la;if(e.includes(Npe))return jo;return null},Bpe=async()=>{if(to!==void 0)return to;to=null;try{let e=await l4(Dy);to=g4(e)}catch(e){}return to},jpe=()=>{if(to!==void 0)return to;to=null;try{let e=u4(Dy);to=g4(e)}catch(e){}return to},y4=async()=>{let e=null;if(gl()){if(e=await Bpe(),!e)e=m4();if(!e){let t=await d4();e=h4(t)}}return e},b4=()=>{let e=null;if(gl()){if(e=jpe(),!e)e=m4();if(!e){let t=p4();e=h4(t)}}return e},Zpe=async()=>gl()&&await y4()!==jo,Upe=()=>gl()&&b4()!==jo,Mpe=async()=>{if(ro!==void 0)return ro;ro=null;try{let t=(await l4(Dy)).match(f4);if(t)ro=t[1]}catch(e){}return ro},qpe=()=>{if(ro!==void 0)return ro;ro=null;try{let t=u4(Dy).match(f4);if(t)ro=t[1]}catch(e){}return ro},S4=()=>{let e=c4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},s4=(e)=>e.trim().split(/\s+/)[1],v4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(jo))return s4(t);if(r&&o&&r.includes(la))return s4(o);return null},Fpe=async()=>{let e=null;if(gl()){if(e=await Mpe(),!e)e=S4();if(!e){let t=await d4();e=v4(t)}}return e},Jpe=()=>{let e=null;if(gl()){if(e=qpe(),!e)e=S4();if(!e){let t=p4();e=v4(t)}}return e};w4.exports={GLIBC:jo,MUSL:la,family:y4,familySync:b4,isNonGlibcLinux:Zpe,isNonGlibcLinuxSync:Upe,version:Fpe,versionSync:Jpe}});var E4=ge(function(rDe,_4){var Kpe={ALLOW:0,DENY:1};_4.exports=Kpe});var k4=ge(function(nDe,I4){var dT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ua(e,t,r){if(new.target!==ua)return new ua(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),dT.value=""+e,Object.defineProperty(this,"message",dT),Error.captureStackTrace(this,ua),this.code=t,this.rawCode=r}Object.setPrototypeOf(ua,Error);Object.setPrototypeOf(ua.prototype,Error.prototype);Object.defineProperty(ua.prototype,"name",dT);I4.exports=ua});var z4=ge(function(oDe,Ly){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Hpe,currentTarget:Vpe}=Xq(),{familySync:A4,GLIBC:Wpe,MUSL:Gpe}=x4();function Qpe(){if(process.env.LIBSQL_JS_DEV)return Hpe(__dirname);let e=Vpe();if(A4()==Wpe)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"&&A4()==Gpe)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:Ype,databaseOpenWithSync:Xpe,databaseInTransaction:efe,databaseInterrupt:tfe,databaseClose:rfe,databaseSyncSync:nfe,databaseSyncUntilSync:ofe,databaseExecSync:ife,databasePrepareSync:sfe,databaseDefaultSafeIntegers:afe,databaseAuthorizer:cfe,databaseLoadExtension:lfe,databaseMaxWriteReplicationIndex:ufe,statementRaw:dfe,statementIsReader:pfe,statementGet:R4,statementRun:T4,statementInterrupt:ffe,statementRowsSync:$4,statementColumns:mfe,statementSafeIntegers:hfe,rowsNext:gfe}=Qpe(),yfe=E4(),O4=k4();function yl(e){if(e.libsqlError)return new O4(e.message,e.code,e.rawCode);return e}class C4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Xpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Ype(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return efe(n)}}})}sync(){return nfe.call(this.db)}syncUntil(e){return ofe.call(this.db,e)}prepare(e){try{let t=sfe.call(this.db,e);return new P4(t)}catch(t){throw yl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){cfe.call(this.db,e)}loadExtension(...e){lfe.call(this.db,...e)}maxWriteReplicationIndex(){return ufe.call(this.db)}exec(e){try{ife.call(this.db,e)}catch(t){throw yl(t)}}interrupt(){tfe.call(this.db)}close(){rfe.call(this.db),this.open=!1}defaultSafeIntegers(e){return afe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class P4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return dfe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return pfe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return T4.call(this.stmt,e[0]);else return T4.call(this.stmt,e.flat())}catch(t){throw yl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return R4.call(this.stmt,e[0]);else return R4.call(this.stmt,e.flat())}catch(t){throw yl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=$4.call(this.stmt,e[0]);else t=$4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)gfe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw yl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw yl(t)}}interrupt(){ffe.call(this.stmt)}columns(){return mfe.call(this.stmt)}safeIntegers(e){return hfe.call(this.stmt,e??!0),this}}Ly.exports=C4;Ly.exports.Authorization=yfe;Ly.exports.SqliteError=O4});import{Buffer as D4}from"buffer";function L4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${eo}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Qq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new xp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new B4(o,n,i,e.intMode)}class B4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Vi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Gt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Gt)throw i;if(i instanceof Ce)throw new Gt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Vi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Gt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Gt)throw n;if(n instanceof Ce)throw new Gt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Vi(e),this.#n),this.#r=null,new j4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return Z4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new xp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new xp.default(this.#e,this.#t);return this.#r}}class j4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Gt)throw o;if(o instanceof Ce)throw new Gt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),Z4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>N4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=N4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>bfe(m,a,r)),d=0,p=void 0;return new ml(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new ml([],[],[],l,u)}}catch(i){throw U4(i)}}function bfe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=Sfe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Sfe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<vfe||e>wfe)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 D4)return e.buffer;return e}function N4(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<xfe||e>_fe)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 D4.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 Z4(e,t){try{e.exec(t)}catch(r){throw U4(r)}}function U4(e){if(e instanceof xp.default.SqliteError){let t=e.code,r=Efe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function Efe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return Ife[t]??`SQLITE_UNKNOWN_${t.toString()}`}var xp,vfe,wfe=9007199254740991n,xfe,_fe=9223372036854775807n,Ife;var M4=v(()=>{wn();wp();hl();xp=Hl(z4(),1);wn();vfe=-9007199254740991n;xfe=-9223372036854775808n;Ife={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 Gi;var pT=v(()=>{if(typeof WebSocket<"u")Gi=WebSocket;else if(typeof global<"u")Gi=global.WebSocket;else if(typeof window<"u")Gi=window.WebSocket;else if(typeof self<"u")Gi=self.WebSocket});class bl{constructor(){this.intMode="number"}intMode}var Ge,Pe,_p,xt,Ep,Sl,da,xn,or,no;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};_p=class _p extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Ep=class Ep extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};Sl=class Sl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};da=class da extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};no=class no extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw vl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw vl(e,"string or null")}function Zo(e){if(typeof e==="number")return e;throw vl(e,"number")}function Qi(e){if(typeof e==="boolean")return e;throw vl(e,"boolean")}function Ip(e){if(Array.isArray(e))return e;throw vl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw vl(e,"object")}function _n(e,t){return Ip(e).map((r)=>t(kt(r)))}function vl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function pa(e,t){return t(kt(e))}var wl=v(()=>{_t()});class q4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function kp(e,t){let r=[],o=new q4(r);return o.begin(),t(o,e),o.end(),r.join("")}var fa=0,Ap=1,Rp=2,F4=5;class J4{#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 K4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(Rp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Yi(this.bytes(),e)}int32(){return this.#r(fa),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(fa),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Ap),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===fa)this.#e.skipVarint();else if(this.#t===Ap)this.#e.skip(8);else if(this.#t===Rp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===F4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Yi(e,t){let r=new J4(e),o=new K4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var fT=v(()=>{_t()});class mT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,Rp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new mT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,fa),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,fa),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Ap),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Tp(e,t){let r=new mT;return t(r,e),r.data()}var H4=()=>{};var hT=v(()=>{wl();fT();H4()});class Xi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var gT=v(()=>{_t()});function Ke(e,t){throw new or(t)}var sn=v(()=>{_t()});function xl(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<Afe||e>Rfe)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 yT(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 no("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var Afe,Rfe=9223372036854775807n;var bT=v(()=>{_t();sn();Afe=-9223372036854775808n});function ma(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function jy(e,t){let r=ma(e),o=e.rows.map((n)=>V4(r.columnNames,n,t));return{...r,rows:o}}function Zy(e,t){let r=ma(e),o;if(e.rows.length>0)o=V4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Uy(e,t){let r=ma(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=yT(e.rows[0][0],t);return{...r,value:o}}function V4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=yT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Uo(e){return new _p(e.message,e)}var $p=v(()=>{_t();bT()});class ha{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new no("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("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 Op(e,t){if(t instanceof ha)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var _l=v(()=>{_t()});class es{#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 Cp{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(xl(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]=xl(t),this}bindName(e,t){return this._namedArgs.set(e,xl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function My(e,t,r){let o,n=[],i=[];if(t instanceof Cp){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>xl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:xl(u)}));else o=t;let{sql:s,sqlId:a}=Op(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var qy=v(()=>{_l();bT()});class Fy{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new ST(this)}execute(){if(this.#t)throw new no("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return $fe(this._stream,this._steps,e);else return Tfe(this._stream,this._steps,e)}}function Tfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function $fe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Uo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class ST{_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,jy)}queryRow(e){return this.#t(e,!0,Zy)}queryValue(e){return this.#t(e,!0,Uy)}run(e){return this.#t(e,!1,ma)}#t(e,t,r){if(this._index!==void 0)throw new no("This BatchStep has already been added to the batch");let o=My(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Uo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class dt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new dt(e._batch,{type:"ok",step:W4(e)})}static error(e){return new dt(e._batch,{type:"error",step:W4(e)})}static not(e){return new dt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)G4(e,r);return new dt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)G4(e,r);return new dt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new dt(e,{type:"is_autocommit"})}}function W4(e){if(e._index===void 0)throw new no("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function G4(e,t){if(t._batch!==e)throw new no("Cannot mix BatchCond objects for different Batch objects")}var vT=v(()=>{_t();$p();qy();sn()});function Q4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class El{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,jy)}queryRow(e){return this.#e(e,!0,Zy)}queryValue(e){return this.#e(e,!0,Uy)}run(e){return this.#e(e,!1,ma)}#e(e,t,r){let o=My(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Fy(this,e)}describe(e){let t=Op(this._sqlOwner(),e);return this._describe(t).then(Q4)}sequence(e){let t=Op(this._sqlOwner(),e);return this._sequence(t)}intMode}var Jy=v(()=>{vT();$p();_l();qy()});class Pp{}var Ofe=1000,Cfe=10,wT;var Y4=v(()=>{_t();wT=class wT extends Pp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new es,this.#o=new es,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<Cfe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:Ofe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var zp;var xT=v(()=>{_t();Jy();Y4();zp=class zp extends El{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new zp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new es,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new wT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Np(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,X4),e.arrayObjects("named_args",t.namedArgs,Pfe),e.boolean("want_rows",t.wantRows)}function Pfe(e,t){e.string("name",t.name),e.object("value",t.value,X4)}function Il(e,t){e.arrayObjects("steps",t.steps,zfe)}function zfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,_T);e.object("stmt",t.stmt,Np)}function _T(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,_T);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,_T);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function X4(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",fl.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var ET=v(()=>{Ny();sn()});function eF(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,Nfe);else throw Ke(t,"Impossible type of ClientMsg")}function Nfe(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,Np);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,Il);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,Il);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var tF=v(()=>{ET();sn()});function Dp(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,nF);for(let r of t.namedArgs)e.message(4,r,Dfe);e.bool(5,t.wantRows)}function Dfe(e,t){e.string(1,t.name),e.message(2,t.value,nF)}function kl(e,t){for(let r of t.steps)e.message(1,r,Lfe)}function Lfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,IT);e.message(2,t.stmt,Dp)}function IT(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,IT);else if(t.type==="and")e.message(4,t.conds,rF);else if(t.type==="or")e.message(5,t.conds,rF);else if(t.type==="is_autocommit")e.message(6,void 0,oF);else throw Ke(t,"Impossible type of BatchCond")}function rF(e,t){for(let r of t)e.message(1,r,IT)}function nF(e,t){if(t===null)e.message(1,void 0,oF);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function oF(e,t){}var kT=v(()=>{sn()});function iF(e,t){if(t.type==="hello")e.message(1,t,Bfe);else if(t.type==="request")e.message(2,t,jfe);else throw Ke(t,"Impossible type of ClientMsg")}function Bfe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function jfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Zfe);else if(r.type==="close_stream")e.message(3,r,Ufe);else if(r.type==="execute")e.message(4,r,Mfe);else if(r.type==="batch")e.message(5,r,qfe);else if(r.type==="open_cursor")e.message(6,r,Ffe);else if(r.type==="close_cursor")e.message(7,r,Jfe);else if(r.type==="fetch_cursor")e.message(8,r,Kfe);else if(r.type==="sequence")e.message(9,r,Hfe);else if(r.type==="describe")e.message(10,r,Vfe);else if(r.type==="store_sql")e.message(11,r,Wfe);else if(r.type==="close_sql")e.message(12,r,Gfe);else if(r.type==="get_autocommit")e.message(13,r,Qfe);else throw Ke(r,"Impossible type of Request")}function Zfe(e,t){e.int32(1,t.streamId)}function Ufe(e,t){e.int32(1,t.streamId)}function Mfe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Dp)}function qfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,kl)}function Ffe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,kl)}function Jfe(e,t){e.int32(1,t.cursorId)}function Kfe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Hfe(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 Vfe(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 Wfe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Gfe(e,t){e.int32(1,t.sqlId)}function Qfe(e,t){e.int32(1,t.streamId)}var sF=v(()=>{kT();sn()});function ts(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Lp(e){let t=_n(e.cols,aF),r=Ip(e.rows).map((s)=>_n(s,cF)),o=Zo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function aF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function Ky(e){let t=new Map;Ip(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Lp(kt(o)))});let r=new Map;return Ip(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,ts(kt(o)))}),{stepResults:t,stepErrors:r}}function Hy(e){let t=Tr(e.type);if(t==="step_begin"){let r=Zo(e.step),o=_n(e.cols,aF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=Zo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=Zo(e.step),o=ts(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,cF)};else if(t==="error")return{type:"error",error:ts(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function Vy(e){let t=_n(e.params,Yfe),r=_n(e.cols,Xfe),o=Qi(e.is_explain),n=Qi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Yfe(e){return{name:Ur(e.name)}}function Xfe(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function cF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return Zo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return fl.toUint8Array(Tr(e.base64));else throw new Pe("Unexpected type of Value")}var Wy=v(()=>{Ny();_t();wl()});function lF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:ts(kt(e.error))};else if(t==="response_ok"){let r=Zo(e.request_id),o=eme(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=Zo(e.request_id),o=ts(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function eme(e){let t=Tr(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:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ky(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=_n(e.entries,Hy),o=Qi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Qi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var uF=v(()=>{_t();wl();Wy()});var an,rs,dF,pF,Al,tme,rme,Gy,nme,ome,ime,Rl,sme,ame,cme;var Qy=v(()=>{an={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},rs={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(dF))},2(e,t){t.rows.push(e.message(pF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},dF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},pF={default(){return[]},1(e,t){t.push(e.message(cme))}},Al={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(tme);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(rme);t.stepErrors.set(r,o)}},tme={default(){return[0,rs.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(rs)}},rme={default(){return[0,an.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(an)}},Gy={default(){return{type:"none"}},1(e){return e.message(nme)},2(e){return e.message(ome)},3(e){return e.message(ime)},4(e){return{type:"row",row:e.message(pF)}},5(e){return{type:"error",error:e.message(an)}}},nme={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(dF))}},ome={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},ime={default(){return{type:"step_error",step:0,error:an.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(an)}},Rl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(sme))},2(e,t){t.cols.push(e.message(ame))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},sme={default(){return{name:void 0}},1(e,t){t.name=e.string()}},ame={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},cme={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 fF,lme,ume,dme,pme,fme,mme,hme,gme;var mF=v(()=>{Qy();fF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(lme)},3(e){return e.message(dme)},4(e){return e.message(ume)}},lme={default(){return{type:"hello_error",error:an.default()}},1(e,t){t.error=e.message(an)}},ume={default(){return{type:"response_error",requestId:0,error:an.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(an)}},dme={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(pme)},5(e,t){t.response=e.message(fme)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(mme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(hme)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(gme)}},pme={default(){return{type:"execute",result:rs.default()}},1(e,t){t.result=e.message(rs)}},fme={default(){return{type:"batch",result:Al.default()}},1(e,t){t.result=e.message(Al)}},mme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Gy))},2(e,t){t.done=e.bool()}},hme={default(){return{type:"describe",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},gme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var hF,AT,Yy;var Xy=v(()=>{hT();_t();gT();$p();_l();sn();xT();tF();sF();uF();mF();hF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),AT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Yy=class Yy extends bl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Xi,this._streamIdAlloc=new Xi,this._cursorIdAlloc=new Xi,this.#l=new Xi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=AT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=kp(e,eF);this.#e.send(r)}else if(t==="protobuf"){let r=Tp(e,iF);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new Sl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new Sl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=pa(JSON.parse(e.data),lF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Yi(new Uint8Array(e.data),fF)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Uo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Uo(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return zp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ha(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ga;var gF=v(()=>{if(typeof queueMicrotask<"u")ga=queueMicrotask;else{let e=Promise.resolve();ga=(t)=>{e.then(t)}}});class RT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function yF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,yme);return{baton:t,baseUrl:r,results:o}}function yme(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:bme(kt(e.response))};else if(t==="error")return{type:"error",error:ts(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function bme(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Lp(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ky(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Qi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function bF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var TT=v(()=>{_t();wl();Wy()});var SF,Sme,vme,wme,xme,_me,Eme,vF;var $T=v(()=>{Qy();SF={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(Sme))}},Sme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(vme)}},2(e){return{type:"error",error:e.message(an)}}},vme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(wme)},3(e){return e.message(xme)},4(e){return{type:"sequence"}},5(e){return e.message(_me)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Eme)}},wme={default(){return{type:"execute",result:rs.default()}},1(e,t){t.result=e.message(rs)}},xme={default(){return{type:"batch",result:Al.default()}},1(e,t){t.result=e.message(Al)}},_me={default(){return{type:"describe",result:Rl.default()}},1(e,t){t.result=e.message(Rl)}},Eme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},vF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var OT;var wF=v(()=>{wl();fT();_t();sn();TT();$T();Wy();Qy();OT=class OT extends Pp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new RT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(bF,vF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Hy,Gy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return pa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Yi(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function xF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Ime)}function Ime(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Np);else if(t.type==="batch")e.object("batch",t.batch,Il);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function _F(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,Il)}var CT=v(()=>{ET();sn()});function EF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,kme)}function kme(e,t){if(t.type==="close")e.message(1,t,Ame);else if(t.type==="execute")e.message(2,t,Rme);else if(t.type==="batch")e.message(3,t,Tme);else if(t.type==="sequence")e.message(4,t,$me);else if(t.type==="describe")e.message(5,t,Ome);else if(t.type==="store_sql")e.message(6,t,Cme);else if(t.type==="close_sql")e.message(7,t,Pme);else if(t.type==="get_autocommit")e.message(8,t,zme);else throw Ke(t,"Impossible type of StreamRequest")}function Ame(e,t){}function Rme(e,t){e.message(1,t.stmt,Dp)}function Tme(e,t){e.message(1,t.batch,kl)}function $me(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Ome(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Cme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Pme(e,t){e.int32(1,t.sqlId)}function zme(e,t){}function IF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,kl)}var PT=v(()=>{kT();sn()});function Nme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Uo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function Dme(e,t){if(t==="json"){let r=await e.json();return pa(r,yF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Yi(new Uint8Array(r),SF)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Lme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Uo(o);return new da(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new da(r,e.status)}return await e.body?.cancel(),new da(r,e.status)}var eb;var zT=v(()=>{_t();hT();gT();gF();$p();_l();Jy();sn();wF();CT();PT();CT();PT();TT();$T();eb=class eb extends El{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new es,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Xi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ha(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ga(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ga(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ga(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ga(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Dme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Nme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new OT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Lme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,xF,EF)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,_F,IF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=kp(t,o),s="application/json";else if(r==="protobuf")i=Tp(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function jme(e,t){let r=e;for(let o of Bme){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return NT}var Bme,NT,tb;var DT=v(()=>{_t();zT();Bme=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],NT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};tb=class tb extends bl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=jme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(NT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=NT.version)return;else if(this._endpoint===void 0)throw new xn(`${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 xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new eb(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var kF=v(()=>{_t()});function LT(e,t,r=2){if(typeof Gi>"u")throw new Ep("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(AT.keys());else o=Array.from(hF.keys());let n=new Gi(e,o);return new Yy(n,t)}function BT(e,t,r,o,n=2){return new tb(e instanceof URL?e:new URL(e),t,r,o,n)}var rb=v(()=>{pT();Xy();_t();DT();Xy();pT();vT();kF();_l();qy();Jy();DT();zT();Xy();xT();_t()});class Bp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Mo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Vi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(dt.ok(l));if(this.#t>=3)d.condition(dt.not(dt.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(dt.ok(s));if(this.#t>=3)l.condition(dt.not(dt.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Gt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push($l(s))}catch(s){if(s instanceof Gt)throw s;let a=st(s);if(a instanceof Ce)throw new Gt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Vi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Tl(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Vi(e)),a=i,l=o.map((h)=>{let b=r.step().condition(dt.ok(a));if(t>=3)b.condition(dt.not(dt.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(dt.ok(a));if(t>=3)u.condition(dt.not(dt.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(dt.not(dt.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Gt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push($l(b))}catch(b){if(b instanceof Gt)throw b;let y=st(b);if(y instanceof Ce)throw new Gt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Mo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Cp(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function $l(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new ml(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=AF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function AF(e){if(e instanceof _p&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?AF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof Sl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof da)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var ZT=v(()=>{rb();wn();hl()});class Ol{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new RF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class RF{#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 UT=ge(function(oje,$F){function Zme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Ume(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function TF(e){return e.queue=0,e.map=Ume,e}$F.exports=function(e){if(e)return TF(Zme(e));else return TF(function(t){return t()})}});function PF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path),r;try{r=LT(t,e.authToken)}catch(o){if(o instanceof Ep){let n=e.scheme==="wss"?"https":"http",i=bp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${eo}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new zF(r,t,e.authToken,e.intMode,e.concurrency)}class zF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=CF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Mo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return $l(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Mo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Tl(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Mo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Tl("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new NF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Mme&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=OF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=LT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Ol(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=OF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var CF,Mme=60000,OF=100,NF;var DF=v(()=>{rb();wn();wp();ZT();Cy();hl();CF=Hl(UT(),1);wn();NF=class NF extends Bp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function BF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${eo}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=bp(e.scheme,e.authority,e.path);return new ZF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class ZF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=BT(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=LF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Mo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return $l(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Mo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Ol(s,jF).apply(o);let u=s.batch(!1);i=Tl(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Mo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Tl("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new UF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=BT(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var LF,jF=30,UF;var MF=v(()=>{rb();wn();wp();ZT();Cy();hl();LF=Hl(UT(),1);wn();UF=class UF extends Bp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Ol(e,jF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Cl(e){return qme(vp(e,!0))}function qme(e){if(e.scheme==="wss"||e.scheme==="ws")return PF(e);else if(e.scheme==="https"||e.scheme==="http")return BF(e);else return L4(e)}var MT=v(()=>{wp();M4();DF();MF();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var En=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var jp;var nb=v(()=>{$e();jp=class jp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Pl=v(()=>{ir=Symbol.for("drizzle:Name")});var qT,qF;var FF=v(()=>{$e();Pl();qT=class qT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new qF(e,this)}};qF=class qF{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function ob(e,...t){return e(...t)}var FT=()=>{};function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var JF,Fme,KF;var HF=v(()=>{$e();Pl();JF=class JF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new KF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Fme=class Fme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new JF(e,this.name)}};KF=class KF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??JT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function VF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function WF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=VF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=WF(e,o+1);r.push(l),o=u;continue}let[s,a]=VF(e,o,!1);r.push(s),o=a}return[r,o]}function GF(e){let[t]=WF(e,1);return t}function KT(e){return`{${e.map((t)=>{if(Array.isArray(t))return KT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var QF=()=>{};var Zp,zl,YF,Jme,XF,HT;var e3=v(()=>{nb();En();$e();FF();FT();HF();QF();Zp=class Zp extends jp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new XF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>ob((n,i)=>{let s=new qT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new YF(e,this.config)}};zl=class zl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};YF=class YF extends zl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Jme=class Jme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};XF=class XF extends Zp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new HT(e,this.config,t)}};HT=class HT extends zl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=GF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,HT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return KT(r)}}});function n3(e){return!!e&&typeof e==="function"&&t3 in e&&e[t3]===!0}var Kme,r3,t3,Hme,o3;var i3=v(()=>{$e();e3();Kme=class Kme extends Zp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new r3(e,this.config)}};r3=class r3 extends zl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};t3=Symbol.for("drizzle:isPgEnum");Hme=class Hme extends Zp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new o3(e,this.config)}};o3=class o3 extends zl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var pt,Up;var In=v(()=>{$e();pt=class pt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Up=class Up extends pt{static[F]="WithSubquery"}});var s3="0.45.2";var a3=()=>{};var VT,WT,c3;var l3=v(()=>{FT();a3();c3={startActiveSpan(e,t){if(!VT)return t();if(!WT)WT=VT.trace.getTracer("drizzle-orm",s3);return ob((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),VT,WT)}}});var ft;var qo=v(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function ns(e){return e[ir]}function ya(e){return`${e[ib]??"public"}.${e[ir]}`}var ib,sb,u3,GT,QT,Mp,d3,Vme,he;var sr=v(()=>{$e();Pl();ib=Symbol.for("drizzle:Schema"),sb=Symbol.for("drizzle:Columns"),u3=Symbol.for("drizzle:ExtraConfigColumns"),GT=Symbol.for("drizzle:OriginalName"),QT=Symbol.for("drizzle:BaseName"),Mp=Symbol.for("drizzle:IsAlias"),d3=Symbol.for("drizzle:ExtraConfigBuilder"),Vme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:ib,OriginalName:GT,Columns:sb,ExtraConfigColumns:u3,BaseName:QT,IsAlias:Mp,ExtraConfigBuilder:d3};[ir];[GT];[ib];[sb];[u3];[QT];[Mp]=!1;[Vme]=!0;[d3]=void 0;constructor(e,t,r){this[ir]=this[GT]=e,this[ib]=t,this[QT]=r}}});function YT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Gme(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 p3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function qp(e,t){return e.map((r)=>{if(oe(r,os)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,os)){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 Wme,Nt,Ee,ab,f3,m3,hZe,Mr,os,Qme,cn;var Yt=v(()=>{$e();i3();In();l3();qo();En();sr();Wme=class Wme{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=f3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return c3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return Gme(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,ab))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Mp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Mp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,cn)){let d=u[ft].schema,p=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,os))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,os))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,pt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new ab(u._.alias)],r)}if(n3(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(YT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.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[F]="Name";brand;getSQL(){return new Ee([this])}};f3={mapFromDriverValue:(e)=>e},m3={mapToDriverValue:(e)=>e},hZe={...f3,...m3};Mr=class Mr{constructor(e,t=m3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new ab(l)}e.identifier=i;function s(l){return new os(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));os=class os{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};Qme=Symbol.for("drizzle:IsDrizzleView");cn=class cn{static[F]="View";[ft];[Qme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};He.prototype.getSQL=function(){return new Ee([this])};he.prototype.getSQL=function(){return new Ee([this])};pt.prototype.getSQL=function(){return new Ee([this])}});function XT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,pt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?ns(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==ns(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function ln(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,pt))r.push({path:i,field:n});else if(oe(n,he))r.push(...ln(n[he.Symbol.Columns],i));else r.push(...ln(n,i));return r},[])}function Fp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function cb(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,He))return[o,n];else return[o,new Mr(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function h3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function lb(e){return e[he.Symbol.Columns]}function Jp(e){return oe(e,pt)?e._.alias:oe(e,cn)?e[ft].name:oe(e,Ee)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function oo(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function g3(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 e$;var Sr=v(()=>{En();$e();Yt();In();sr();qo();e$=typeof TextDecoder>"u"?null:new TextDecoder});var y3,t$,r$;var ub=v(()=>{$e();y3=class y3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};t$=class t${static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new y3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};r$=class r${static[F]="NoopLogger";logQuery(){}}});var b3,S3,n$;var v3=v(()=>{$e();sr();b3=Symbol.for("drizzle:PgInlineForeignKeys"),S3=Symbol.for("drizzle:EnableRLS");n$=class n$ extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:b3,EnableRLS:S3});[b3]=[];[S3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var o$,w3;var x3=v(()=>{$e();v3();o$=class o${static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new w3(e,this.columns,this.name)}};w3=class w3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[n$.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(p3(t)&&!YT(e)&&!oe(e,Mr)&&!oe(e,os)&&!oe(e,He)&&!oe(e,he)&&!oe(e,cn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function un(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function E3(e){return C`not ${e}`}function ss(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function db(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function A3(e){return C`${e} is not null`}function pb(e){return C`exists ${e}`}function as(e){return C`not exists ${e}`}function R3(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function T3(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function $3(e,t){return C`${e} like ${t}`}function O3(e,t){return C`${e} not like ${t}`}function C3(e,t){return C`${e} ilike ${t}`}function P3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,_3=(e,t)=>C`${e} <> ${$r(t,e)}`,kn=(e,t)=>C`${e} > ${$r(t,e)}`,I3=(e,t)=>C`${e} >= ${$r(t,e)}`,k3=(e,t)=>C`${e} < ${$r(t,e)}`,is=(e,t)=>C`${e} <= ${$r(t,e)}`;var z3=v(()=>{En();$e();sr();Yt()});function Fo(e){return C`${e} asc`}function ba(e){return C`${e} desc`}var N3=v(()=>{Yt()});var i$=v(()=>{z3();N3()});function L3(){return{and:tt,between:R3,eq:je,exists:pb,gt:kn,gte:I3,ilike:C3,inArray:ss,isNull:qr,isNotNull:A3,like:$3,lt:k3,lte:is,ne:_3,not:E3,notBetween:T3,notExists:as,notLike:O3,notIlike:P3,notInArray:db,or:un,sql:C}}function B3(){return{sql:C,asc:Fo,desc:ba}}function j3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ya(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,o$))n[i].primaryKey.push(...d.columns)}}else if(oe(s,D3)){let a=ya(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Yme(e){return function(r,o){return new cs(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Xme(e){return function(r,o){return new Kp(e,r,o)}}function Z3(e,t,r){if(oe(r,cs)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ya(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ya(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],cs)&&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 U3(e){return{one:Yme(e),many:Xme(e)}}function fb(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,cs)?d&&fb(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>fb(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var s$,D3,cs,Kp;var Hp=v(()=>{sr();En();$e();x3();i$();Yt();s$=class s${constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};D3=class D3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};cs=class cs extends s${constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new cs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Kp=class Kp extends s${constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Kp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Vp(e,t){return new Proxy(e,new Sa(t,!1))}function io(e,t){return new Proxy(e,new Nl(new Proxy(e.table,new Sa(t,!1))))}function a$(e,t){return new Ee.Aliased(Wp(e.sql,t),e.fieldAlias)}function Wp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return io(r,t);if(oe(r,Ee))return Wp(r,t);if(oe(r,Ee.Aliased))return a$(r,t);return r}))}var Nl,Sa,ehe;var Gp=v(()=>{En();$e();Yt();sr();qo();Nl=class Nl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Sa=class Sa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Nl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Nl(new Proxy(e,this)));return r}};ehe=class ehe{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Vp(e.sourceTable,this.alias);return e[t]}}});var at;var va=v(()=>{Gp();En();$e();Yt();In();qo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,pt)?e._.selectedFields:oe(e,cn)?e[ft].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Nl(new Proxy(o.table,new Sa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Jo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var c$,M3;var l$=v(()=>{$e();Pl();c$=class c${static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new M3(e,this)}};M3=class M3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function u$(e,t){return`${e[ir]}_${t.join("_")}_unique`}var q3,the,F3;var d$=v(()=>{$e();Pl();q3=class q3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new F3(e,this.columns,this.name)}};the=class the{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new q3(e,this.name)}};F3=class F3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??u$(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Ut,bt;var ls=v(()=>{nb();En();$e();l$();d$();Ut=class Ut extends jp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new c$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};bt=class bt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=u$(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function Q3(e,t){let{name:r,config:o}=oo(e,t);if(o?.mode==="json")return new H3(r);if(o?.mode==="bigint")return new J3(r);return new W3(r)}var J3,K3,H3,V3,W3,G3;var p$=v(()=>{$e();Sr();ls();J3=class J3 extends Ut{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new K3(e,this.config)}};K3=class K3 extends bt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(e$.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};H3=class H3 extends Ut{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new V3(e,this.config)}};V3=class V3 extends bt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(e$.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};W3=class W3 extends Ut{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new G3(e,this.config)}};G3=class G3 extends bt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function e5(e){return(t,r)=>{let{name:o,config:n}=oo(t,r);return new Y3(o,n,e)}}var Y3,X3;var f$=v(()=>{$e();Sr();ls();Y3=class Y3 extends Ut{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new X3(e,this.config)}};X3=class X3 extends bt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=oo(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new n5(r,o.mode);if(o?.mode==="boolean")return new i5(r,o.mode);return new t5(r)}var mb,hb,t5,r5,n5,o5,i5,s5;var m$=v(()=>{$e();Yt();Sr();ls();mb=class mb extends Ut{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};hb=class hb extends bt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};t5=class t5 extends mb{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new r5(e,this.config)}};r5=class r5 extends hb{static[F]="SQLiteInteger"};n5=class n5 extends mb{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new o5(e,this.config)}};o5=class o5 extends hb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};i5=class i5 extends mb{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new s5(e,this.config)}};s5=class s5 extends hb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function f5(e,t){let{name:r,config:o}=oo(e,t),n=o?.mode;return n==="number"?new l5(r):n==="bigint"?new d5(r):new a5(r)}var a5,c5,l5,u5,d5,p5;var h$=v(()=>{$e();Sr();ls();a5=class a5 extends Ut{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new c5(e,this.config)}};c5=class c5 extends bt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};l5=class l5 extends Ut{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new u5(e,this.config)}};u5=class u5 extends bt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};d5=class d5 extends Ut{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new p5(e,this.config)}};p5=class p5 extends bt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function g5(e){return new m5(e??"")}var m5,h5;var g$=v(()=>{$e();ls();m5=class m5 extends Ut{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new h5(e,this.config)}};h5=class h5 extends bt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function mt(e,t={}){let{name:r,config:o}=oo(e,t);if(o.mode==="json")return new S5(r);return new y5(r,o)}var y5,b5,S5,v5;var y$=v(()=>{$e();Sr();ls();y5=class y5 extends Ut{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new b5(e,this.config)}};b5=class b5 extends bt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};S5=class S5 extends Ut{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new v5(e,this.config)}};v5=class v5 extends bt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function w5(){return{blob:Q3,customType:e5,integer:ar,numeric:f5,real:g5,text:mt}}var x5=v(()=>{p$();f$();m$();h$();g$();y$()});function rhe(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(w5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[b$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var b$,At,Qp=(e,t,r)=>rhe(e,t,r);var Ko=v(()=>{$e();sr();x5();b$=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:b$});[he.Symbol.Columns];[b$]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var nhe,_5;var E5=v(()=>{$e();nhe=class nhe{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new _5(e,this)}};_5=class _5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ho(e){return new I5(e,!1)}var I5,k5,A5;var R5=v(()=>{$e();I5=class I5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new k5(this.name,e,this.unique)}};k5=class k5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new A5(this.config,e)}};A5=class A5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var ohe,T5;var $5=v(()=>{$e();Ko();ohe=class ohe{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new T5(e,this.columns,this.name)}};T5=class T5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function An(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,pt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var Dl=v(()=>{$e();Yt();In();sr();Ko()});var gb;var O5=v(()=>{$e();Jo();va();Ko();sr();Sr();Dl();gb=class gb extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=ln(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:An(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 ihe(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function she(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function ahe(e){return e}var S$;var C5=v(()=>{$e();sr();S$=class S${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?ihe:e==="camelCase"?she:ahe}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Ll,Vo,v$;var yb=v(()=>{$e();Ll=class Ll extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Vo=class Vo extends Error{constructor(e,t,r){super(`Failed query: ${e}
429
429
  params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Vo),r)this.cause=r}};v$=class v$ extends Ll{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var P5=()=>{};var z5=()=>{};var N5=v(()=>{P5();z5()});var w$=v(()=>{i$();N5();Yt()});var x$=v(()=>{p$();ls();f$();m$();h$();g$();y$()});var Wo;var Yp=v(()=>{$e();Yt();Wo=class Wo extends cn{static[F]="SQLiteViewBase"}});var Bl,_$,E$;var bb=v(()=>{Gp();C5();En();$e();yb();Hp();w$();Yt();x$();Ko();In();sr();Sr();qo();Yp();Bl=class Bl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new S$(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,l=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${l}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[he.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],l=a.onUpdateFn?.(),u=t[i]??(oe(l,Ee)?l:C.param(l,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:l}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),p=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=r?C` where ${r}`:void 0,y=this.buildOrderBy(l),S=this.buildLimit(a);return C`${u}update ${e} set ${d}${p}${m}${b}${h}${y}${S}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,Ee.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,Ee.Aliased)||oe(n,Ee)){let a=oe(n,Ee.Aliased)?n.sql:n;if(t)s.push(new Ee(a.queryChunks.map((l)=>{if(oe(l,He))return C.identifier(this.casing.getColumnCasing(l));return l})));else s.push(a);if(oe(n,Ee.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,He)){let a=n.table[he.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,pt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let l=a[0][1],u=oe(l,Ee)?l.decoder:oe(l,He)?{mapFromDriverValue:(d)=>l.mapFromDriverValue(d)}:l.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,At)){let s=n[At.Symbol.Name],a=n[At.Symbol.Schema],l=n[At.Symbol.OriginalName],u=s===l?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(l)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,he)&&e[he.Symbol.IsAlias])return C`${C`${C.identifier(e[he.Symbol.Schema]??"")}.`.if(e[he.Symbol.Schema])}${C.identifier(e[he.Symbol.OriginalName])} ${C.identifier(e[he.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:l,limit:u,offset:d,distinct:p,setOperators:m}){let h=r??ln(t);for(let T of h)if(oe(T.field,He)&&ns(T.field.table)!==(oe(i,pt)?i._.alias:oe(i,Wo)?i[ft].name:oe(i,Ee)?void 0:ns(i))&&!((B)=>s?.some(({alias:I})=>I===(B[he.Symbol.IsAlias]?ns(B):B[he.Symbol.BaseName])))(T.field.table)){let B=ns(T.field.table);throw Error(`Your "${T.path.join("->")}" field references a column "${B}"."${T.field.name}", but the table "${B}" is not part of the query! Did you forget to join it?`)}let b=!s||s.length===0,y=this.buildWithCTE(e),S=p?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:b}),_=this.buildFromTable(i),A=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,z=[];if(l){for(let[T,B]of l.entries())if(z.push(B),T<l.length-1)z.push(C`, `)}let K=z.length>0?C` group by ${C.join(z)}`:void 0,P=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${S} ${x} from ${_}${A}${O}${K}${L}${P}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,l=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let b of i)if(oe(b,bt))h.push(C.identifier(b.name));else if(oe(b,Ee)){for(let y=0;y<b.queryChunks.length;y++){let S=b.queryChunks[y];if(oe(S,bt))b.queryChunks[y]=C.identifier(this.casing.getColumnCasing(S))}h.push(C`${b}`)}else h.push(C`${b}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,p=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${p}${l}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[he.Symbol.Columns],l=Object.entries(a).filter(([b,y])=>!y.shouldDisableInsert()),u=l.map(([,b])=>C.identifier(this.casing.getColumnCasing(b)));if(i){let b=t;if(oe(b,Ee))s.push(b);else s.push(b.getSQL())}else{let b=t;s.push(C.raw("values "));for(let[y,S]of b.entries()){let x=[];for(let[_,A]of l){let O=S[_];if(O===void 0||oe(O,Mr)&&O.value===void 0){let L;if(A.default!==null&&A.default!==void 0)L=oe(A.default,Ee)?A.default:C.param(A.default,A);else if(A.defaultFn!==void 0){let z=A.defaultFn();L=oe(z,Ee)?z:C.param(z,A)}else if(!A.default&&A.onUpdateFn!==void 0){let z=A.onUpdateFn();L=oe(z,Ee)?z:C.param(z,A)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<b.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),p=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${p}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:l}){let u=[],d,p,m=[],h,b=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:io(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(n.columns).map(([z,K])=>[z,io(K,s)]));if(i.where){let z=typeof i.where==="function"?i.where(S,L3()):i.where;h=z&&Wp(z,s)}let x=[],_=[];if(i.columns){let z=!1;for(let[K,P]of Object.entries(i.columns)){if(P===void 0)continue;if(K in n.columns){if(!z&&P===!0)z=!0;_.push(K)}}if(_.length>0)_=z?_.filter((K)=>i.columns?.[K]===!0):Object.keys(n.columns).filter((K)=>!_.includes(K))}else _=Object.keys(n.columns);for(let z of _){let K=n.columns[z];x.push({tsKey:z,value:K})}let A=[];if(i.with)A=Object.entries(i.with).filter((z)=>!!z[1]).map(([z,K])=>({tsKey:z,queryConfig:K,relation:n.relations[z]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(S,{sql:C}):i.extras;for(let[z,K]of Object.entries(O))x.push({tsKey:z,value:a$(K,s)})}for(let{tsKey:z,value:K}of x)u.push({dbKey:oe(K,Ee.Aliased)?K.fieldAlias:n.columns[z].name,tsKey:z,field:oe(K,He)?io(K,s):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(S,B3()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((z)=>{if(oe(z,He))return io(z,s);return Wp(z,s)}),d=i.limit,p=i.offset;for(let{tsKey:z,queryConfig:K,relation:P}of A){let W=Z3(t,r,P),ee=ya(P.referencedTable),j=r[ee],T=`${s}_${z}`,B=tt(...W.fields.map((k,q)=>je(io(W.references[q],T),io(k,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(P,cs)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:T,joinOn:B,nestedQueryRelation:P}),R=C`(${I.sql})`.as(z);u.push({dbKey:z,tsKey:z,field:R,relationTableTsKey:j,isJson:!0,selection:I.selection})}}if(u.length===0)throw new Ll({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(l,h),a){let S=C`json_array(${C.join(u.map(({field:A})=>oe(A,bt)?C.identifier(this.casing.getColumnCasing(A)):oe(A,Ee.Aliased)?A.sql:A),C`, `)})`;if(oe(a,Kp))S=C`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||p!==void 0||m.length>0)y=this.buildSelectQuery({table:Vp(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:p,orderBy:m,setOperators:[]}),h=void 0,d=void 0,p=void 0,m=void 0;else y=Vp(o,s);y=this.buildSelectQuery({table:oe(y,At)?y:new pt(y,{},s),fields:{},fieldsFlat:x.map(({field:A})=>({path:[],field:oe(A,He)?io(A,s):A})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:Vp(o,s),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:oe(S,He)?io(S,s):S})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};_$=class _$ extends Bl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
430
430
  CREATE TABLE IF NOT EXISTS ${C.identifier(o)} (
431
431
  id SERIAL PRIMARY KEY,
@@ -438,7 +438,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
438
438
  hash text NOT NULL,
439
439
  created_at numeric
440
440
  )
441
- `;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}});var I$;var D5=v(()=>{$e();I$=class I${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Sb(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Fp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var Rn,L5,k$,che=()=>({union:lhe,unionAll:uhe,intersect:dhe,except:phe}),lhe,uhe,dhe,phe;var A$=v(()=>{$e();D5();Jo();va();Yt();In();sr();Sr();qo();Dl();Yp();Rn=class Rn{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,pt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Wo))r=e[ft].selectedFields;else if(oe(e,Ee))r={};else r=lb(e);return new k$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};L5=class L5 extends I${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Jp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of An(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=Jp(t);for(let i of An(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,Ee)){let i=oe(t,pt)?t._.selectedFields:oe(t,cn)?t[ft].selectedFields:t[he.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(che()):r;if(!Fp(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...An(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...An(r.table));return new Proxy(new pt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};k$=class k$ extends L5{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=ln(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()}};h3(k$,[vr]);lhe=Sb("union",!1),uhe=Sb("union",!0),dhe=Sb("intersect",!1),phe=Sb("except",!1)});var wa;var vb=v(()=>{$e();va();bb();In();A$();wa=class wa{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,Bl)?e:void 0,this.dialectConfig=oe(e,Bl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new _$(this.dialectConfig);return this.dialect}}});var wb,R$;var B5=v(()=>{$e();Jo();Yt();Ko();sr();Sr();Dl();vb();wb=class wb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[he.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,Ee)?s:new Mr(s,n[i])}return o});return new R$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new wa):e;if(!oe(t,Ee)&&!Fp(this.table[sb],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 R$(this.table,t,this.session,this.dialect,this.withList,!0)}};R$=class R$ extends vr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=ln(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,cb(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:An(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 xb,j5;var Z5=v(()=>{$e();Jo();va();Ko();In();sr();Sr();qo();Dl();Yp();xb=class xb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new j5(this.table,cb(this.table,e),this.session,this.dialect,this.withList)}};j5=class j5 extends vr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=Jp(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,At)?t[he.Symbol.Columns]:oe(t,pt)?t._.selectedFields:oe(t,Wo)?t[ft].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=ln(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:An(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 T$=v(()=>{O5();B5();vb();A$();Z5()});var Xp;var U5=v(()=>{$e();Yt();Xp=class Xp extends Ee{constructor(e){super(Xp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Xp.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var O$,_b,$$;var M5=v(()=>{$e();Jo();Hp();O$=class O${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new $$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new _b(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new $$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new _b(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};_b=class _b extends vr{constructor(e,t,r,o,n,i,s,a,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=l}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>fb(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};$$=class $$ extends _b{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var jl;var q5=v(()=>{$e();Jo();jl=class jl extends vr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var ef;var Eb=v(()=>{$e();va();Yt();T$();In();U5();M5();q5();ef=class ef{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new O$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new wa(r.dialect));return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Xp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new xb(a,t.session,t.dialect,e)}function i(a){return new wb(a,t.session,t.dialect,e)}function s(a){return new gb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new xb(e,this.session,this.dialect)}$cache;insert(e){return new wb(e,this.session,this.dialect)}delete(e){return new gb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(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 C$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((l)=>l.toString(16).padStart(2,"0")).join("")}var F5,tf;var P$=v(()=>{$e();F5=class F5{static[F]="Cache"};tf=class tf extends F5{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var J5=v(()=>{P$()});function Ib(e,t){return new Proxy(e,new Sa(t,!1))}var K5=v(()=>{Gp()});var H5,z$,N$,D$;var L$=v(()=>{P$();$e();yb();Jo();Eb();H5=class H5 extends vr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};z$=class z${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,tf)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Vo(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Vo(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await C$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Vo(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await C$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Vo(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new H5(()=>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)}}};N$=class N${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Ll({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")}};D$=class D$ extends ef{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new v$}}});var B$,fhe,mhe,kb;var V5=v(()=>{$e();va();Sr();vb();Ko();Yp();B$=class B${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};fhe=class fhe extends B${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new wa);let t=new at({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)}};mhe=class mhe extends B${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=lb(Qp(e,t))}existing(){return new Proxy(new kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};kb=class kb extends Wo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var Ab=v(()=>{K5();E5();x$();Eb();bb();l$();R5();$5();T$();L$();Ko();d$();Dl();V5()});function W5(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Rb(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 Tb,j$,G5;var Z$=v(()=>{J5();$e();ub();Yt();Ab();L$();Sr();Tb=class Tb extends N${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new r$,this.cache=o.cache??new tf}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new G5(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new Tb(this.client,this.dialect,this.schema,this.options,r),n=new j$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};j$=class j$ extends D${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new j$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};G5=class G5 extends z${constructor(e,t,r,o,n,i,s,a,l,u,d){super("async",l,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>W5(r));if(this.customResultMapper)return this.customResultMapper(e,Rb);return e.map((r)=>XT(this.fields,Array.prototype.slice.call(r).map((o)=>Rb(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return W5(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Rb);return XT(this.fields,Array.prototype.slice.call(r).map((o)=>Rb(o)),this.joinsNotNullableMap)}async values(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Zl(e,t={}){let r=new E$({casing:t.casing}),o;if(t.logger===!0)o=new t$;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=j3(t.schema,U3);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new Tb(e,r,n,{logger:o,cache:t.cache},void 0),s=new Q5("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var Q5;var Y5=v(()=>{$e();ub();Hp();Eb();bb();Z$();Q5=class Q5 extends ef{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function $b(...e){if(typeof e[0]==="string"){let t=Cl({url:e[0]});return Zl(t,e[1])}if(g3(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return Zl(r,o);let n=typeof t==="string"?Cl({url:t}):Cl(t);return Zl(n,o)}return Zl(e[0],e[1])}var X5=v(()=>{MT();Sr();Y5();((e)=>{function t(r){return Zl({},r)}e.mock=t})($b||($b={}))});var e8=v(()=>{X5();Z$()});function hhe(){return new Promise((e)=>setTimeout(e,0))}function yhe(){if(U$)return;U$=!0,setTimeout(()=>{U$=!1,M$=performance.now()},0)}async function rf(e=ghe){if(yhe(),performance.now()-M$<e)return;await hhe(),M$=performance.now()}var ghe=50,M$,U$=!1;var t8=v(()=>{M$=performance.now()});function r8(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function whe(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Ob(e,t){let r=Date.now()+(t.budgetMs??bhe),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!whe(i))throw i;await t.afterRefusal?.();let s=Math.min(She*2**(n-1),vhe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((l)=>setTimeout(l,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function q$(e,t={}){let r=Cl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),l=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(p,m){return await rf(),Ob(()=>typeof p==="string"?s(p,m):s(p),u)}r.execute=d,r.batch=async(p,m)=>(await rf(),Ob(()=>a(p,m),u)),r.migrate=async(p)=>(await rf(),Ob(()=>l(p),u)),r.transaction=async(p)=>(await rf(),Ob(()=>o(p),u))}return r}function Cb(e){let{url:t,schema:r}=e,o=r8(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?q$({url:t,authToken:o},n):q$({url:t},n);return{db:$b(i,{schema:r}),client:i,url:t}}async function Pb(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var bhe=5000,She=5,vhe=40;var F$=v(()=>{MT();e8();t8()});var n8=v(()=>{nT();F$()});var J$=v(()=>{F$();n8()});var K$=v(()=>{Gp();nb();En();$e();yb();ub();Jo();Hp();w$();In();sr();Sr();qo()});var Y,Me;var H$=v(()=>{Ab();K$();hp();Y=Qp("job_queue",{id:mt("id").primaryKey().$defaultFn(()=>Lo()),type:mt("type").notNull(),data:mt("data").notNull(),result:mt("result",{mode:"json"}),progress:mt("progress",{mode:"json"}).$type(),source:mt("source"),metadata:mt("metadata",{mode:"json"}).$type().notNull(),status:mt("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:mt("lastError"),lastErrorPublic:mt("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:mt("attemptId"),workerSlotId:mt("workerSlotId"),workerSessionId:mt("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:mt("brainVersion"),brainVersionSortKey:mt("brainVersionSortKey")},(e)=>({queueReadyIdx:Ho("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Ho("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Ho("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Ho("idx_job_queue_source").on(e.source),rootJobIdx:Ho("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Ho("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),Me=Qp("job_worker_sessions",{slotId:mt("slotId").primaryKey(),sessionId:mt("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:mt("brainVersion"),brainVersionSortKey:mt("brainVersionSortKey"),stableSlotId:mt("stableSlotId")},(e)=>({heartbeatIdx:Ho("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Ho("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function o8(e){return Cb({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:Me},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var i8=v(()=>{J$();H$()});class V${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 W${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class G${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=xhe.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var xhe;var s8=v(()=>{pe();Bo();xhe=c.looseObject({deduplicationKey:c.string().optional()})});function l8(e){return`${String(e.length).padStart(2,"0")}${e}`}function Ehe(e){return _he.test(e)?`0${l8(e)}`:`1${e}`}function nf(e){let t=a8.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(l8).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(Ehe).join("!")}`}var a8,_he,c8;var Q$=v(()=>{pe();a8=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,_he=/^\d+$/u,c8=c.string().regex(a8,"Brain version must be a semver version")});function u8(e){return JSON.stringify(new ui(e).toJSON())}class Y${db;transactionClient;databaseUrl;logger;deduplicator=new G$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??Ihe}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return The.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,l=!0;if(!o.closed)try{await o.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!l)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",l=async()=>{await s?.(),r()},u=async()=>{await l(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),p=this.deduplicator.findDuplicate(d,a,i);if(!p)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,p.id,o),{kind:"skipped",jobId:p.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,p.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await l();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",u8("cancelled"),m,m,p.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=nf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?nf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(khe*2**(o-1),Ahe),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ve(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=Hi,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?nf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(Me).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:Me.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=Hi){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(Me).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,Me.slotId),je(Y.workerSessionId,Me.sessionId),je(Y.status,Oe.PROCESSING),kn(Y.leaseExpiresAt,e)));await this.db.delete(Me).where(tt(is(Me.expiresAt,e-t),as(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Me).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async release(e,t,r=Date.now()){return(await this.write("release",async()=>this.db.update(Y).set({status:Oe.PENDING,scheduledFor:r,startedAt:null,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?o+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:ih(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new ui("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),un(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),qr(Y.attemptId),qr(Y.workerSlotId),qr(Y.workerSessionId),qr(Y.leaseExpiresAt),qr(Y.attemptHeartbeatAt),qr(Y.progress),qr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(Fo(Y.createdAt),Fo(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(ba(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${Me.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${Me.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${Me.heartbeatAt})`}).from(Me)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:l(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=Rhe.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(Fo(Y.runtimeUpdatedAt),Fo(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(un(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),is(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=un(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,ss(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?ss(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,ss(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:l}=e,u=l?this.brainVersionGate(l,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,o),je(Me.sessionId,n),kn(Me.expiresAt,t))),p=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,Y.workerSlotId),je(Me.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),un(qr(Y.attemptId),as(m),is(Y.leaseExpiresAt,t))),b=Ib(Y,"running"),y=this.db.select({id:b.id}).from(b).where(tt(je(b.type,Y.type),je(b.status,Oe.PROCESSING),kn(b.leaseExpiresAt,t),C`${b.id} <> ${Y.id}`)),S=a.length===0?void 0:un(db(Y.type,[...a]),as(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(ss(Y.type,s),S,u.admissible,un(tt(je(Y.status,Oe.PENDING),is(Y.scheduledFor,t)),h))).orderBy(Fo(Y.priority),Fo(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${u8("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(ss(Y.id,_),pb(d),p,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=Ib(Me,"claimer"),n=Ib(Me,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),kn(n.expiresAt,r),un(kn(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),kn(n.slotId,o.slotId)))));return as(i)}brainVersionGate(e,t){let r=nf(e),o=this.db.select({slotId:Me.slotId}).from(Me).where(tt(kn(Me.expiresAt,t),kn(Me.brainVersionSortKey,r)));return{admissible:un(qr(Y.brainVersionSortKey),is(Y.brainVersionSortKey,r)),noNewerWorker:as(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),qr(Y.attemptId),un(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var Ihe=2000,khe=5,Ahe=40,Rhe,The;var d8=v(()=>{K$();Ab();H$();Tt();pe();Bo();yp();s8();Q$();Rhe=c.number().int().min(0).max(1000),The=new W$});import{AsyncLocalStorage as $he}from"async_hooks";class Ul{storage=new $he;static createFresh(){return new Ul}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=fo.parse(e),n=Ohe(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function Ohe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var zb=v(()=>{Tt()});class of{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Lo()}`;directWorkerSessionId=Lo();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new of(e,t??Rr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:c8.parse(e.brainVersion);let{db:o,client:n,url:i}=o8(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Ul.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new V$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new Y$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Pb(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Lo(),l=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,l,o),d=o?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},b,y=()=>{b?.rollback(),b=void 0};try{let S=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{b=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(b?.commit(),b=void 0,S.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:S.jobId});else if(S.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:S.jobId});else{if(S.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:S.replacedJobId});this.logger.debug("Job enqueued",{id:S.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return S.jobId}catch(S){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ve(S)}),S}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,l=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return fo.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:Lo(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=Hi){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=Hi){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}release(e,t){return this.repository.release(e,t)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(l)};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 p8=v(()=>{hp();nT();yp();Bo();J$();i8();d8();Tt();zb();Q$()});var X$=()=>{};var f8=v(()=>{hp();Bo();yp();Bo();X$();zb()});var m8=v(()=>{Bo();X$()});var Nb,h8;var eO=v(()=>{pe();Nb=c.object({success:c.boolean(),data:c.unknown().optional(),error:c.string().optional(),code:c.string().optional()}),h8=c.object({id:c.string().min(1),timestamp:c.string(),type:c.string().min(1),source:c.string().min(1),target:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()})});var f3e;var g8=v(()=>{pe();eO();f3e=c.union([c.object({noop:c.literal(!0)}),Nb])});var Db=v(()=>{g8()});var y8=v(()=>{Db()});var b8=v(()=>{Db()});var S8=v(()=>{b8()});var O3e;var tO=v(()=>{pe();O3e=c.looseObject({issues:c.array(c.looseObject({message:c.string()})).optional()})});var v8=v(()=>{y8();Db();S8();tO();Tt();zb()});var Uhe;var w8=v(()=>{pe();eO();Uhe=c.object({id:c.string().min(1),requestId:c.string().min(1),success:c.boolean(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional(),timestamp:c.string().datetime()})});var W3e;var x8=v(()=>{Tt();W3e=new ui("invalid_response").toJSON()});var _8=v(()=>{v8();w8();tO();x8()});var m5e;var E8=v(()=>{pe();_8();gp();Bo();m5e=c.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},c.record(c.string(),c.unknown()))});var y5e;var I8=v(()=>{pe();y5e=c.record(c.string(),c.unknown())});var k8=v(()=>{Tt();hp()});var A8=v(()=>{p8();f8();m8();E8();I8();yp();Bo();gp();k8()});var rO={};Lt(rO,{LEGACY_PROJECTION_JOB_TYPES:()=>T8,LEGACY_PROJECTION_RETIREMENT_REASON:()=>O8,legacyProjectionJobTypeSchema:()=>$8,retireLegacyProjectionJob:()=>Khe});import{existsSync as qhe}from"fs";import{resolve as Fhe}from"path";function R8(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 Jhe(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 Khe(e){let t=Fhe(e.databasePath);if(!qhe(t))throw Error(`Job database does not exist: ${t}`);let r=$8.parse(e.jobType),o=of.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(Jhe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:R8(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:O8,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:R8(s),retired:!0}}finally{o.close()}}var T8,$8,O8="Retired legacy projection job superseded by scheduler-owned projections";var nO=v(()=>{A8();pe();T8=["conversation-memory:project","skill:project","swot:derive","topic:project"],$8=c.enum(T8)});function Mt(e,t,r,o,n){return P8.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function iO(e){return af.parse(structuredClone(Ghe[e]))}function cf(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 Bb(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let l=await r(e,{method:"GET",signal:s.signal});return await l.arrayBuffer(),oO.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:l.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:l.ok})}catch(l){return oO.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:Qhe(l)})}finally{clearTimeout(a)}}async function sO(e,t){let r=af.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(l){n=`monitor: ${Lb(l)}`}if(!n)for(let l of r.phases)try{let u=z8.parse(await t.executePhase(l,i));if(o.push(u),!u.success){n=`${l.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=Lb(u);o.push({id:l.id,operation:l.operation,count:l.count,success:!1,error:d}),n=`${l.id}: ${d}`;break}}finally{try{if(s=N8.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(l){let u=Lb(l);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=D8.parse(await t.stopMonitoring())}catch(l){let u=Lb(l);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=B8(a,r.maximumExternalAiCalls??0),L8.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function B8(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Qhe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Lb(e){return Ve(e)}var sf,C8,P8,af,Hhe,oO,Vhe,z8,N8,Whe,D8,L8,Ghe;var jb=v(()=>{pe();sf=c.enum(["regression","load","stress"]),C8=c.enum(["add","update","rename","delete"]),P8=c.object({id:c.string().min(1),operation:C8,count:c.number().int().positive().max(700),targetProbeCount:c.number().int().min(0).max(700),settleMs:c.number().int().nonnegative().max(300000)}),af=c.object({profile:sf,maximumProbeCount:c.number().int().positive().max(700),maximumExternalAiCalls:c.number().int().nonnegative().max(1e4).optional(),phases:c.array(P8).min(1)}),Hhe=c.object({entities:c.number().int().nonnegative(),notes:c.number().int().nonnegative(),version:c.string().min(1)}),oO=c.object({timestamp:c.iso.datetime(),endpoint:c.string().startsWith("/"),status:c.number().int().nonnegative(),durationMs:c.number().nonnegative(),ok:c.boolean(),error:c.string().optional()}),Vhe=c.object({timestamp:c.iso.datetime(),cpuPercent:c.number().nonnegative(),memoryPercent:c.number().nonnegative(),pids:c.number().int().nonnegative()}),z8=c.object({id:c.string().min(1),operation:C8,count:c.number().int().positive(),success:c.boolean(),commitLatencyMs:c.number().nonnegative().optional(),persistenceLatencyMs:c.number().nonnegative().optional(),error:c.string().optional()}),N8=c.object({success:c.boolean(),probesRemaining:c.number().int().nonnegative(),finalEntities:c.number().int().nonnegative().optional(),finalNotes:c.number().int().nonnegative().optional(),contentTreeRestored:c.boolean().optional(),error:c.string().optional()}),Whe=c.object({status:c.string(),restartCount:c.number().int().nonnegative(),oomKilled:c.boolean()}),D8=c.object({health:c.array(oO),runtime:c.array(Vhe),externalAiCalls:c.number().int().nonnegative().optional(),container:Whe.optional()}),L8=c.object({profile:sf,success:c.boolean(),baseline:Hhe,phases:c.array(z8),cleanup:N8,metrics:D8,failure:c.string().optional()}),Ghe={regression:{profile:"regression",maximumProbeCount:20,phases:[Mt("add20","add",20,20,0),Mt("update20","update",20,20,30000),Mt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Mt("add50","add",50,50,0),Mt("add150","add",100,150,0),Mt("add350","add",200,350,0),Mt("update350a","update",350,350,45000),Mt("rename100","rename",100,350,45000),Mt("update350b","update",350,350,45000),Mt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Mt("add50","add",50,50,0),Mt("add150","add",100,150,0),Mt("add350","add",200,350,0),Mt("add700","add",350,700,0),Mt("update700a","update",700,700,45000),Mt("rename200","rename",200,700,45000),Mt("update700b","update",700,700,45000),Mt("delete700","delete",700,0,150000)]}}});import{spawn as Yhe}from"child_process";async function j8(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw so(t,r,n);return n}function so(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var Go=async(e,t,r={})=>new Promise((o,n)=>{let i=Yhe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(l)=>{s+=l}),i.stderr.on("data",(l)=>{a+=l}),i.on("error",n),i.on("close",(l)=>{o({exitCode:l??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var lf=()=>{};class Ml{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new Ml(e,r,o);return await j8(e,"git",["-c","credential.helper=","-c",`credential.helper=${Z8}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",Z8]),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 so("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 Z8='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var U8=v(()=>{lf()});function uf(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class aO{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await Bb(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#f()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#p(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#p(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return Xhe.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#p(e,t,r){return e!==void 0&&(t===void 0||uf(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await Bb(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#f(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var M8,Xhe;var q8=v(()=>{pe();jb();M8=c.array(c.object({entityType:c.string(),count:c.number().int().nonnegative()})),Xhe=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),app:c.object({version:c.string()})})});var Zb={};Lt(Zb,{applyDirectorySyncStressPhase:()=>G8,cleanupDirectorySyncStress:()=>H8,listProbeFiles:()=>xa,parseStressRuntimeSample:()=>Q8,removeProbeFiles:()=>mO,runDeployedDirectorySyncStress:()=>J8,runStressCommand:()=>Go,verifyDirectorySyncStressAccess:()=>K8});import{chmod as ege,mkdir as lO,mkdtemp as uO,readFile as tge,readdir as rge,rename as nge,rm as pf,writeFile as Tn}from"fs/promises";import{tmpdir as dO}from"os";import{join as ct,resolve as pO}from"path";async function J8(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=hO(r),n=pO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await lO(n,{recursive:!0});let{pilot:i,user:s}=await fO(e.rootDir,e.handle);cf({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=sf.parse(e.profile),l=e.plan?af.parse(e.plan):iO(a);if(l.profile!==a)throw Error(`Directory-sync stress plan profile ${l.profile} does not match requested profile ${a}`);if((l.maximumExternalAiCalls??0)===0)W8(s);let u=oge.parse(e.env??process.env),d=new V8({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??Go,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),p;try{p=await sO(l,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:p};return await uge(m),m}async function K8(e){let r=(e.now??(()=>new Date))().toISOString(),o=hO(r),n=pO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await lO(n,{recursive:!0});let{pilot:i,user:s}=await fO(e.rootDir,e.handle);cf({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),W8(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let l=await uO(ct(dO(),"brains-ops-directory-sync-access-check-"));try{let u=await Ml.clone(e.commandRunner??Go,`${i.githubOrg}/${s.contentRepo}`,ct(l,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let p={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await Tn(ct(n,"access-check.json"),`${JSON.stringify(p,null,2)}
441
+ `;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}});var I$;var D5=v(()=>{$e();I$=class I${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Sb(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Fp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var Rn,L5,k$,che=()=>({union:lhe,unionAll:uhe,intersect:dhe,except:phe}),lhe,uhe,dhe,phe;var A$=v(()=>{$e();D5();Jo();va();Yt();In();sr();Sr();qo();Dl();Yp();Rn=class Rn{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,pt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Wo))r=e[ft].selectedFields;else if(oe(e,Ee))r={};else r=lb(e);return new k$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};L5=class L5 extends I${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Jp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of An(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=Jp(t);for(let i of An(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,Ee)){let i=oe(t,pt)?t._.selectedFields:oe(t,cn)?t[ft].selectedFields:t[he.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(che()):r;if(!Fp(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...An(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...An(r.table));return new Proxy(new pt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};k$=class k$ extends L5{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=ln(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()}};h3(k$,[vr]);lhe=Sb("union",!1),uhe=Sb("union",!0),dhe=Sb("intersect",!1),phe=Sb("except",!1)});var wa;var vb=v(()=>{$e();va();bb();In();A$();wa=class wa{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,Bl)?e:void 0,this.dialectConfig=oe(e,Bl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new _$(this.dialectConfig);return this.dialect}}});var wb,R$;var B5=v(()=>{$e();Jo();Yt();Ko();sr();Sr();Dl();vb();wb=class wb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[he.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,Ee)?s:new Mr(s,n[i])}return o});return new R$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new wa):e;if(!oe(t,Ee)&&!Fp(this.table[sb],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 R$(this.table,t,this.session,this.dialect,this.withList,!0)}};R$=class R$ extends vr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=ln(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,cb(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:An(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 xb,j5;var Z5=v(()=>{$e();Jo();va();Ko();In();sr();Sr();qo();Dl();Yp();xb=class xb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new j5(this.table,cb(this.table,e),this.session,this.dialect,this.withList)}};j5=class j5 extends vr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=Jp(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,At)?t[he.Symbol.Columns]:oe(t,pt)?t._.selectedFields:oe(t,Wo)?t[ft].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=ln(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:An(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 T$=v(()=>{O5();B5();vb();A$();Z5()});var Xp;var U5=v(()=>{$e();Yt();Xp=class Xp extends Ee{constructor(e){super(Xp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Xp.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var O$,_b,$$;var M5=v(()=>{$e();Jo();Hp();O$=class O${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new $$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new _b(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new $$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new _b(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};_b=class _b extends vr{constructor(e,t,r,o,n,i,s,a,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=l}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>fb(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};$$=class $$ extends _b{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var jl;var q5=v(()=>{$e();Jo();jl=class jl extends vr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var ef;var Eb=v(()=>{$e();va();Yt();T$();In();U5();M5();q5();ef=class ef{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new O$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new wa(r.dialect));return new Proxy(new Up(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Xp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new xb(a,t.session,t.dialect,e)}function i(a){return new wb(a,t.session,t.dialect,e)}function s(a){return new gb(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new xb(e,this.session,this.dialect)}$cache;insert(e){return new wb(e,this.session,this.dialect)}delete(e){return new gb(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new jl(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 C$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((l)=>l.toString(16).padStart(2,"0")).join("")}var F5,tf;var P$=v(()=>{$e();F5=class F5{static[F]="Cache"};tf=class tf extends F5{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var J5=v(()=>{P$()});function Ib(e,t){return new Proxy(e,new Sa(t,!1))}var K5=v(()=>{Gp()});var H5,z$,N$,D$;var L$=v(()=>{P$();$e();yb();Jo();Eb();H5=class H5 extends vr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};z$=class z${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,tf)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Vo(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Vo(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Vo(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await C$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Vo(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await C$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Vo(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new H5(()=>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)}}};N$=class N${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Ll({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")}};D$=class D$ extends ef{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new v$}}});var B$,fhe,mhe,kb;var V5=v(()=>{$e();va();Sr();vb();Ko();Yp();B$=class B${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};fhe=class fhe extends B${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new wa);let t=new at({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)}};mhe=class mhe extends B${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=lb(Qp(e,t))}existing(){return new Proxy(new kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new kb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};kb=class kb extends Wo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var Ab=v(()=>{K5();E5();x$();Eb();bb();l$();R5();$5();T$();L$();Ko();d$();Dl();V5()});function W5(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Rb(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 Tb,j$,G5;var Z$=v(()=>{J5();$e();ub();Yt();Ab();L$();Sr();Tb=class Tb extends N${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new r$,this.cache=o.cache??new tf}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new G5(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new Tb(this.client,this.dialect,this.schema,this.options,r),n=new j$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};j$=class j$ extends D${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new j$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};G5=class G5 extends z${constructor(e,t,r,o,n,i,s,a,l,u,d){super("async",l,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>W5(r));if(this.customResultMapper)return this.customResultMapper(e,Rb);return e.map((r)=>XT(this.fields,Array.prototype.slice.call(r).map((o)=>Rb(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=qp(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return W5(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Rb);return XT(this.fields,Array.prototype.slice.call(r).map((o)=>Rb(o)),this.joinsNotNullableMap)}async values(e){let t=qp(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Zl(e,t={}){let r=new E$({casing:t.casing}),o;if(t.logger===!0)o=new t$;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=j3(t.schema,U3);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new Tb(e,r,n,{logger:o,cache:t.cache},void 0),s=new Q5("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var Q5;var Y5=v(()=>{$e();ub();Hp();Eb();bb();Z$();Q5=class Q5 extends ef{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function $b(...e){if(typeof e[0]==="string"){let t=Cl({url:e[0]});return Zl(t,e[1])}if(g3(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return Zl(r,o);let n=typeof t==="string"?Cl({url:t}):Cl(t);return Zl(n,o)}return Zl(e[0],e[1])}var X5=v(()=>{MT();Sr();Y5();((e)=>{function t(r){return Zl({},r)}e.mock=t})($b||($b={}))});var e8=v(()=>{X5();Z$()});function hhe(){return new Promise((e)=>setTimeout(e,0))}function yhe(){if(U$)return;U$=!0,setTimeout(()=>{U$=!1,M$=performance.now()},0)}async function rf(e=ghe){if(yhe(),performance.now()-M$<e)return;await hhe(),M$=performance.now()}var ghe=50,M$,U$=!1;var t8=v(()=>{M$=performance.now()});function r8(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function whe(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function Ob(e,t){let r=Date.now()+(t.budgetMs??bhe),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!whe(i))throw i;await t.afterRefusal?.();let s=Math.min(She*2**(n-1),vhe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((l)=>setTimeout(l,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function q$(e,t={}){let r=Cl({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),l=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(p,m){return await rf(),Ob(()=>typeof p==="string"?s(p,m):s(p),u)}r.execute=d,r.batch=async(p,m)=>(await rf(),Ob(()=>a(p,m),u)),r.migrate=async(p)=>(await rf(),Ob(()=>l(p),u)),r.transaction=async(p)=>(await rf(),Ob(()=>o(p),u))}return r}function Cb(e){let{url:t,schema:r}=e,o=r8(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?q$({url:t,authToken:o},n):q$({url:t},n);return{db:$b(i,{schema:r}),client:i,url:t}}async function Pb(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var bhe=5000,She=5,vhe=40;var F$=v(()=>{MT();e8();t8()});var n8=v(()=>{nT();F$()});var J$=v(()=>{F$();n8()});var K$=v(()=>{Gp();nb();En();$e();yb();ub();Jo();Hp();w$();In();sr();Sr();qo()});var Y,Me;var H$=v(()=>{Ab();K$();hp();Y=Qp("job_queue",{id:mt("id").primaryKey().$defaultFn(()=>Lo()),type:mt("type").notNull(),data:mt("data").notNull(),result:mt("result",{mode:"json"}),progress:mt("progress",{mode:"json"}).$type(),source:mt("source"),metadata:mt("metadata",{mode:"json"}).$type().notNull(),status:mt("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:mt("lastError"),lastErrorPublic:mt("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:mt("attemptId"),workerSlotId:mt("workerSlotId"),workerSessionId:mt("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:mt("brainVersion"),brainVersionSortKey:mt("brainVersionSortKey")},(e)=>({queueReadyIdx:Ho("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Ho("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Ho("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Ho("idx_job_queue_source").on(e.source),rootJobIdx:Ho("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Ho("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),Me=Qp("job_worker_sessions",{slotId:mt("slotId").primaryKey(),sessionId:mt("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:mt("brainVersion"),brainVersionSortKey:mt("brainVersionSortKey"),stableSlotId:mt("stableSlotId")},(e)=>({heartbeatIdx:Ho("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Ho("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function o8(e){return Cb({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:Me},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var i8=v(()=>{J$();H$()});class V${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 W${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class G${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=xhe.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var xhe;var s8=v(()=>{pe();Bo();xhe=c.looseObject({deduplicationKey:c.string().optional()})});function l8(e){return`${String(e.length).padStart(2,"0")}${e}`}function Ehe(e){return _he.test(e)?`0${l8(e)}`:`1${e}`}function nf(e){let t=a8.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(l8).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(Ehe).join("!")}`}var a8,_he,c8;var Q$=v(()=>{pe();a8=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,_he=/^\d+$/u,c8=c.string().regex(a8,"Brain version must be a semver version")});function u8(e){return JSON.stringify(new ui(e).toJSON())}class Y${db;transactionClient;databaseUrl;logger;deduplicator=new G$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??Ihe}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return The.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,l=!0;if(!o.closed)try{await o.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!l)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",l=async()=>{await s?.(),r()},u=async()=>{await l(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),p=this.deduplicator.findDuplicate(d,a,i);if(!p)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,p.id,o),{kind:"skipped",jobId:p.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,p.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await l();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",u8("cancelled"),m,m,p.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=nf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?nf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(khe*2**(o-1),Ahe),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ve(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=Hi,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?nf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(Me).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:Me.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=Hi){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(Me).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,Me.slotId),je(Y.workerSessionId,Me.sessionId),je(Y.status,Oe.PROCESSING),kn(Y.leaseExpiresAt,e)));await this.db.delete(Me).where(tt(is(Me.expiresAt,e-t),as(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Me).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async release(e,t,r=Date.now()){return(await this.write("release",async()=>this.db.update(Y).set({status:Oe.PENDING,scheduledFor:r,startedAt:null,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?o+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:ih(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new ui("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),un(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),qr(Y.attemptId),qr(Y.workerSlotId),qr(Y.workerSessionId),qr(Y.leaseExpiresAt),qr(Y.attemptHeartbeatAt),qr(Y.progress),qr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(Fo(Y.createdAt),Fo(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(ba(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${Me.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${Me.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${Me.heartbeatAt})`}).from(Me)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:l(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=Rhe.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(Fo(Y.runtimeUpdatedAt),Fo(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(un(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),is(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=un(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,ss(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?ss(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,ss(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:l}=e,u=l?this.brainVersionGate(l,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,o),je(Me.sessionId,n),kn(Me.expiresAt,t))),p=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,Y.workerSlotId),je(Me.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),un(qr(Y.attemptId),as(m),is(Y.leaseExpiresAt,t))),b=Ib(Y,"running"),y=this.db.select({id:b.id}).from(b).where(tt(je(b.type,Y.type),je(b.status,Oe.PROCESSING),kn(b.leaseExpiresAt,t),C`${b.id} <> ${Y.id}`)),S=a.length===0?void 0:un(db(Y.type,[...a]),as(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(ss(Y.type,s),S,u.admissible,un(tt(je(Y.status,Oe.PENDING),is(Y.scheduledFor,t)),h))).orderBy(Fo(Y.priority),Fo(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${u8("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(ss(Y.id,_),pb(d),p,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=Ib(Me,"claimer"),n=Ib(Me,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),kn(n.expiresAt,r),un(kn(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),kn(n.slotId,o.slotId)))));return as(i)}brainVersionGate(e,t){let r=nf(e),o=this.db.select({slotId:Me.slotId}).from(Me).where(tt(kn(Me.expiresAt,t),kn(Me.brainVersionSortKey,r)));return{admissible:un(qr(Y.brainVersionSortKey),is(Y.brainVersionSortKey,r)),noNewerWorker:as(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),qr(Y.attemptId),un(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var Ihe=2000,khe=5,Ahe=40,Rhe,The;var d8=v(()=>{K$();Ab();H$();Tt();pe();Bo();yp();s8();Q$();Rhe=c.number().int().min(0).max(1000),The=new W$});import{AsyncLocalStorage as $he}from"async_hooks";class Ul{storage=new $he;static createFresh(){return new Ul}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=fo.parse(e),n=Ohe(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function Ohe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var zb=v(()=>{Tt()});class of{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Lo()}`;directWorkerSessionId=Lo();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new of(e,t??Rr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:c8.parse(e.brainVersion);let{db:o,client:n,url:i}=o8(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Ul.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new V$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new Y$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Pb(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Lo(),l=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,l,o),d=o?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},b,y=()=>{b?.rollback(),b=void 0};try{let S=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{b=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(b?.commit(),b=void 0,S.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:S.jobId});else if(S.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:S.jobId});else{if(S.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:S.replacedJobId});this.logger.debug("Job enqueued",{id:S.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return S.jobId}catch(S){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ve(S)}),S}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,l=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return fo.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:Lo(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=Hi){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=Hi){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}release(e,t){return this.repository.release(e,t)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(l)};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 p8=v(()=>{hp();nT();yp();Bo();J$();i8();d8();Tt();zb();Q$()});var X$=()=>{};var f8=v(()=>{hp();Bo();yp();Bo();X$();zb()});var m8=v(()=>{Bo();X$()});var Nb,h8;var eO=v(()=>{pe();Nb=c.object({success:c.boolean(),data:c.unknown().optional(),error:c.string().optional(),code:c.string().optional()}),h8=c.object({id:c.string().min(1),timestamp:c.string(),type:c.string().min(1),source:c.string().min(1),target:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()})});var h3e;var g8=v(()=>{pe();eO();h3e=c.union([c.object({noop:c.literal(!0)}),Nb])});var Db=v(()=>{g8()});var y8=v(()=>{Db()});var b8=v(()=>{Db()});var S8=v(()=>{b8()});var P3e;var tO=v(()=>{pe();P3e=c.looseObject({issues:c.array(c.looseObject({message:c.string()})).optional()})});var v8=v(()=>{y8();Db();S8();tO();Tt();zb()});var Uhe;var w8=v(()=>{pe();eO();Uhe=c.object({id:c.string().min(1),requestId:c.string().min(1),success:c.boolean(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional(),timestamp:c.string().datetime()})});var Q3e;var x8=v(()=>{Tt();Q3e=new ui("invalid_response").toJSON()});var _8=v(()=>{v8();w8();tO();x8()});var g5e;var E8=v(()=>{pe();_8();gp();Bo();g5e=c.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},c.record(c.string(),c.unknown()))});var S5e;var I8=v(()=>{pe();S5e=c.record(c.string(),c.unknown())});var k8=v(()=>{Tt();hp()});var A8=v(()=>{p8();f8();m8();E8();I8();yp();Bo();gp();k8()});var rO={};Lt(rO,{LEGACY_PROJECTION_JOB_TYPES:()=>T8,LEGACY_PROJECTION_RETIREMENT_REASON:()=>O8,legacyProjectionJobTypeSchema:()=>$8,retireLegacyProjectionJob:()=>Khe});import{existsSync as qhe}from"fs";import{resolve as Fhe}from"path";function R8(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 Jhe(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 Khe(e){let t=Fhe(e.databasePath);if(!qhe(t))throw Error(`Job database does not exist: ${t}`);let r=$8.parse(e.jobType),o=of.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(Jhe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:R8(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:O8,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:R8(s),retired:!0}}finally{o.close()}}var T8,$8,O8="Retired legacy projection job superseded by scheduler-owned projections";var nO=v(()=>{A8();pe();T8=["conversation-memory:project","skill:project","swot:derive","topic:project"],$8=c.enum(T8)});function Mt(e,t,r,o,n){return P8.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function iO(e){return af.parse(structuredClone(Ghe[e]))}function cf(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 Bb(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let l=await r(e,{method:"GET",signal:s.signal});return await l.arrayBuffer(),oO.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:l.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:l.ok})}catch(l){return oO.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:Qhe(l)})}finally{clearTimeout(a)}}async function sO(e,t){let r=af.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(l){n=`monitor: ${Lb(l)}`}if(!n)for(let l of r.phases)try{let u=z8.parse(await t.executePhase(l,i));if(o.push(u),!u.success){n=`${l.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=Lb(u);o.push({id:l.id,operation:l.operation,count:l.count,success:!1,error:d}),n=`${l.id}: ${d}`;break}}finally{try{if(s=N8.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(l){let u=Lb(l);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=D8.parse(await t.stopMonitoring())}catch(l){let u=Lb(l);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=B8(a,r.maximumExternalAiCalls??0),L8.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function B8(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Qhe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Lb(e){return Ve(e)}var sf,C8,P8,af,Hhe,oO,Vhe,z8,N8,Whe,D8,L8,Ghe;var jb=v(()=>{pe();sf=c.enum(["regression","load","stress"]),C8=c.enum(["add","update","rename","delete"]),P8=c.object({id:c.string().min(1),operation:C8,count:c.number().int().positive().max(700),targetProbeCount:c.number().int().min(0).max(700),settleMs:c.number().int().nonnegative().max(300000)}),af=c.object({profile:sf,maximumProbeCount:c.number().int().positive().max(700),maximumExternalAiCalls:c.number().int().nonnegative().max(1e4).optional(),phases:c.array(P8).min(1)}),Hhe=c.object({entities:c.number().int().nonnegative(),notes:c.number().int().nonnegative(),version:c.string().min(1)}),oO=c.object({timestamp:c.iso.datetime(),endpoint:c.string().startsWith("/"),status:c.number().int().nonnegative(),durationMs:c.number().nonnegative(),ok:c.boolean(),error:c.string().optional()}),Vhe=c.object({timestamp:c.iso.datetime(),cpuPercent:c.number().nonnegative(),memoryPercent:c.number().nonnegative(),pids:c.number().int().nonnegative()}),z8=c.object({id:c.string().min(1),operation:C8,count:c.number().int().positive(),success:c.boolean(),commitLatencyMs:c.number().nonnegative().optional(),persistenceLatencyMs:c.number().nonnegative().optional(),error:c.string().optional()}),N8=c.object({success:c.boolean(),probesRemaining:c.number().int().nonnegative(),finalEntities:c.number().int().nonnegative().optional(),finalNotes:c.number().int().nonnegative().optional(),contentTreeRestored:c.boolean().optional(),error:c.string().optional()}),Whe=c.object({status:c.string(),restartCount:c.number().int().nonnegative(),oomKilled:c.boolean()}),D8=c.object({health:c.array(oO),runtime:c.array(Vhe),externalAiCalls:c.number().int().nonnegative().optional(),container:Whe.optional()}),L8=c.object({profile:sf,success:c.boolean(),baseline:Hhe,phases:c.array(z8),cleanup:N8,metrics:D8,failure:c.string().optional()}),Ghe={regression:{profile:"regression",maximumProbeCount:20,phases:[Mt("add20","add",20,20,0),Mt("update20","update",20,20,30000),Mt("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Mt("add50","add",50,50,0),Mt("add150","add",100,150,0),Mt("add350","add",200,350,0),Mt("update350a","update",350,350,45000),Mt("rename100","rename",100,350,45000),Mt("update350b","update",350,350,45000),Mt("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Mt("add50","add",50,50,0),Mt("add150","add",100,150,0),Mt("add350","add",200,350,0),Mt("add700","add",350,700,0),Mt("update700a","update",700,700,45000),Mt("rename200","rename",200,700,45000),Mt("update700b","update",700,700,45000),Mt("delete700","delete",700,0,150000)]}}});import{spawn as Yhe}from"child_process";async function j8(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw so(t,r,n);return n}function so(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var Go=async(e,t,r={})=>new Promise((o,n)=>{let i=Yhe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(l)=>{s+=l}),i.stderr.on("data",(l)=>{a+=l}),i.on("error",n),i.on("close",(l)=>{o({exitCode:l??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var lf=()=>{};class Ml{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new Ml(e,r,o);return await j8(e,"git",["-c","credential.helper=","-c",`credential.helper=${Z8}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",Z8]),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 so("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 Z8='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var U8=v(()=>{lf()});function uf(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class aO{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await Bb(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#f()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#p(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#p(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return Xhe.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#p(e,t,r){return e!==void 0&&(t===void 0||uf(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await Bb(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#f(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var M8,Xhe;var q8=v(()=>{pe();jb();M8=c.array(c.object({entityType:c.string(),count:c.number().int().nonnegative()})),Xhe=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),app:c.object({version:c.string()})})});var Zb={};Lt(Zb,{applyDirectorySyncStressPhase:()=>G8,cleanupDirectorySyncStress:()=>H8,listProbeFiles:()=>xa,parseStressRuntimeSample:()=>Q8,removeProbeFiles:()=>mO,runDeployedDirectorySyncStress:()=>J8,runStressCommand:()=>Go,verifyDirectorySyncStressAccess:()=>K8});import{chmod as ege,mkdir as lO,mkdtemp as uO,readFile as tge,readdir as rge,rename as nge,rm as pf,writeFile as Tn}from"fs/promises";import{tmpdir as dO}from"os";import{join as ct,resolve as pO}from"path";async function J8(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=hO(r),n=pO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await lO(n,{recursive:!0});let{pilot:i,user:s}=await fO(e.rootDir,e.handle);cf({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=sf.parse(e.profile),l=e.plan?af.parse(e.plan):iO(a);if(l.profile!==a)throw Error(`Directory-sync stress plan profile ${l.profile} does not match requested profile ${a}`);if((l.maximumExternalAiCalls??0)===0)W8(s);let u=oge.parse(e.env??process.env),d=new V8({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??Go,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),p;try{p=await sO(l,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:p};return await uge(m),m}async function K8(e){let r=(e.now??(()=>new Date))().toISOString(),o=hO(r),n=pO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await lO(n,{recursive:!0});let{pilot:i,user:s}=await fO(e.rootDir,e.handle);cf({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),W8(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let l=await uO(ct(dO(),"brains-ops-directory-sync-access-check-"));try{let u=await Ml.clone(e.commandRunner??Go,`${i.githubOrg}/${s.contentRepo}`,ct(l,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let p={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await Tn(ct(n,"access-check.json"),`${JSON.stringify(p,null,2)}
442
442
  `),p}finally{await pf(l,{recursive:!0,force:!0})}}async function H8(e){let t=e.now??(()=>new Date),r=pO(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`cleanup-${hO(t().toISOString())}`));await lO(r,{recursive:!0});let{pilot:o,user:n}=await fO(e.rootDir,e.handle);cf({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let i=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!i)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??Go,a=e.logger??console.info,l=await uO(ct(dO(),"brains-ops-directory-sync-cleanup-")),u=ct(l,"content");try{let d=await Ml.clone(s,`${o.githubOrg}/${n.contentRepo}`,u,i),p=await mO(d.dir),m;if(p>0)await d.commitAll("test(directory-sync): clean residual stress probes"),await d.pushMainWithRebase(),m=await d.output(["rev-parse","HEAD"]),a(`Removed ${p} directory-sync stress probes`);let h=(await xa(d.dir)).length,b=h===0?await d.pruneStressBackupBranches():[],y={success:h===0,artifactsDir:r,probesRemoved:p,probesRemaining:h,backupBranchesDeleted:b,...m?{cleanupCommit:m}:{}};return await Tn(ct(r,"cleanup.json"),`${JSON.stringify(y,null,2)}
443
443
  `),y}finally{await pf(l,{recursive:!0,force:!0})}}class V8{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new aO({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#b(),readEntityCounts:()=>this.#y()})}async prepare(e){this.#r=await uO(ct(dO(),"brains-ops-directory-sync-stress-"));let t=ct(this.#r,"content");this.#o=ct(this.#r,"id_ed25519"),this.#i=ct(this.#r,"known_hosts"),this.#a=await this.#m(),await Tn(this.#o,lge(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await ege(this.#o,384);let r=await this.#S("ssh-keyscan",["-T","10","-t","ed25519",this.#a]);if(r.exitCode!==0||!r.stdout.trim())throw Error("Unable to resolve smoke SSH host key");await Tn(this.#i,r.stdout,{mode:384});let o=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=o.stdout.trim().split(/\r?\n/)[0],!this.#s||!/^[A-Za-z0-9_.-]+$/.test(this.#s))throw Error("Unable to resolve a running smoke container");let n=await Ml.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await xa(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let i=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#p();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 Tn(ct(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:i,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:uf(s),version:s.version}},null,2)}
444
444
  `),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:uf(s),version:s.version}}async startMonitoring(){this.#v(),this.#t.start()}async executePhase(e,t){this.#v();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let o=this.#t.healthSamples.length,n=this.#e.now().getTime(),i=await this.#g();if(i?.pending!==0||i.processing!==0)return ql(e,"health did not provide a drained queue before the phase");await G8(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"]),l=await this.#f(a,900000);if(l===void 0)return ql(e,"runtime did not pull the phase commit");let u;if(e.operation==="rename"){let h=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let b=await this.#t.waitForStableEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-s,!b)return ql(e,`health did not stabilize at ${h} notes`,l,u)}else if(e.operation==="add"||e.operation==="delete"){let h=t.notes+e.targetProbeCount,b=this.#e.now().getTime(),y=await this.#t.waitForEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-b,!y)return ql(e,`health did not reach ${h} notes`,l,u)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let d=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(i.completedImports+d,1200000))return ql(e,`health did not observe ${d} completed import job(s) with a drained queue`,l,u);let m=this.#t.healthSamples.slice(o).find((h)=>!h.ok);if(m)return ql(e,`${m.endpoint} unavailable (${m.status===0?m.error??"unknown":m.status})`,l,u);return this.#e.logger(`Completed ${e.id} in ${this.#e.now().getTime()-n}ms`),{id:e.id,operation:e.operation,count:e.count,success:!0,commitLatencyMs:l,...u===void 0?{}:{persistenceLatencyMs:u}}}async cleanup(e){let t=this.#n;if(!t)return{success:!1,probesRemaining:0,error:"stress checkout was not prepared"};try{if(await t.sync(!0),await mO(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let o=(await xa(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=o===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:o,...n?{finalEntities:n.entities,finalNotes:uf(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 xa(t.dir)).length,error:Ve(r)}}}async stopMonitoring(){await this.#t.stop(),await Tn(ct(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
@@ -452,7 +452,7 @@ Update marker: ${t.id}.
452
452
  `}function hO(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function uge(e){await Tn(ct(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
453
453
  `),await Tn(ct(e.artifactsDir,"report.md"),dge(e))}function dge(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,o=t.map((a)=>a.cpuPercent).sort((a,l)=>a-l),n=t.map((a)=>a.memoryPercent),i=r.filter((a)=>!a.ok),s=["# Directory-sync stress report","",`- Run: \`${e.runId}\``,`- Target: \`${e.target.handle}\` (${e.target.domain})`,`- Profile: \`${e.report.profile}\``,`- Version: \`${e.report.baseline.version}\``,`- Result: **${e.report.success?"PASS":"FAIL"}**`,`- Started: ${e.startedAt}`,`- Completed: ${e.completedAt}`,"","## Phases","","| Phase | Operation | Count | Result | Pull latency | Persistence latency |","| --- | --- | ---: | --- | ---: | ---: |",...e.report.phases.map((a)=>`| ${a.id} | ${a.operation} | ${a.count} | ${a.success?"pass":`fail: ${a.error??"unknown"}`} | ${F8(a.commitLatencyMs)} | ${F8(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${df(cO(o,0.5))} / ${df(cO(o,0.95))} / ${df(cO(o,0.99))} / ${df(o.at(-1))}`,`- Memory max: ${df(n.length?Math.max(...n):void 0)}`,`- PIDs max: ${t.length?Math.max(...t.map((a)=>a.pids)):"n/a"}`,`- Container status/restarts/OOM: ${e.report.metrics.container?`${e.report.metrics.container.status} / ${e.report.metrics.container.restartCount} / ${e.report.metrics.container.oomKilled}`:"unknown"}`,`- External AI calls: ${e.report.metrics.externalAiCalls??0}`,`- Health samples: ${r.length}`,`- Health failures: ${i.length}`,"","## Cleanup","",`- Result: ${e.report.cleanup.success?"pass":"fail"}`,`- Remaining probes: ${e.report.cleanup.probesRemaining}`,`- Final entities: ${e.report.cleanup.finalEntities??"unknown"}`,`- Final notes: ${e.report.cleanup.finalNotes??"unknown"}`,`- Content tree restored: ${e.report.cleanup.contentTreeRestored??"unknown"}`,""];if(e.report.failure)s.push("## Failure","",e.report.failure,"");return`${s.join(`
454
454
  `)}
455
- `}function cO(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function df(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function F8(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var oge,ige,sge,age;var ff=v(()=>{pe();jb();Hr();lf();U8();q8();lf();oge=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1),CONTENT_REPO_ADMIN_TOKEN:c.string().min(1)}),ige=c.object({servers:c.array(c.object({id:c.number().int(),status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))}),sge=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),resources:c.object({queue:c.object({totals:c.object({pending:c.number().int().nonnegative(),processing:c.number().int().nonnegative()}),byType:c.array(c.object({type:c.string(),status:c.string(),count:c.number().int().nonnegative()}))})})}),age=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var Y8=v(()=>{Xo()});var pge="/usr/local/sbin/brains-health-watchdog",fge="ai.rizom.brain.watchdog",mge="true",gO,X8,m8e;var eJ=v(async()=>{Y8();gO=`${fge}=${mge}`,X8=`#!/usr/bin/env bash
455
+ `}function cO(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function df(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function F8(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var oge,ige,sge,age;var ff=v(()=>{pe();jb();Hr();lf();U8();q8();lf();oge=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1),CONTENT_REPO_ADMIN_TOKEN:c.string().min(1)}),ige=c.object({servers:c.array(c.object({id:c.number().int(),status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))}),sge=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),resources:c.object({queue:c.object({totals:c.object({pending:c.number().int().nonnegative(),processing:c.number().int().nonnegative()}),byType:c.array(c.object({type:c.string(),status:c.string(),count:c.number().int().nonnegative()}))})})}),age=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var Y8=v(()=>{Xo()});var pge="/usr/local/sbin/brains-health-watchdog",fge="ai.rizom.brain.watchdog",mge="true",gO,X8,g8e;var eJ=v(async()=>{Y8();gO=`${fge}=${mge}`,X8=`#!/usr/bin/env bash
456
456
  set -euo pipefail
457
457
  umask 077
458
458
 
@@ -511,7 +511,7 @@ while read -r container_id; do
511
511
  logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
512
512
  docker restart "$container_id"
513
513
  done < <(docker ps --filter health=unhealthy --filter label=${gO} --format '{{.ID}}')
514
- `,m8e=`[Unit]
514
+ `,g8e=`[Unit]
515
515
  Description=Restart persistently unhealthy Brain containers
516
516
  After=docker.service
517
517
  Requires=docker.service
@@ -751,7 +751,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
751
751
  `),i}async function cJ(e,t){let r=await ut(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function lJ(e){let t=await yge(ao(bge(),"brains-ops-watchdog-smoke-")),r=ao(t,"id_ed25519"),o=ao(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),i=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!i.ok)throw Error(`Hetzner server lookup failed with ${i.status}`);let s=Sge.parse(await i.json());if(s.servers.length!==1)throw Error(`Expected one smoke server, found ${s.servers.length}`);let a=s.servers[0];if(a?.status!=="running")throw Error("Smoke server is not running");await Fl(r,wge(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await gge(r,384);let l=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(l.exitCode!==0||!l.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await Fl(o,l.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:o,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await bO(t,{recursive:!0,force:!0}),n}}async function yO(e,t,r){return e.commandRunner("ssh",[...uJ(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:SO()})}async function vge(e,t,r){return e.commandRunner("scp",[...uJ(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function uJ(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function Ub(e,t,r){await Promise.all([Fl(ao(e,`${t}.stdout.log`),r.stdout),Fl(ao(e,`${t}.stderr.log`),r.stderr)])}function wge(e){return`${e.replace(/\r\n/g,`
752
752
  `).replace(/\\n/g,`
753
753
  `).trimEnd()}
754
- `}var iJ,Sge;var qb=v(async()=>{pe();tJ();Hr();lf();Rs();await eJ();iJ=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),Sge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{chmod as nI,mkdir as fh,readFile as K2,writeFile as J2}from"fs/promises";import{dirname as iG,join as mc}from"path";import{fileURLToPath as sG}from"url";var mf={name:"@rizom/ops",version:"0.2.0-alpha.756",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Xo();fc();Rs();var aG=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],oI=new Set([".kamal/hooks/pre-deploy"]),cG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),lG=sG(new URL("../templates/rover-pilot/",import.meta.url));function ho(e){return(t)=>t.includes(e)}function uG(e){return RO.find((t)=>e===`deploy/scripts/${t}`)}function iI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
754
+ `}var iJ,Sge;var qb=v(async()=>{pe();tJ();Hr();lf();Rs();await eJ();iJ=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),Sge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{chmod as nI,mkdir as fh,readFile as K2,writeFile as J2}from"fs/promises";import{dirname as iG,join as mc}from"path";import{fileURLToPath as sG}from"url";var mf={name:"@rizom/ops",version:"0.2.0-alpha.757",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Xo();fc();Rs();var aG=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],oI=new Set([".kamal/hooks/pre-deploy"]),cG=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),lG=sG(new URL("../templates/rover-pilot/",import.meta.url));function ho(e){return(t)=>t.includes(e)}function uG(e){return RO.find((t)=>e===`deploy/scripts/${t}`)}function iI(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
755
755
  secret:
756
756
  - __DYNAMIC_SECRETS__
757
757