hatchlight 0.0.0-stage → 0.4.1
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/LICENSE +21 -0
- package/README.md +34 -2
- package/bin/hatchlight.js +434 -0
- package/package.json +32 -5
- package/resources/drizzle/0000_init.sql +57 -0
- package/resources/drizzle/0001_job_error_codes.sql +2 -0
- package/resources/drizzle/0002_assistant_messages.sql +10 -0
- package/resources/drizzle/0003_accounts.sql +56 -0
- package/resources/drizzle/0004_spending.sql +14 -0
- package/resources/drizzle/0005_account_hardening.sql +12 -0
- package/resources/drizzle/0006_lora_uploads.sql +8 -0
- package/resources/drizzle/0007_reset_notices.sql +1 -0
- package/resources/drizzle/0008_spending_key_source.sql +1 -0
- package/resources/drizzle/0009_asset_usage.sql +8 -0
- package/resources/drizzle/0010_agent_tokens.sql +8 -0
- package/resources/drizzle/0011_pending_spending.sql +1 -0
- package/resources/drizzle/meta/0000_snapshot.json +374 -0
- package/resources/drizzle/meta/0001_snapshot.json +388 -0
- package/resources/drizzle/meta/0002_snapshot.json +449 -0
- package/resources/drizzle/meta/0003_snapshot.json +814 -0
- package/resources/drizzle/meta/0004_snapshot.json +872 -0
- package/resources/drizzle/meta/0005_snapshot.json +950 -0
- package/resources/drizzle/meta/0006_snapshot.json +994 -0
- package/resources/drizzle/meta/0007_snapshot.json +1001 -0
- package/resources/drizzle/meta/0008_snapshot.json +1009 -0
- package/resources/drizzle/meta/0009_snapshot.json +1033 -0
- package/resources/drizzle/meta/0010_snapshot.json +1064 -0
- package/resources/drizzle/meta/0011_snapshot.json +1072 -0
- package/resources/drizzle/meta/_journal.json +90 -0
- package/resources/web/assets/Assistant-Dcr31LAV.js +44 -0
- package/resources/web/assets/Gallery-CMRGE3qD.js +11 -0
- package/resources/web/assets/Models-D468Wmoj.js +1 -0
- package/resources/web/assets/Settings-DSXHt9Y3.js +2 -0
- package/resources/web/assets/bricolage-grotesque-latin-500-normal-CV-uA8Lw.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-500-normal-DEDBoLFO.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-700-normal-DvJDmrLu.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-700-normal-gtcctNPv.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-800-normal-Br4b-5gk.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-800-normal-J50vIsBe.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-ext-500-normal-B0ZDNVGf.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-ext-500-normal-DIhLz7G7.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-ext-700-normal-BXpPFNFj.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-ext-700-normal-fBkt-7fi.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-ext-800-normal-BimIDUhy.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-latin-ext-800-normal-CkoBqIJM.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-vietnamese-500-normal-CAK5R6Iy.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-vietnamese-500-normal-FzY9NZwK.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-vietnamese-700-normal-BLYPkJbo.woff2 +0 -0
- package/resources/web/assets/bricolage-grotesque-vietnamese-700-normal-CHrFuVHU.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-vietnamese-800-normal-DJ4hCX8l.woff +0 -0
- package/resources/web/assets/bricolage-grotesque-vietnamese-800-normal-RJtJa6zl.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-400-normal-CJUKFyLa.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-400-normal-DvQQgHTq.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-500-normal-BtGHVI3Q.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-500-normal-N1TV9ACq.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-ext-400-normal-B3hZxag_.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-ext-400-normal-ZyMXPjaT.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-ext-500-normal-CmcxpzmF.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-cyrillic-ext-500-normal-yqk7_qG0.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-400-normal-Dm_PoFIZ.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-400-normal-O6-GRVqx.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-500-normal-C_OblDzq.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-500-normal-zoSM89R3.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-ext-400-normal-DxDDqVQb.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-ext-400-normal-uwM7KshN.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-ext-500-normal-BhDX_RLI.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-latin-ext-500-normal-Dn-cqWhb.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-vietnamese-400-normal-BFiUPp6R.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-vietnamese-400-normal-DLynVohM.woff +0 -0
- package/resources/web/assets/ibm-plex-mono-vietnamese-500-normal-CevHOlzG.woff2 +0 -0
- package/resources/web/assets/ibm-plex-mono-vietnamese-500-normal-QhwQXayn.woff +0 -0
- package/resources/web/assets/index-DrgBjkJQ.js +322 -0
- package/resources/web/assets/index-gLwjTNlu.css +1 -0
- package/resources/web/assets/index-ydGCWKys.js +1 -0
- package/resources/web/assets/inter-tight-cyrillic-400-normal-Cu6X1knp.woff +0 -0
- package/resources/web/assets/inter-tight-cyrillic-400-normal-DLglYK2S.woff2 +0 -0
- package/resources/web/assets/inter-tight-cyrillic-500-normal-BS_Q301l.woff +0 -0
- package/resources/web/assets/inter-tight-cyrillic-500-normal-GsQC2I9I.woff2 +0 -0
- package/resources/web/assets/inter-tight-cyrillic-600-normal-CA1nZd4A.woff +0 -0
- package/resources/web/assets/inter-tight-cyrillic-600-normal-zvV8lvuq.woff2 +0 -0
- package/resources/web/assets/inter-tight-cyrillic-ext-400-normal-CPa21WFm.woff +0 -0
- package/resources/web/assets/inter-tight-cyrillic-ext-400-normal-wRoSiYJX.woff2 +0 -0
- package/resources/web/assets/inter-tight-cyrillic-ext-500-normal-DDZdcw0e.woff2 +0 -0
- package/resources/web/assets/inter-tight-cyrillic-ext-500-normal-SbyCo7Dv.woff +0 -0
- package/resources/web/assets/inter-tight-cyrillic-ext-600-normal-BwQoccyI.woff2 +0 -0
- package/resources/web/assets/inter-tight-cyrillic-ext-600-normal-D1EOoMTg.woff +0 -0
- package/resources/web/assets/inter-tight-greek-400-normal-8GU0b4sT.woff2 +0 -0
- package/resources/web/assets/inter-tight-greek-400-normal-BeMKI6ne.woff +0 -0
- package/resources/web/assets/inter-tight-greek-500-normal-BGOdJ4jK.woff +0 -0
- package/resources/web/assets/inter-tight-greek-500-normal-DfwCMcvd.woff2 +0 -0
- package/resources/web/assets/inter-tight-greek-600-normal-BIWCW30H.woff2 +0 -0
- package/resources/web/assets/inter-tight-greek-600-normal-CMARuIv4.woff +0 -0
- package/resources/web/assets/inter-tight-greek-ext-400-normal-B035aUhC.woff2 +0 -0
- package/resources/web/assets/inter-tight-greek-ext-400-normal-tWLvaB1R.woff +0 -0
- package/resources/web/assets/inter-tight-greek-ext-500-normal-BtZsBjxU.woff +0 -0
- package/resources/web/assets/inter-tight-greek-ext-500-normal-DitH-qUF.woff2 +0 -0
- package/resources/web/assets/inter-tight-greek-ext-600-normal-4wRrF3Lp.woff2 +0 -0
- package/resources/web/assets/inter-tight-greek-ext-600-normal-DTLxDvi0.woff +0 -0
- package/resources/web/assets/inter-tight-latin-400-normal-BW_APOAv.woff +0 -0
- package/resources/web/assets/inter-tight-latin-400-normal-CjmW70MP.woff2 +0 -0
- package/resources/web/assets/inter-tight-latin-500-normal-DHfo6WYp.woff2 +0 -0
- package/resources/web/assets/inter-tight-latin-500-normal-DSK3iurg.woff +0 -0
- package/resources/web/assets/inter-tight-latin-600-normal-BhR4EMHT.woff2 +0 -0
- package/resources/web/assets/inter-tight-latin-600-normal-RFJ2ueZL.woff +0 -0
- package/resources/web/assets/inter-tight-latin-ext-400-normal-BdDiaPns.woff +0 -0
- package/resources/web/assets/inter-tight-latin-ext-400-normal-Gi8wMfrP.woff2 +0 -0
- package/resources/web/assets/inter-tight-latin-ext-500-normal-BdRfio7v.woff +0 -0
- package/resources/web/assets/inter-tight-latin-ext-500-normal-CSMKT5kA.woff2 +0 -0
- package/resources/web/assets/inter-tight-latin-ext-600-normal-BiZjrIRq.woff +0 -0
- package/resources/web/assets/inter-tight-latin-ext-600-normal-Yxv5k3jL.woff2 +0 -0
- package/resources/web/assets/inter-tight-vietnamese-400-normal-CWFku8rW.woff2 +0 -0
- package/resources/web/assets/inter-tight-vietnamese-400-normal-s0S0Ysqp.woff +0 -0
- package/resources/web/assets/inter-tight-vietnamese-500-normal-B9o3jXvc.woff2 +0 -0
- package/resources/web/assets/inter-tight-vietnamese-500-normal-D9AKxpnU.woff +0 -0
- package/resources/web/assets/inter-tight-vietnamese-600-normal-B6ESNxpD.woff +0 -0
- package/resources/web/assets/inter-tight-vietnamese-600-normal-BZpsSm6S.woff2 +0 -0
- package/resources/web/assets/splash-CLEpm4fL.js +1 -0
- package/resources/web/favicon.svg +15 -0
- package/resources/web/index.html +17 -0
- package/resources/web/samples/flux-schnell.webp +0 -0
- package/resources/web/samples/sdxl-turbo.webp +0 -0
- package/resources/web/samples/sdxl.webp +0 -0
- package/resources/web/samples/z-image-turbo.webp +0 -0
- package/resources/web/splash.html +26 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
var R6=Object.create;var{getPrototypeOf:C6,defineProperty:Vm,getOwnPropertyNames:O6}=Object;var tS=Object.prototype.hasOwnProperty;function z6(e){return this[e]}var M6,N6,rS=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var s=t?M6??=new WeakMap:N6??=new WeakMap,o=s.get(e);if(o)return o}r=e!=null?R6(C6(e)):{};let i=t||!e||!e.__esModule||!tS.call(e,"default")?Vm(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of O6(e))if(!tS.call(i,a))Vm(i,a,{get:z6.bind(e,a),enumerable:!0})}if(n)s.set(e,i);return i};var H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var L6=(e)=>e;function D6(e,t){this[e]=L6.bind(null,t)}var j6=(e,t)=>{for(var r in t)Vm(e,r,{get:t[r],enumerable:!0,configurable:!0,set:D6.bind(t,r)})};var b=(e,t,r)=>()=>{if(e)try{t=e(e=0)}catch(n){r=[n]}if(r)throw r[0];return t};function $s(e){if(e instanceof le&&e.code)return{message:e.message,code:e.code,params:e.params};return{message:e instanceof Error?e.message:String(e),code:null,params:null}}var le,O,Ee,be;var Ar=b(()=>{le=class le extends Error{code;params;retry;constructor(e,t,r={},n){super(e);this.code=t;this.params=r;this.retry=n}};O=class O extends le{};Ee=class Ee extends le{};be=class be extends le{status;constructor(e,t,r,n={}){super(e,t,n);this.status=r}}});function Ft(e){return`${e}_${crypto.randomUUID().replaceAll("-","")}`}import{createHmac as U6,timingSafeEqual as B6}from"crypto";function q6(e){let t="",r=0,n=0;for(let s of e){r=r<<8|s,n+=8;while(n>=5)t+=Zm[r>>n-5&31],n-=5}if(n>0)t+=Zm[r<<5-n&31];return t}function F6(e){let t=e.replace(/[\s=]/g,"").toUpperCase(),r=[],n=0,s=0;for(let o of t){let i=Zm.indexOf(o);if(i<0)return null;if(n=n<<5|i,s+=5,s>=8)r.push(n>>s-8&255),s-=8}return new Uint8Array(r)}function V6(e,t,{algorithm:r="sha1",digits:n=6,period:s=30}={}){let o=Math.floor(t/s),i=Buffer.alloc(8);i.writeBigUInt64BE(BigInt(o));let a=U6(r,e).update(i).digest(),c=(a[a.length-1]??0)&15,l=((a[c]??0)&127)<<24|(a[c+1]??0)<<16|(a[c+2]??0)<<8|(a[c+3]??0);return String(l%10**n).padStart(n,"0")}function Hm(e,t,r=Date.now()){let n=F6(e),s=t.replace(/\s/g,"");if(!n||!/^\d{6}$/.test(s))return null;let o=Math.floor(r/1000/30),i=null;for(let a of[o-1,o,o+1]){let c=Buffer.from(V6(n,a*30));if(B6(c,Buffer.from(s)))i=a}return i}function nS(){return q6(crypto.getRandomValues(new Uint8Array(20)))}function sS(e,t,r){let n=encodeURIComponent(`${r}:${t}`),s=new URLSearchParams({secret:e,issuer:r,algorithm:"SHA1",digits:"6",period:"30"});return`otpauth://totp/${n}?${s}`}var Zm="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";var Gm=()=>{};function Ga(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,s])=>t.indexOf(+n)===-1).map(([n,s])=>s)}function Wm(e,t="|"){return e.map((r)=>Qm(r)).join(t)}function Ka(e,t){if(typeof t==="bigint")return t.toString();return t}class oS{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Wa(e){return new oS(e)}function iS(e){return e===null||e===void 0}function du(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function aS(e,t){let r=e/t,n=Math.round(r),s=4*Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<s)return 0;return r-n}function Rr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ja(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Kn(e){return Ja(e._zod.def)??e._zod.def.shape}function cS(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return Rr(this,t,n),n},enumerable:!0,configurable:!0})}function lS(e,t,r){if(t in e)Rr(e,t,r);else e[t]=r}function ko(e,t,r,n){let s=Kn(t);for(let o of r){let i=Object.getOwnPropertyDescriptor(s,o);if(!i.enumerable)continue;if(i.get)cS(e,o,()=>{let a=t._zod.def.shape[o];return n?n(a,o):a});else lS(e,o,n?n(i.value,o):i.value)}}function Z6(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);if(!n.enumerable)continue;if(n.get)cS(e,r,()=>t[r]);else lS(e,r,n.value)}}function dr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function uS(e){return JSON.stringify(e)}function dS(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function fi(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function To(e){if(fi(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(fi(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function pu(e){if(To(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function Ts(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pr(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function ee(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Qm(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function mS(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function hS(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let o={};return ko(o,e,mu(e,t)),pr(e,dr(r,{shape:o,checks:[]}))}function mu(e,t){let r=Kn(e),n=[];for(let s of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,s)?.enumerable)throw Error(`Unrecognized key: "${String(s)}"`);if(t[s])n.push(s)}return n}function gS(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let o=new Set(mu(e,t)),i={};return ko(i,e,Reflect.ownKeys(Kn(e)).filter((a)=>!o.has(a))),pr(e,dr(r,{shape:i,checks:[]}))}function yS(e,t){if(!To(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let s=Kn(e);for(let o of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(s,o)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return pr(e,dr(e._zod.def,{shape:wS(e,t)}))}function wS(e,t){let r={};return ko(r,e,Reflect.ownKeys(Kn(e))),Z6(r,t),r}function bS(e,t){if(!To(t))throw Error("Invalid input to safeExtend: expected a plain object");return pr(e,dr(e._zod.def,{shape:wS(e,t)}))}function vS(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};ko(r,e,Reflect.ownKeys(Kn(e))),ko(r,t,Reflect.ownKeys(Kn(t)));let n=dr(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return pr(e,n)}function Ym(e,t,r,n="partial"){let o=t._zod.def.checks;if(o&&o.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(mu(t,r)):void 0,c={};return ko(c,t,Reflect.ownKeys(Kn(t)),e&&((l,u)=>a&&!a.has(u)?l:new e({type:"optional",innerType:l}))),pr(t,dr(t._zod.def,{shape:c,checks:[]}))}function _S(e,t,r){let n=r?new Set(mu(t,r)):void 0,s={};return ko(s,t,Reflect.ownKeys(Kn(t)),(o,i)=>n&&!n.has(i)?o:new e({type:"nonoptional",innerType:o})),pr(t,dr(t._zod.def,{shape:s}))}function vn(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function xS(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function Ps(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ha(e){return typeof e==="string"?e:e?.message}function eh(e){let t=[];for(let r of e??[]){let n=r._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let s=n.maximum??n.length??n.size;if(s>=0)t.push([s,r])}return t}function hu(e,t,r){var n;for(let s=t;s<e.length;s++)(n=e[s]).schema??(n.schema=r)}function _n(e,t,r){var n;let s=e.inst?._zod?.traits;if(s?.has("$ZodType"))if(s.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let o=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Ha(e.inst?._zod.def?.error?.(e))??Ha(o?.(e))??Ha(t?.error?.(e))??Ha(r.customError?.(e))??Ha(r.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=e.input;return a}function gu(e){let t=e.length;if(!H6.test(e))return t;let r=t;for(let n=0;n<t-1;n++)if((e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320)r--,n++;return r}function yu(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function SS(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Po(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}function $S(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else G6(e,r,n.value)}}function sn(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function wu(e,t,r){return sn(e,t,r,!1)}function kS(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return sn(this,r,n(this))},set(s){sn(this,r,s)}})}return t}function G6(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:sn(this,t,r.bind(this))},set(n){sn(this,t,n)}})}function K6(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}function Le(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Km!==e._zod){Km=void 0;return}Km=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,W6);let s=ks;ks=!1;try{let o=r(this);if(ks)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o});return ks=ks||s,o}catch(o){throw delete this[t],ks=ks||s,o}},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s})}})}function th(e,t,r,n){let s=K6(e,t);if(!s)return;Object.defineProperty(s,t,{configurable:!0,get(){let o={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,o),o.value=r(this),Object.defineProperty(this,t,o),o.value},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:o})}})}function TS(e){let t=()=>e;return t[J6]=!0,t}var Jm,pS,fS,fu,Xm,H6,Km,ks=!1,W6,J6="~constantCatch";var rr=b(()=>{Eo();Jm="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};pS=Wa(()=>{if(mr.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});fS=new Set(["string","number","symbol"]);fu=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Xm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};H6=/[\uD800-\uDBFF]/;W6={configurable:!0,get(){ks=!0;return}}});function Q6(e){let t=ES;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return ES=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function R(e,t,r,n){let s={};function o(p){this.def=p,this.constr=d,this.traits=new Set}o.prototype=s;let i=r,a=i&&new WeakSet;function c(p,f){if(!p._zod){rh.value=new o(f);try{Object.defineProperty(p,"_zod",rh)}finally{rh.value=void 0}}else if(p._zod.traits.has(e))return;if(p._zod.traits.add(e),t(p,f),a){let h=Object.getPrototypeOf(p),g=p._zod.constr.prototype,w=h;while(w&&w!==g)w=Object.getPrototypeOf(w);let v=w??h;if(!a.has(v))a.add(v),$S(v,i)}let m=d.prototype;for(let h in m){if(!Object.prototype.hasOwnProperty.call(m,h))continue;if(!(h in p))p[h]=m[h].bind(p)}}let l=n?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(p){let f=n?.Parent?Q6(u):this;c(f,p);let m=f._zod.deferred;if(m){for(let g of m)g();f._zod.deferred=void 0}let h=globalThis.__zod_globalConfig?.postProcessor;if(h)h(f);return f}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:(p)=>{if(n?.Parent&&p instanceof n.Parent)return!0;return p?._zod?.traits?.has(e)}}),Object.defineProperty(d,"name",{value:e}),d}function hr(e){if(e)Object.assign(mr,e);return mr}var PS,rh,ES,xn,Qa,mr;var Eo=b(()=>{rr();rh={value:void 0,enumerable:!1},ES="captureStackTrace"in Error?Error:null;xn=class xn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};Qa=class Qa extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(PS=globalThis).__zod_globalConfig??(PS.__zod_globalConfig={});mr=globalThis.__zod_globalConfig});function X6(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Ka,2)),e.message}function Y6(e){this._zod.message=e}function tD(e,t,r){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0});else e[t]=r();return e[t]}function oh(e,t=(r)=>r.message){let r={},n=[];for(let s of e.issues)if(s.path.length>0)tD(r,s.path[0],()=>[]).push(t(s));else n.push(t(s));return{formErrors:n,fieldErrors:r}}function ih(e,t=(r)=>r.message){let r={_errors:[]},n=(s,o=[])=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>n({issues:a},[...o,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...o,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...o,...i.path]);else{let a=[...o,...i.path];if(a.length===0)r._errors.push(t(i));else{let c=r,l=0;while(l<a.length){let u=a[l],d=l===a.length-1;if(u==="_errors"){if(d)c._errors.push(t(i));l++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let p=c[u];if(d)p._errors.push(t(i));c=p,l++}}}};return n(e),r}function rD(e){let t=[],r=e.map((n)=>typeof n==="object"?n.key:n);for(let n of r)if(typeof n==="number")t.push(`[${n}]`);else if(typeof n==="symbol")t.push(`[${JSON.stringify(String(n))}]`);else if(/[^\w$]/.test(n))t.push(`[${JSON.stringify(n)}]`);else{if(t.length)t.push(".");t.push(n)}return t.join("")}function CS(e){let t=[],r=[...e.issues].sort((n,s)=>(n.path??[]).length-(s.path??[]).length);for(let n of r)if(t.push(`\u2716 ${n.message}`),n.path?.length)t.push(` \u2192 at ${rD(n.path)}`);return t.join(`
|
|
4
|
+
`)}var eD,sh,IS,AS=(e,t)=>{e.name="$ZodError",sh.value=t,Object.defineProperty(e,"issues",sh),sh.value=void 0,Object.defineProperty(e,"message",eD);let r=Object.getPrototypeOf(e);if(!IS.has(r))IS.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},RS,Xa;var ah=b(()=>{Eo();rr();eD={get:X6,set:Y6,enumerable:!0,configurable:!0},sh={value:void 0,enumerable:!1},IS=new WeakSet([Object.prototype,Error.prototype]),RS=R("$ZodError",AS),Xa=R("$ZodError",AS,void 0,{Parent:Error})});function bu(e,t){return{callee:t?.callee??e,Err:t?.Err}}function OS(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((s)=>_n(s,r,hr()))),t=void 0,r=void 0;return n},set error(s){n=s,t=void 0,r=void 0}}}function iD(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},s=e._zod.bag.fallbackRun,o;if(s)n[oD]=!0,o=s({value:t,issues:[]},n);else o=e._zod.run({value:t,issues:[]},n);if(o instanceof Promise)throw new xn;return o.issues.length===0}var Ya=(e)=>{let t=(r,n,s,o)=>{let i=s?{...s,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new xn;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((l)=>_n(l,i,hr())));throw Jm(c,o?.callee??t),c}return a.value};return t},ch,ec=(e)=>{let t=async(r,n,s,o)=>{let i=s?{...s,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(o?.Err??e)(a.issues.map((l)=>_n(l,i,hr())));throw Jm(c,o?.callee??t),c}return a.value};return t},lh,tc=(e)=>(t,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new xn;return o.issues.length?OS(e,o.issues,s):{success:!0,data:o.value}},rc,nc=(e)=>async(t,r,n)=>{let s=n?{...n,async:!0}:{async:!0},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)o=await o;return o.issues.length?OS(e,o.issues,s):{success:!0,data:o.value}},sc,sD,oD,vu=(e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==sD)return!0;if(n.definite===!0&&r===void 0)return!1}return iD(e,t,r)},_u=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},s=e._zod.run({value:t,issues:[]},n);if(s instanceof Promise)s=await s;return s.issues.length===0},zS=(e)=>{let t=Ya(e),r=(n,s,o,i)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return t(n,s,a,bu(r,i))};return r},MS=(e)=>{let t=Ya(e),r=(n,s,o,i)=>t(n,s,o,bu(r,i));return r},NS=(e)=>{let t=ec(e),r=async(n,s,o,i)=>{let a=o?{...o,direction:"backward"}:{direction:"backward"};return await t(n,s,a,bu(r,i))};return r},LS=(e)=>{let t=ec(e),r=async(n,s,o,i)=>await t(n,s,o,bu(r,i));return r},DS=(e)=>(t,r,n)=>{let s=n?{...n,direction:"backward"}:{direction:"backward"};return tc(e)(t,r,s)},jS=(e)=>(t,r,n)=>tc(e)(t,r,n),US=(e)=>async(t,r,n)=>{let s=n?{...n,direction:"backward"}:{direction:"backward"};return nc(e)(t,r,s)},BS=(e)=>async(t,r,n)=>nc(e)(t,r,n);var qS=b(()=>{Eo();ah();rr();ch=Ya(Xa),lh=ec(Xa),rc=tc(Xa);sc=nc(Xa),sD=Symbol.for("zod.compile.invalid"),oD=Symbol.for("zod.compile.fallback")});function WS(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}function YS(){return new RegExp(aD,"u")}function cD(e){return new RegExp(`^${e}$`)}function uh(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function u$(e){return new RegExp(`^${uh(e)}$`)}function d$(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${uh({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${uh({precision:e.precision})}`:r;return new RegExp(`^${c$}T(?:${n})$`)}var FS,VS,ZS,HS,GS,KS,JS,QS,dh=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},XS,aD="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",e$,t$,r$,n$,s$,o$,i$,a$,c$="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",l$,p$,ph,oc,f$,m$,h$,g$;var ic=b(()=>{FS=/^[cC][0-9a-z]{6,}$/,VS=/^[0-9a-z]+$/,ZS=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,HS=/^[0-9a-vA-V]{20}$/,GS=/^[A-Za-z0-9]{27}$/,KS=/^[a-zA-Z0-9_-]{21}$/;JS=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,QS=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,XS=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;e$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,t$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,r$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,n$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,s$=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,o$=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,i$=/^https?$/,a$=/^\+[1-9]\d{6,14}$/;l$=cD(c$);p$=/^[\s\S]{0,}$/,ph=/^-?\d+$/,oc=/^-?\d+(?:\.\d+)?$/,f$=/^(?:true|false)$/i,m$=/^null$/i,h$=/^[^A-Z]*$/,g$=/^[^a-z]*$/});var Nt,fh=(e)=>{let t=e.value;return!iS(t)&&t.length!==void 0},xu,mh,hh,y$,w$,b$,v$,_$,ac,x$,S$,$$,k$,T$,P$,E$;var Su=b(()=>{Eo();ic();rr();Nt=R("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),xu={number:"number",bigint:"bigint",object:"date"},mh=R("$ZodCheckLessThan",(e,t)=>{Nt.init(e,t);let r=xu[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:xu[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),hh=R("$ZodCheckGreaterThan",(e,t)=>{Nt.init(e,t);let r=xu[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:xu[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),y$=R("$ZodCheckMultipleOf",(e,t)=>{Nt.init(e,t),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):aS(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),w$=R("$ZodCheckNumberFormat",(e,t)=>{Nt.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[s,o]=fu[t.format];e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<s)i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort});if(a>o)i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),b$=R("$ZodCheckMaxLength",(e,t)=>{var r;Nt.init(e,t),(r=e._zod.def).when??(r.when=fh),e._zod.check=(n)=>{let s=n.value,o=s.length;if((typeof s==="string"&&o>t.maximum?gu(s):o)<=t.maximum)return;let a=yu(s);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),v$=R("$ZodCheckMinLength",(e,t)=>{var r;Nt.init(e,t),(r=e._zod.def).when??(r.when=fh),e._zod.check=(n)=>{let s=n.value,o=s.length;if((typeof s==="string"&&o>=t.minimum&&o<t.minimum*2?gu(s):o)>=t.minimum)return;let a=yu(s);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),_$=R("$ZodCheckLengthEquals",(e,t)=>{var r;Nt.init(e,t),(r=e._zod.def).when??(r.when=fh),e._zod.check=(n)=>{let s=n.value,o=s.length,i=typeof s==="string"&&o>=t.length&&o<=t.length*2?gu(s):o;if(i===t.length)return;let a=yu(s),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ac=R("$ZodCheckStringFormat",(e,t)=>{var r,n;if(Nt.init(e,t),t.pattern)(r=e._zod).check??(r.check=(s)=>{if(t.pattern.lastIndex=0,t.pattern.test(s.value))return;s.issues.push({origin:"string",code:"invalid_format",format:t.format,input:s.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),x$=R("$ZodCheckRegex",(e,t)=>{ac.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),S$=R("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=h$),ac.init(e,t)}),$$=R("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=g$),ac.init(e,t)}),k$=R("$ZodCheckIncludes",(e,t)=>{Nt.init(e,t);let r=Ts(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=(s)=>{if(s.value.includes(t.includes,t.position))return;s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:s.value,inst:e,continue:!t.abort})}}),T$=R("$ZodCheckStartsWith",(e,t)=>{Nt.init(e,t);let r=new RegExp(`^${Ts(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),P$=R("$ZodCheckEndsWith",(e,t)=>{Nt.init(e,t);let r=new RegExp(`.*${Ts(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),E$=R("$ZodCheckOverwrite",(e,t)=>{Nt.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}})});class gh{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
|
|
5
|
+
`).filter((o)=>o),n=Math.min(...r.map((o)=>o.length-o.trimStart().length)),s=r.map((o)=>o.slice(n)).map((o)=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
6
|
+
${t.join(`
|
|
7
|
+
`)}
|
|
8
|
+
};`)(...Object.values(this.closed))}}var A$;var yh=b(()=>{A$={major:4,minor:6,patch:7}});async function lD(e,t){let r={async:!0};return B$(await e._zod.run({value:t,issues:[]},r),r)}function bh(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return B$(n,r)}catch(n){}return lD(e,t)},vendor:"zod",version:1}}function F$(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function uD(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return F$(e)||ku;return dD(e,t)}function dD(e,t){if(!t.normalize&&t.protocol?.source===i$.source&&!/^https?:\/\//i.test(e))return q$;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??ku}return new URL(e)}catch{return ku}}function R$(e){return e.replace(pD,"")}function fD(e,t){return t.lastIndex=0,t.test(e.hostname)}function mD(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}function K$(e){if(!hD.test(e))return!1;return F$(`http://[${e}]`)}function gD(e){let t=e.split("/");if(t.length!==2)return!1;let[r,n]=t;if(!n)return!1;let s=Number(n);if(`${s}`!==n)return!1;if(s<0||s>128)return!1;return K$(r)}function W$(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function yD(e){if(!Pu.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return W$(r)}function wD(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));if("typ"in s&&s?.typ!=="JWT")return!1;if(!s.alg)return!1;if(t&&(!("alg"in s)||s.alg!==t))return!1;return!0}catch{return!1}}function bD(e,t){let r=eh(e._zod.def.checks);if(!r.length)return;let n=Math.min(...r.map((o)=>o[0])),s=e._zod.parse;e._zod.parse=(o,i)=>{let a=t(o.value);if(a>n&&!i?.skipChecks&&i?.direction!=="backward"){for(let[c,l]of eh(e._zod.def.checks))if(a>c&&l._zod.def.when(o)){let u=o.issues.length;return l._zod.check(o),o.issues[u].continue=!1,hu(o.issues,u,e),o}}return s(o,i)}}function C$(e,t,r){if(e.issues.length)t.issues.push(...Ps(r,e.issues));t.value[r]=e.value}function Tu(e,t,r,n,s,o){let i=r in n,a=o==="optional";if(!i&&a&&s==="optional")return;if(e.issues.length){if(s!==void 0&&a&&!i)return;t.issues.push(...Ps(r,e.issues))}if(!i&&s===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i||s==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}function J$(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:_D,s=n.length?[...t,...n]:t;for(let i of s)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let o=mS(e.shape);return{...e,allKeys:s,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(o)}}function Q$(e,t,r,n,s,o,i){let a=[],c=s.keySet,l=s.catchall._zod,u=l.def.type,{optin:d,optout:p}=l,f=0;for(let m in t){if(i&&r.issues.length!==f){if(vn(r,f))break;f=r.issues.length}if(c.has(m))continue;if(m==="__proto__"){if(u==="never")a.push(m);continue}if(u==="never"){a.push(m);continue}let h=l.run({value:t[m],issues:[]},n);if(h instanceof Promise)e.push(h.then((g)=>Tu(g,r,m,t,d,p)));else Tu(h,r,m,t,d,p)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}function O$(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;let s=e.filter((o)=>!vn(o));if(s.length===1)return t.value=s[0].value,s[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((o)=>o.issues.map((i)=>_n(i,n,hr())))}),t}function xD(e){let t=new Map;for(let r of e.options){let n=r._zod.propValues?.[e.discriminator];if(!n||n.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(let s of n)if(t.has(s)){if(s!==void 0)throw Error(`Duplicate discriminator value "${String(s)}"`);t.set(s,null)}else t.set(s,r)}return t}function wh(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(To(e)&&To(t)){let r=Object.keys(t),n=Object.keys(e).filter((o)=>r.indexOf(o)!==-1),s={...e,...t};if(Object.prototype.hasOwnProperty.call(s,"__proto__"))delete s.__proto__;for(let o of n){if(o==="__proto__")continue;let i=wh(e[o],t[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};s[o]=i.data}return{valid:!0,data:s}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let s=e[n],o=t[n],i=wh(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function z$(e,t,r){let n=new Map,s,o=new Map,i=(l,u)=>{let d;if(l.code==="unrecognized_keys"&&!l.path?.length)s??(s=l),d=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&l.path?.length===1){let p=String(l.path[0]);if(!o.has(p))o.set(p,l);d=[p]}else return!1;for(let p of d){if(!n.has(p))n.set(p,{});n.get(p)[u]=!0}return!0};for(let l of t.issues)if(!i(l,"l"))e.issues.push(l);for(let l of r.issues)if(!i(l,"r"))e.issues.push(l);let a=[...n].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(a.length){let l=s?a.filter((u)=>s.keys.includes(u)):[];if(l.length)e.issues.push({...s,keys:l});for(let u of a)if(!l.includes(u)&&o.has(u))e.issues.push(o.get(u))}let c=wh(t.value,r.value);if(!c.valid){if(vn(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}function M$(e,t){return e.value=t.issues.length?void 0:t.value,e}function N$(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function L$(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function D$(e,t,r,n){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map((s)=>_n(s,n,hr()))},input:e.value}),e}function $u(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}function j$(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function U$(e,t,r,n){if(!e){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)s.params=n._zod.def.params;t.issues.push(Po(s))}}var He,B$=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>_n(r,t,hr()))}:{value:e.value},cc,We,vh,_h,xh,q$=1,ku=2,pD,Sh,$h,kh,Th,Ph,Eh,Ih,Ah,V$,Z$,H$,G$,Rh,hD,Ch,Oh,zh,Mh,Nh,Pu,Lh,Dh,jh,Eu,Uh,Bh,qh,Fh,Vh,vD=(e)=>Array.isArray(e)?e.length:-1,Zh,_D,Hh,X$,Iu,Gh,Kh,Wh,Jh,Qh,Xh,Au,Yh,eg,tg,rg,ng,sg,Ru,Y$,og,ig;var ag=b(()=>{Su();Eo();ic();rr();yh();rr();He=R("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=A$;let n=e._zod.def.checks,s=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let o of s)for(let i of o._zod.onattach)i(e);if(s.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,c,l)=>{if(a.memo)return a;let u=vn(a),d;for(let p of c){if(p._zod.def.when){if(xS(a))continue;if(!p._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,m=p._zod.check(a);if(m instanceof Promise&&l?.async===!1)throw new xn;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{if(await m,a.issues.length===f)return;if(hu(a.issues,f,e),!u)u=vn(a,f)});else{if(a.issues.length===f)continue;if(hu(a.issues,f,e),!u)u=vn(a,f)}}if(d)return d.then(()=>a);return a},i=(a,c,l)=>{if(vn(a))return a.aborted=!0,a;let u=o(c,s,l);if(u instanceof Promise){if(l.async===!1)throw new xn;return u.then((d)=>e._zod.parse(d,l))}return e._zod.parse(u,l)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((d)=>i(d,a,c));return i(u,a,c)}let l=e._zod.parse(a,c);if(l instanceof Promise){if(c.async===!1)throw new xn;return l.then((u)=>o(u,s,c))}return o(l,s,c)}}},{get "~standard"(){return wu(this,"~standard",bh(this))},set "~standard"(e){sn(this,"~standard",e)}});cc=R("$ZodString",(e,t)=>{He.init(e,t),e._zod.pattern=t.pattern??p$,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(s){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),We=R("$ZodStringFormat",(e,t)=>{ac.init(e,t),cc.init(e,t)}),vh=R("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=QS),We.init(e,t)}),_h=R("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=dh(n))}else t.pattern??(t.pattern=dh());We.init(e,t)}),xh=R("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=XS),We.init(e,t)});pD=/[\t\n\r]/g;Sh=R("$ZodURL",(e,t)=>{We.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),s=uD(n,t);if(s===q$){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(s===ku){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(s===!0){r.value=R$(n);return}if(t.hostname&&!fD(s,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!mD(s,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?s.href:R$(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),$h=R("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=YS()),We.init(e,t)}),kh=R("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?KS:WS(t.length)),We.init(e,t)}),Th=R("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=FS),We.init(e,t)}),Ph=R("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=VS),We.init(e,t)}),Eh=R("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ZS),We.init(e,t)}),Ih=R("$ZodXID",(e,t)=>{t.pattern??(t.pattern=HS),We.init(e,t)}),Ah=R("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=GS),We.init(e,t)}),V$=R("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=d$(t)),We.init(e,t)}),Z$=R("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=l$),We.init(e,t)}),H$=R("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=u$(t)),We.init(e,t)}),G$=R("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=JS),We.init(e,t)}),Rh=R("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=e$),We.init(e,t)}),hD=/^[0-9a-fA-F:.]+$/;Ch=R("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=t$),We.init(e,t),e._zod.check=(r)=>{if(!K$(r.value))r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}),Oh=R("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=r$),We.init(e,t)});zh=R("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=n$),We.init(e,t),e._zod.check=(r)=>{if(!gD(r.value))r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});Mh=/^[0-9a-zA-Z+/]*={0,2}$/,Nh=R("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Mh),We.init(e,t),e._zod.check=(r)=>{if(W$(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Pu=/^[A-Za-z0-9_-]*$/;Lh=R("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Pu),We.init(e,t),e._zod.check=(r)=>{if(yD(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Dh=R("$ZodE164",(e,t)=>{t.pattern??(t.pattern=a$),We.init(e,t)});jh=R("$ZodJWT",(e,t)=>{We.init(e,t),e._zod.check=(r)=>{if(wD(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Eu=R("$ZodNumber",(e,t)=>{He.init(e,t),e._zod.pattern=oc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let s=r.value;if(typeof s==="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let o=typeof s==="number"?Number.isNaN(s)?"NaN":!Number.isFinite(s)?String(s):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...o?{received:o}:{}}),r}}),Uh=R("$ZodNumberFormat",(e,t)=>{w$.init(e,t),Eu.init(e,t)}),Bh=R("$ZodBoolean",(e,t)=>{He.init(e,t),e._zod.pattern=f$,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(o){}let s=r.value;if(typeof s==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),r}}),qh=R("$ZodNull",(e,t)=>{He.init(e,t),e._zod.pattern=m$,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let s=r.value;if(s===null)return r;return r.issues.push({expected:"null",code:"invalid_type",input:s,inst:e}),r}}),Fh=R("$ZodUnknown",(e,t)=>{He.init(e,t),e._zod.parse=(r)=>r}),Vh=R("$ZodNever",(e,t)=>{He.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});Zh=R("$ZodArray",(e,t)=>{He.init(e,t);let r=mr.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=r?r.alloc(e,n,Array(o.length),s):Array(o.length);let i=[],a=s?.abortEarly;for(let c=0;c<o.length;c++){let l=o[c],u=t.element._zod.run({value:l,issues:[]},s);if(u instanceof Promise)i.push(u.then((d)=>C$(d,n,c)));else if(C$(u,n,c),a&&u.issues.length!==0&&vn(u))break}if(i.length)return Promise.all(i).then(()=>n);return n},bD(e,vD)});_D=[];Hh=R("$ZodObject",(e,t)=>{He.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let l=()=>{let u={...n};return Object.defineProperty(t,"shape",{value:u}),l.raw=u,u};l.raw=n,Object.defineProperty(t,"shape",{get:l})}let s=Wa(()=>J$(t));Le(e,"propValues",(l)=>{let u=l.def.shape,d={};for(let p in u){let f=u[p]._zod;if(f.values){if(!Object.prototype.hasOwnProperty.call(d,p))Rr(d,p,new Set);for(let m of f.values)d[p].add(m);if(f.optin!==void 0)d[p].add(void 0)}}return d});let o=fi,i=t.catchall,a,c=mr.memoizer;c?.attach(e),e._zod.parse=(l,u)=>{a??(a=s.value);let d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;l.value=c?c.alloc(e,l,{},u):{};let p=[],f=a.shape,m=u?.abortEarly,h=l.issues.length;for(let g of a.allKeys){if(m&&l.issues.length!==h){if(vn(l,h))break;h=l.issues.length}if(g==="__proto__")continue;let w=f[g],v=w._zod.optin,_=w._zod.optout,C=w._zod.run({value:d[g],issues:[]},u);if(C instanceof Promise)p.push(C.then((k)=>Tu(k,l,g,d,v,_)));else Tu(C,l,g,d,v,_)}if(!i)return p.length?Promise.all(p).then(()=>l):l;return Q$(p,d,l,u,s.value,e,m===!0)}}),X$=R("$ZodObjectJIT",(e,t)=>{Hh.init(e,t);let r=e._zod.parse,n=Wa(()=>J$(t)),s=mr.memoizer,o=(f)=>{let m=n.value,h=m.symbolKeys,g=new gh(["payload","ctx"],{shape:f,inst:e,memo:s,syms:h}),w=(k)=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,v=(k,P)=>`
|
|
9
|
+
let ${k}_ab = false;
|
|
10
|
+
for (let i = 0; i < ${k}.issues.length; i++) {
|
|
11
|
+
const iss = ${k}.issues[i];
|
|
12
|
+
iss.path = iss.path ? [${P}, ...iss.path] : [${P}];
|
|
13
|
+
payload.issues.push(iss);
|
|
14
|
+
if (iss.continue !== true) ${k}_ab = true;
|
|
15
|
+
}
|
|
16
|
+
if (${k}_ab && ctx && ctx.abortEarly) {
|
|
17
|
+
payload.value = newResult;
|
|
18
|
+
return payload;
|
|
19
|
+
}`;g.write("const input = payload.value;");let _=Object.create(null),C=0;for(let k of m.allKeys)_[k]=`key_${C++}`;g.write(s?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let k of m.allKeys){if(k==="__proto__")continue;let P=_[k],y=typeof k==="symbol"?`syms[${h.indexOf(k)}]`:uS(k),x=`${y} in input`,T=f[k],I=T?._zod?.optin,j=I!==void 0,se=T?._zod?.optout==="optional";if(g.write(`const ${P} = ${w(y)};`),j&&se){let we=I==="optional"?`${P}_present`:`${P}.value !== undefined || ${P}_present`;g.write(`
|
|
20
|
+
const ${P}_present = ${x};
|
|
21
|
+
if (!${P}.issues.length || ${P}_present) {
|
|
22
|
+
if (${P}.issues.length) {${v(P,y)}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (${we}) {
|
|
26
|
+
newResult[${y}] = ${P}.value;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
`)}else if(!j)g.write(`
|
|
31
|
+
const ${P}_present = ${x};
|
|
32
|
+
if (${P}.issues.length) {${v(P,y)}
|
|
33
|
+
}
|
|
34
|
+
if (!${P}_present && !${P}.issues.length) {
|
|
35
|
+
payload.issues.push({
|
|
36
|
+
code: "invalid_type",
|
|
37
|
+
expected: "nonoptional",
|
|
38
|
+
input: undefined,
|
|
39
|
+
path: [${y}]
|
|
40
|
+
});
|
|
41
|
+
if (ctx && ctx.abortEarly) {
|
|
42
|
+
payload.value = newResult;
|
|
43
|
+
return payload;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (${P}_present) {
|
|
48
|
+
newResult[${y}] = ${P}.value;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
`);else if(g.write(`
|
|
52
|
+
if (${P}.issues.length) {${v(P,y)}
|
|
53
|
+
}
|
|
54
|
+
`),I==="defaulted")g.write(`newResult[${y}] = ${P}.value;`);else g.write(`
|
|
55
|
+
if (${P}.value !== undefined || ${x}) {
|
|
56
|
+
newResult[${y}] = ${P}.value;
|
|
57
|
+
}
|
|
58
|
+
`)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},i,a=fi,c=!mr.jitless,u=c&&pS.value,d=t.catchall,p;e._zod.parse=(f,m)=>{p??(p=n.value);let h=f.value;if(!a(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;if(c&&u&&m?.async===!1&&m.jitless!==!0){if(!i)i=o(t.shape);if(f=i(f,m),!d)return f;return Q$([],h,f,m,p,e,m?.abortEarly===!0)}return r(f,m)}});Iu=R("$ZodUnion",(e,t)=>{He.init(e,t),Le(e,"optin",(n)=>n.def.options.some((s)=>s._zod.optin==="defaulted")?"defaulted":n.def.options.some((s)=>s._zod.optin!==void 0)?"optional":void 0),Le(e,"optout",(n)=>n.def.options.some((s)=>s._zod.optout==="optional")?"optional":void 0),Le(e,"values",(n)=>{if(n.def.options.every((s)=>s._zod.values))return new Set(n.def.options.flatMap((s)=>Array.from(s._zod.values)));return}),Le(e,"pattern",(n)=>{if(n.def.options.every((s)=>s._zod.pattern)){let s=n.def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${s.map((o)=>du(o.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,s)=>{if(r)return r(n,s);let o=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},s);if(c instanceof Promise)i.push(c),o=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!o)return O$(i,n,e,s);return Promise.all(i).then((a)=>O$(a,n,e,s))}});Gh=R("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Iu.init(e,t);let r=e._zod.parse;Le(e,"propValues",(s)=>{let o={},i=0;for(let a of s.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw Error(`Invalid discriminated union option at index "${s.def.options.indexOf(a)}"`);if(c[s.def.discriminator]?.has(void 0))i++;for(let[l,u]of Object.entries(c)){if(!Object.prototype.hasOwnProperty.call(o,l))Rr(o,l,new Set);for(let d of u)o[l].add(d)}}if(!s.def.unionFallback&&i>1)o[s.def.discriminator]?.delete(void 0);return o}),t.options.forEach((s,o)=>{let i=Ja(s._zod.def);if(i&&!Object.prototype.hasOwnProperty.call(i,t.discriminator))throw Error(`Invalid discriminated union option at index "${o}"`)});let n=Wa(()=>xD(t));e._zod.parse=(s,o)=>{let i=s.value;if(!fi(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),s;let a=i?.[t.discriminator],c=n.value.get(a);if(c&&(a!==void 0||o.direction!=="backward"))return c._zod.run(s,o);if(t.unionFallback||o.direction==="backward")return r(s,o);return s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter((l)=>n.value.get(l)!==null),input:i,path:[t.discriminator],inst:e}),s}}),Kh=R("$ZodIntersection",(e,t)=>{He.init(e,t),e._zod.parse=(r,n)=>{let s=r.value,o=t.left._zod.run({value:s,issues:[]},n),i=t.right._zod.run({value:s,issues:[]},n);if(o instanceof Promise||i instanceof Promise)return Promise.all([o,i]).then(([c,l])=>z$(r,c,l));return z$(r,o,i)}});Wh=R("$ZodRecord",(e,t)=>{He.init(e,t);let r=mr.memoizer;r?.attach(e),e._zod.parse=(n,s)=>{let o=n.value;if(!To(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},s):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let d=t.keyType._zod.run({value:u,issues:[]},s);if(d instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map((m)=>_n(m,s,hr())),input:u,path:[u],inst:e});continue}let p=d.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:o[u],issues:[]},s);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...Ps(u,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...Ps(u,f.issues));n.value[p]=f.value}}let l;for(let u in o)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=o[u]}else l=l??[],l.push(u);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:l,continue:!0})}else{n.value=r?r.alloc(e,n,{},s):{};let c;for(let l of Reflect.ownKeys(o)){if(l==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(o,l))continue;let u=t.keyType._zod.run({value:l,issues:[]},s);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&oc.test(l)&&u.issues.length){let m=t.keyType._zod.run({value:Number(l),issues:[]},s);if(m instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(m.issues.length===0)u=m}if(u.issues.length){if(t.mode==="loose")n.value[l]=o[l];else if(a)c=c??[],c.push(l);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((m)=>_n(m,s,hr())),input:l,path:[l],inst:e});continue}let p=u.value;if(p==="__proto__")continue;let f=t.valueType._zod.run({value:o[l],issues:[]},s);if(f instanceof Promise)i.push(f.then((m)=>{if(m.issues.length)n.issues.push(...Ps(l,m.issues));n.value[p]=m.value}));else{if(f.issues.length)n.issues.push(...Ps(l,f.issues));n.value[p]=f.value}}if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>n);return n}}),Jh=R("$ZodEnum",(e,t)=>{He.init(e,t);let r=Ga(t.entries),n=new Set(r);e._zod.values=n,Le(e,"pattern",(s)=>{let o=Ga(s.def.entries).filter((i)=>fS.has(typeof i));return new RegExp(o.length?`^(${o.map((i)=>Ts(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(s,o)=>{let i=s.value;if(n.has(i))return s;return s.issues.push({code:"invalid_value",values:r,input:i,inst:e}),s}}),Qh=R("$ZodLiteral",(e,t)=>{He.init(e,t);let r=new Set(t.values);e._zod.values=r,Le(e,"pattern",(n)=>{let s=n.def.values;return new RegExp(s.length?`^(${s.map((o)=>typeof o==="string"?Ts(o):o?Ts(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,s)=>{let o=n.value;if(r.has(o))return n;return n.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),n}}),Xh=R("$ZodTransform",(e,t)=>{He.init(e,t),e._zod.optin="optional",mr.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Qa(e.constructor.name);let s=t.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then((i)=>(r.value=i,r));if(s instanceof Promise)throw new xn;return r.value=s,r}});Au=R("$ZodOptional",(e,t)=>{He.init(e,t),Le(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Le(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),Le(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${du(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let s=t.innerType._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)return s.then((o)=>M$(r,o));return M$(r,s)}return t.innerType._zod.run(r,n)}}),Yh=R("$ZodExactOptional",(e,t)=>{Au.init(e,t),Le(e,"values",(r)=>r.def.innerType._zod.values),Le(e,"pattern",(r)=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),eg=R("$ZodNullable",(e,t)=>{He.init(e,t),Le(e,"optin",(r)=>r.def.innerType._zod.optin),Le(e,"optout",(r)=>r.def.innerType._zod.optout),Le(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${du(n.source)}|null)$`):void 0}),Le(e,"values",(r)=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),tg=R("$ZodDefault",(e,t)=>{He.init(e,t),e._zod.optin="defaulted",Le(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let s=t.innerType._zod.run(r,n);if(s instanceof Promise)return s.then((o)=>N$(o,t));return N$(s,t)}});rg=R("$ZodPrefault",(e,t)=>{He.init(e,t),e._zod.optin="defaulted",Le(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),ng=R("$ZodNonOptional",(e,t)=>{He.init(e,t),Le(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter((s)=>s!==void 0)):void 0}),e._zod.parse=(r,n)=>{let s=t.innerType._zod.run(r,n);if(s instanceof Promise)return s.then((o)=>L$(o,e));return L$(s,e)}});sg=R("$ZodCatch",(e,t)=>{He.init(e,t),Le(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Le(e,"optout",(r)=>r.def.innerType._zod.optout),Le(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let s=t.innerType._zod.run({value:r.value,issues:[]},n);if(s instanceof Promise)return s.then((o)=>D$(r,o,t,n));return D$(r,s,t,n)}}),Ru=R("$ZodPipe",(e,t)=>{He.init(e,t),Le(e,"values",(r)=>r.def.in._zod.values),Le(e,"optin",(r)=>r.def.in._zod.optin),Le(e,"optout",(r)=>r.def.out._zod.optout),Le(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let o=t.out._zod.run(r,n);if(o instanceof Promise)return o.then((i)=>$u(i,t.in,n));return $u(o,t.in,n)}let s=t.in._zod.run(r,n);if(s instanceof Promise)return s.then((o)=>$u(o,t.out,n));return $u(s,t.out,n)}});Y$=R("$ZodPreprocess",(e,t)=>{Ru.init(e,t)}),og=R("$ZodReadonly",(e,t)=>{He.init(e,t),Le(e,"propValues",(r)=>r.def.innerType._zod.propValues),Le(e,"values",(r)=>r.def.innerType._zod.values),Le(e,"optin",(r)=>r.def.innerType?._zod?.optin),Le(e,"optout",(r)=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let s=t.innerType._zod.run(r,n);if(s instanceof Promise)return s.then(j$);return j$(s)}});ig=R("$ZodCustom",(e,t)=>{Nt.init(e,t),He.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,s=t.fn(n);if(s instanceof Promise)return s.then((o)=>U$(o,r,n,e));U$(s,r,n,e);return}})});function rk(e){return e!==null&&typeof e==="object"}function cg(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}function Mu(e,t,r){let n=nk.get(e);if(n!==void 0)return n?uc:lc;if(t.has(e))return uc;t.add(e);let s=lc,o=(u)=>{if(s!==uc&&u?._zod){let d=Mu(u,t,r);if(d>s)s=d}},i=(u,d)=>{let p=lc;for(let f of Reflect.ownKeys(u)){let m=Object.getOwnPropertyDescriptor(u,f);if(d&&!m.enumerable)continue;let h=m.get?zu:m.value?._zod?Mu(m.value,t,r):lc;if(h>p)p=h}return p},a=(u)=>{if(u>s)s=u},c=e._zod.def,l=c.type;switch(l){case"object":{let u=Ja(c);a(u?i(u,!0):zu),o(c.catchall);break}case"array":o(c.element);break;case"tuple":for(let u of c.items)o(u);o(c.rest);break;case"record":case"map":o(c.keyType),o(c.valueType);break;case"set":o(c.valueType);break;case"union":for(let u of c.options)o(u);break;case"intersection":o(c.left),o(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":o(c.innerType);break;case"pipe":o(c.in),o(c.out);break;case"function":o(c.input),o(c.output);break;case"lazy":{let u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?Mu(u,t,!1):zu);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let d=Object.getOwnPropertyDescriptor(c,u);if(!d||d.get)continue;let p=d.value;if(!p||typeof p!=="object")continue;if(p._zod)o(p);else if(Array.isArray(p))for(let f of p)o(f)}}return t.delete(e),SD(e,s)}function SD(e,t){if(t!==zu)nk.set(e,t===uc);return t}function $D(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}function ug(){return kD}function TD(e,t){let r=e[lg]?.backEdges;return r!==void 0&&rk(t)&&r.has(t)}var tk,lg="~memo",ek,nk,lc=0,zu=1,uc=2,Cu,Ou,kD;var sk=b(()=>{rr();tk=class tk extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}};ek=[];nk=new WeakMap;Ou=[],kD={alloc(e,t,r){let n=Cu;if(!n)return r;Cu=void 0;let s={value:r,issues:null};return n.set(t.value,s),Ou.push(s),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(s,o)=>{if(o.direction!=="backward"&&TD(o,s.value))throw new tk;return r(s,o)};if(e._zod.parse=n,e._zod.run===r)e._zod.run=n})},attach(e){var t;let r,n=!1,s,o;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,l)=>{if(r===void 0){let w=Mu(e,new Set,!1);if(w===lc){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,l)}if(w===uc||n)r=!0;else n=!0}let u=c.value;if(!rk(u))return i(c,l);let d=l[lg];if(!d)d={buckets:new WeakMap,backEdges:void 0},l[lg]=d;let p;if(s===l)p=o;else p=$D(d,e),s=l,o=p;let f=p.get(u);if(f){if(c.value=f.value,f.issues){if(f.issues.length)c.issues.push(...cg(f.issues))}else c.memo=!0,d.backEdges??(d.backEdges=new WeakSet),d.backEdges.add(f.value);return c}Cu=p;let m=Ou.length,h=i(c,l);Cu=void 0;let g=Ou.length>m?Ou.pop():void 0;if(h instanceof Promise)return h.then((w)=>{if(g)g.issues=w.issues.length?cg(w.issues):ek;return w});if(g)g.issues=h.issues.length?cg(h.issues):ek;return h};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}}});function dg(){return{localeError:PD()}}var PD=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function s(o,i){if(o==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return n[o]??o}return(o)=>{switch(o.code){case"invalid_type":{let i=s(o.expected),a=SS(o.input),c=s(a,o.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(o.values.length===1)return`Invalid input: expected ${Qm(o.values[0])}`;return`Invalid option: expected one of ${Wm(o.values,"|")}`;case"too_big":{let i=o.exact?"exactly ":o.inclusive?"<=":"<",a=t(o.origin);if(a)return`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.exact?"exactly ":o.inclusive?">=":">",a=t(o.origin);if(a)return`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${a.unit}`;return`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Wm(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":if(o.options&&Array.isArray(o.options)&&o.options.length>0)return`Invalid discriminator value. Expected ${o.options.map((a)=>`'${a}'`).join(" | ")}`;if(o.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};var ok=b(()=>{rr()});var Nu=()=>{};class ak{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function ck(){return new ak}var ik,Es;var fg=b(()=>{(ik=globalThis).__zod_globalRegistry??(ik.__zod_globalRegistry=ck());Es=globalThis.__zod_globalRegistry});var lk=()=>{};function uk(e){if(e.checks)e.checks=[...e.checks];return e}function mg(e,t){return new e(uk({type:"string",...ee(t)}))}function hg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ee(t)})}function gg(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ee(t)})}function yg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(t)})}function wg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(t)})}function bg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(t)})}function vg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(t)})}function _g(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ee(t)})}function xg(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(t)})}function Sg(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(t)})}function $g(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(t)})}function kg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(t)})}function Tg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(t)})}function Pg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ee(t)})}function Eg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(t)})}function Ig(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(t)})}function Ag(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(t)})}function Rg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(t)})}function Cg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(t)})}function Og(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ee(t)})}function zg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(t)})}function Mg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ee(t)})}function Ng(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(t)})}function Lu(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(t)})}function Lg(e,t){return new e({type:"string",format:"date",check:"string_format",...ee(t)})}function Dg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ee(t)})}function jg(e,t){return new e({type:"string",format:"duration",check:"string_format",...ee(t)})}function Ug(e,t){return new e(uk({type:"number",checks:[],...ee(t)}))}function Bg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(t)})}function qg(e,t){return new e({type:"boolean",...ee(t)})}function Fg(e,t){return new e({type:"null",...ee(t)})}function Vg(e){return new e({type:"unknown"})}function Zg(e,t){return new e({type:"never",...ee(t)})}function Du(e,t){return new mh({check:"less_than",...ee(t),value:e,inclusive:!1})}function dc(e,t){return new mh({check:"less_than",...ee(t),value:e,inclusive:!0})}function ju(e,t){return new hh({check:"greater_than",...ee(t),value:e,inclusive:!1})}function pc(e,t){return new hh({check:"greater_than",...ee(t),value:e,inclusive:!0})}function Uu(e,t){return new y$({check:"multiple_of",...ee(t),value:e})}function Bu(e,t){return new b$({check:"max_length",...ee(t),maximum:e})}function mi(e,t){return new v$({check:"min_length",...ee(t),minimum:e})}function qu(e,t){return new _$({check:"length_equals",...ee(t),length:e})}function Hg(e,t){return new x$({check:"string_format",format:"regex",...ee(t),pattern:e})}function Gg(e){return new S$({check:"string_format",format:"lowercase",...ee(e)})}function Kg(e){return new $$({check:"string_format",format:"uppercase",...ee(e)})}function Wg(e,t){return new k$({check:"string_format",format:"includes",...ee(t),includes:e})}function Jg(e,t){return new T$({check:"string_format",format:"starts_with",...ee(t),prefix:e})}function Qg(e,t){return new P$({check:"string_format",format:"ends_with",...ee(t),suffix:e})}function Is(e){return new E$({check:"overwrite",tx:e})}function Xg(e){return Is((t)=>t.normalize(e))}function Yg(){return Is((e)=>e.trim())}function ey(){return Is((e)=>e.toLowerCase())}function ty(){return Is((e)=>e.toUpperCase())}function ry(){return Is((e)=>dS(e))}function dk(e,t,r){return new e({type:"array",element:t,...ee(r)})}function ny(e,t,r){let n=ee(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function sy(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ee(r)})}function oy(e,t){let r=ED((n)=>(n.addIssue=(s)=>{if(typeof s==="string")n.issues.push(Po(s,n.value,r._zod.def));else{let o=s;if(o.fatal)o.continue=!1;if(o.code??(o.code="custom"),!("input"in o))o.input=n.value;o.inst??(o.inst=r),o.continue??(o.continue=!r._zod.def.abort),n.issues.push(Po(o))}},e(n.value,n)),t);return r}function ED(e,t){let r=new Nt({check:"custom",...ee(t)});return r._zod.check=e,r}var pk=b(()=>{Su();rr()});function fc(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))if(Object.prototype.propertyIsEnumerable.call(r,n))Rr(e,n,r[n]);return e}function hc(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Es,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Lt(e,t,r,n,s){let o=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:n.path,message:s}):t.unrepresentable;if(o==="any")return!1;if(o===void 0||o==="throw")throw Error(s);return Object.assign(r,o),!0}function Ge(e,t,r={path:[],schemaPath:[]}){var n;let s=e._zod.def,o=t.seen.get(e);if(o){if(o.count++,r.schemaPath.includes(e))o.cycle=r.path;return o.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let p=i.schema,f=t.processors[s.type];if(!f)throw Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);f(e,t,p,u)}let d=e._zod.parent;if(d){if(!i.ref)i.ref=d;Ge(d,t,u),t.seen.get(d).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)fc(i.schema,c);if(t.io==="input"&&nr(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function fk(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function gc(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let s=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(i[0])?.id,p=e.external.uri??((m)=>m);if(d)return{ref:p(d)};let f=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${fk(f)}`}}let c="#",l=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+fk(u)}},o=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:l}=s(i);if(a.def={...a.schema},l)a.defId=l;let u=a.schema;for(let d in u)delete u[d];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
59
|
+
|
|
60
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){o(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){o(i);continue}}if(e.metadataRegistry.get(i[0])?.id){o(i);continue}if(a.cycle){o(i);continue}if(a.count>1){if(e.reused==="ref")o(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function gk(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;gk(n);let s=Object.keys(n);if(s.length!==1||s[0]!=="type")return;let o=n.type;for(let i of Array.isArray(o)?o:[o]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}function hk(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function iy(e){let t=[];for(let o of e){if(typeof o!=="object"||o.type!=="object")return null;for(let i in o)if(!yk.has(i))return null;t.push(o)}let r={},n=new Set;for(let o of t){for(let i in o.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let l of t){let u=l.properties?.[i]??hk(l);if(u===null||u===void 0)continue;if(!a.some((d)=>JSON.stringify(d)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:iy(a)??{allOf:a};Rr(r,i,c)}for(let i of o.required??[])n.add(i)}let s={type:"object",properties:r};if(n.size)s.required=[...n];if(t.every((o)=>o.additionalProperties===!1))s.additionalProperties=!1;else{let o=[];for(let i of t){let a=hk(i);if(a&&!o.some((c)=>JSON.stringify(c)===JSON.stringify(a)))o.push(a)}if(o.length===1)s.additionalProperties=o[0];else if(o.length>1)s.additionalProperties={allOf:o}}return s}function ID(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let s of yk)if(s in e)return;let r=t.filter((s)=>mk.some((o)=>Array.isArray(s[o]))),n=null;if(!r.length)n=iy(t);else{let s=r[0],o=mk.find((c)=>Array.isArray(s[c]));if(Object.keys(s).length!==1)return;let i=t.filter((c)=>c!==s),a=s[o].map((c)=>iy([...i,c]));if(a.some((c)=>!c))return;n={[o]:a}}if(!n)return;delete e.allOf,fc(e,n)}function yc(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},d=c.ref;if(c.ref=null,d){n(d);let f=e.seen.get(d),m=f.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(m);else fc(l,m);if(fc(l,u),a._zod.parent===d)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(!(g in u))delete l[g]}if(m.$ref&&f.def)for(let g in l){if(g==="$ref"||g==="allOf")continue;if(g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g]))delete l[g]}}let p=a._zod.parent;if(p&&p!==d){n(p);let f=e.seen.get(p);if(f?.schema.$ref){if(l.$ref=f.schema.$ref,f.def)for(let m in l){if(m==="$ref"||m==="allOf")continue;if(m in f.def&&JSON.stringify(l[m])===JSON.stringify(f.def[m]))delete l[m]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())gk(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let d=a.get(u);if(d)d.push(l);else a.set(u,[l])}for(let c of e.intersections)for(let l of a.get(c)??[])ID(l)}}let s={};if(e.target==="draft-2020-12")s.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")s.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")s.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");s.$id=e.external.uri(a)}fc(s,r.defId?r.schema:r.def??r.schema);let o=e.metadataRegistry.get(t)?.id;if(o!==void 0&&s.id===o)delete s.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;Rr(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")s.$defs=i;else s.definitions=i;try{let a=JSON.parse(JSON.stringify(s));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:mc(t,"input",e.processors),output:mc(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function nr(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return nr(n.element,r);if(n.type==="set")return nr(n.valueType,r);if(n.type==="lazy")return nr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return nr(n.innerType,r);if(n.type==="intersection")return nr(n.left,r)||nr(n.right,r);if(n.type==="record"||n.type==="map")return nr(n.keyType,r)||nr(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return nr(n.in,r)||nr(n.out,r)}if(n.type==="object"){for(let s in n.shape)if(nr(n.shape[s],r))return!0;return!1}if(n.type==="union"){for(let s of n.options)if(nr(s,r))return!0;return!1}if(n.type==="tuple"){for(let s of n.items)if(nr(s,r))return!0;if(n.rest&&nr(n.rest,r))return!0;return!1}return!1}var yk,mk,wk=(e,t={})=>(r)=>{let n=hc({...r,processors:t});return Ge(e,n),gc(n,e),yc(n,e)},mc=(e,t,r={})=>(n)=>{let{libraryOptions:s,target:o}=n??{},i=hc({...s??{},target:o,io:t,processors:r});return Ge(e,i),gc(i,e),yc(i,e)};var Fu=b(()=>{fg();rr();yk=new Set(["type","properties","required","additionalProperties"]),mk=["oneOf","anyOf"]});function gr(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let o of n)AD[o._zod.def.check]?.(t,o._zod.def);let s=e._zod.bag;if(s.minimum!==void 0)hi(t,"minimum",s.minimum);if(s.exclusiveMinimum!==void 0)hi(t,"exclusiveMinimum",s.exclusiveMinimum);if(s.maximum!==void 0)gi(t,"maximum",s.maximum);if(s.exclusiveMaximum!==void 0)gi(t,"exclusiveMaximum",s.exclusiveMaximum);if(s.multipleOf!==void 0)$k(t,s.multipleOf);if(s.format!==void 0){if(t.format??(t.format=s.format),s.format.includes("int"))t.isInt=!0}if(s.mime)Tk(t,s.mime);for(let o of s.patterns??[])kk(t,o);return t}function wc(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return wc(t.out);if(t.type==="catch")return wc(t.innerType);return e._zod.optin}function ay(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let h=ay(e,m,r);return h===m?t:h}for(let m of["anyOf","oneOf"]){let h=t[m];if(!Array.isArray(h))continue;let g=h.map((w)=>ay(e,w,r));if(g.some((w,v)=>w!==h[v]))t={...t,[m]:g}}let n=Array.isArray(t.type)?t.type:[t.type],s=!n.includes("string")&&n.some((m)=>m==="number"||m==="integer"),o=t.enum??(t.const!==void 0?[t.const]:void 0);if(!s&&!o?.some((m)=>typeof m==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:p,...f}=t;if(f.enum)f.enum=f.enum.map((m)=>typeof m==="number"?String(m):m);else if(typeof f.const==="number")f.const=String(f.const);if(!s)return f;if(f.type="string",!o)f.pattern=(n.includes("number")?oc:ph).source;return f}function OD(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of cy.get(e)??[]){let s=e.seen.get(n),o=(s?.def??s?.schema)?.propertyNames;if(!o||o===!0||r.has(o))continue;let i=ay(t,o,new Set);if(i!==o)r.set(o,i)}if(!r.size)return;for(let n of e.seen.values())for(let s of[n.schema,n.def]){let o=s&&r.get(s.propertyNames);if(o)s.propertyNames=o}}function Fk(e,t,r,n,s){let o=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return o=!0,null});if(!o)return JSON.parse(i);return Lt(t,r,n,s,"BigInt defaults cannot be represented in JSON Schema"),Ty}function bc(e,t){if("_idmap"in e){let n=e,s=hc({...t,processors:Sk}),o={};for(let c of n._idmap.entries()){let[l,u]=c;Ge(u,s)}let i={},a={registry:n,uri:t?.uri,defs:o};s.external=a;for(let c of n._idmap.entries()){let[l,u]=c;gc(s,u),Rr(i,l,yc(s,u))}if(Object.keys(o).length>0){let c=s.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[c]:o}}return{schemas:i}}let r=hc({...t,processors:Sk});return Ge(e,r),gc(r,e),yc(r,e)}var hi=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},gi=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},bk=(e,t)=>{hi(e,"minimum",t),gi(e,"maximum",t)},$k=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},kk=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Tk=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Pk=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},vk=(e,t)=>hi(e,"minimum",t.minimum),_k=(e,t)=>gi(e,"maximum",t.maximum),xk=(e)=>(t,r)=>{Pk(t,r.format);let[n,s]=e[r.format];hi(t,"minimum",n),gi(t,"maximum",s)},AD,RD,CD,Ek=(e)=>CD.get(e)??e,ly=(e,t,r,n)=>{let s=r;s.type="string";let{minimum:o,maximum:i,format:a,patterns:c,contentEncoding:l,laxFormat:u}=gr(e);if(typeof o==="number")s.minLength=o;if(typeof i==="number")s.maxLength=i;if(a){if(s.format=RD[a]??a,s.format==="")delete s.format;if(a==="time"||u)delete s.format}if(l)s.contentEncoding=l;if(c&&c.size>0){let d=[...c].map(Ek);if(d.length===1)s.pattern=d[0].source;else if(d.length>1)s.allOf=[...d.map((p)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))]}},uy=(e,t,r,n)=>{let s=r,{minimum:o,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=gr(e);s.type=u?"integer":"number";let d=typeof l==="number"&&l>=(o??Number.NEGATIVE_INFINITY),p=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(d)if(f)s.minimum=l,s.exclusiveMinimum=!0;else s.exclusiveMinimum=l;else if(typeof o==="number")s.minimum=o;if(p)if(f)s.maximum=c,s.exclusiveMaximum=!0;else s.exclusiveMaximum=c;else if(typeof i==="number")s.maximum=i;if(a){let m=new Set;for(let w of a)if(Number.isFinite(w)&&w!==0)m.add(Math.abs(w));else Lt(e,t,s,n,`A multipleOf divisor of ${w} cannot be represented in JSON Schema`);let[h,...g]=m;if(h!==void 0)s.multipleOf=h;if(g.length)s.allOf=[...s.allOf??[],...g.map((w)=>({multipleOf:w}))]}},dy=(e,t,r,n)=>{r.type="boolean"},Ik=(e,t,r,n)=>{Lt(e,t,r,n,"BigInt cannot be represented in JSON Schema")},Ak=(e,t,r,n)=>{Lt(e,t,r,n,"Symbols cannot be represented in JSON Schema")},py=(e,t,r,n)=>{if(t.target==="openapi-3.0")r.type="string",r.nullable=!0,r.enum=[null];else r.type="null"},Rk=(e,t,r,n)=>{Lt(e,t,r,n,"Undefined cannot be represented in JSON Schema")},Ck=(e,t,r,n)=>{Lt(e,t,r,n,"Void cannot be represented in JSON Schema")},fy=(e,t,r,n)=>{r.not={}},Ok=(e,t,r,n)=>{},my=(e,t,r,n)=>{},zk=(e,t,r,n)=>{Lt(e,t,r,n,"Date cannot be represented in JSON Schema")},hy=(e,t,r,n)=>{let s=e._zod.def,o=Ga(s.entries);if(o.length===0){r.not={};return}if(o.every((i)=>typeof i==="number"))r.type="number";if(o.every((i)=>typeof i==="string"))r.type="string";r.enum=o},gy=(e,t,r,n)=>{let s=e._zod.def;if(s.values.length===0){r.not={};return}let o=[];for(let i of s.values)if(i===void 0){if(Lt(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof i==="bigint"){if(Lt(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;o.push(Number(i))}else o.push(i);if(o.length===0);else if(o.length===1){let i=o[0];if(r.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0")r.enum=[i];else r.const=i}else{if(o.every((i)=>typeof i==="number"))r.type="number";if(o.every((i)=>typeof i==="string"))r.type="string";if(o.every((i)=>typeof i==="boolean"))r.type="boolean";if(o.every((i)=>i===null))r.type="null";r.enum=o}},Mk=(e,t,r,n)=>{Lt(e,t,r,n,"NaN cannot be represented in JSON Schema")},Nk=(e,t,r,n)=>{let s=r,o=e._zod.pattern;if(!o)throw Error("Pattern not found in template literal");s.type="string",s.pattern=o.source},Lk=(e,t,r,n)=>{let s=r;s.type="string",s.format="binary",s.contentEncoding="binary";let{minimum:o,maximum:i,mime:a}=gr(e);if(o!==void 0)s.minLength=o;if(i!==void 0)s.maxLength=i;if(!a)return;if(a.length===0)s.not={};else if(a.length===1)s.contentMediaType=a[0];else s.anyOf=a.map((c)=>({contentMediaType:c}))},Dk=(e,t,r,n)=>{r.type="boolean"},yy=(e,t,r,n)=>{Lt(e,t,r,n,"Custom types cannot be represented in JSON Schema")},jk=(e,t,r,n)=>{Lt(e,t,r,n,"Function types cannot be represented in JSON Schema")},wy=(e,t,r,n)=>{Lt(e,t,r,n,"Transforms cannot be represented in JSON Schema")},Uk=(e,t,r,n)=>{Lt(e,t,r,n,"Map cannot be represented in JSON Schema")},Bk=(e,t,r,n)=>{Lt(e,t,r,n,"Set cannot be represented in JSON Schema")},by=(e,t,r,n)=>{let s=r,o=e._zod.def,{minimum:i,maximum:a}=gr(e);if(typeof i==="number")s.minItems=i;if(typeof a==="number")s.maxItems=a;s.type="array",s.items=Ge(o.element,t,{...n,path:[...n.path,"items"]})},vy=(e,t,r,n)=>{let s=r,o=e._zod.def,i=o.shape;if(Object.getOwnPropertySymbols(i).length&&Lt(e,t,s,n,"Symbol keys cannot be represented in JSON Schema"))return;s.type="object",s.properties={};for(let l in i)Rr(s.properties,l,Ge(i[l],t,{...n,path:[...n.path,"properties",l]}));let c=[];for(let l of Object.keys(i)){let u=o.shape[l];if(t.io==="input"?wc(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)s.required=c;if(o.catchall?._zod.def.type==="never")s.additionalProperties=!1;else if(!o.catchall){if(t.io==="output")s.additionalProperties=!1}else if(o.catchall)s.additionalProperties=Ge(o.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},_y=(e,t,r,n)=>{let s=e._zod.def,o=s.inclusive===!1,i=s.options.map((a,c)=>Ge(a,t,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));if(o)r.oneOf=i;else r.anyOf=i},xy=(e,t,r,n)=>{let s=e._zod.def,o=Ge(s.left,t,{...n,path:[...n.path,"allOf",0]}),i=Ge(s.right,t,{...n,path:[...n.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(o)?o.allOf:[o],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)},qk=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="array";let i=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"?"items":t.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((h,g)=>Ge(h,t,{...n,path:[...n.path,i,g]})),l=o.rest?Ge(o.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[o.items.length]:[]]}):null,u=o.items.length;while(u>0){let h=o.items[u-1];if(!(t.io==="input"?wc(h)!==void 0:h._zod.optout==="optional"))break;u--}let d=o.items.length,p=!o.rest;if(t.target==="draft-2020-12"){if(s.prefixItems=c,p)s.items=!1;else if(l)s.items=l;if(u>0)s.minItems=u;if(p)s.maxItems=d}else if(t.target==="openapi-3.0"){if(s.items={anyOf:c},l)s.items.anyOf.push(l);if(u>0)s.minItems=u;if(p)s.maxItems=d}else{if(s.items=c,p)s.additionalItems=!1;else if(l)s.additionalItems=l;if(u>0)s.minItems=u;if(p)s.maxItems=d}let{minimum:f,maximum:m}=gr(e);if(typeof f==="number")s.minItems=f;if(typeof m==="number")s.maxItems=m},cy,Sy=(e,t,r,n)=>{let s=r,o=e._zod.def;s.type="object";let i=o.keyType,a=gr(i).patterns;if(o.mode==="loose"&&a&&a.size>0){let u=Ge(o.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});s.patternProperties={};for(let d of a)Rr(s.patternProperties,Ek(d).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){s.propertyNames=Ge(o.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=cy.get(t);if(!u)u=[],cy.set(t,u),t.deferred.push(()=>OD(t));u.push(e)}s.additionalProperties=Ge(o.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,l=t.io==="input"&&wc(o.valueType)!==void 0;if(c&&!o.partial&&!l){let u=[...c].filter((d)=>typeof d==="string"||typeof d==="number");if(u.length>0)s.required=u.map(String)}},$y=(e,t,r,n)=>{let s=e._zod.def,o=Ge(s.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=s.innerType,r.nullable=!0;else r.anyOf=[o,{type:"null"}]},ky=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},Ty,Py=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i=Fk(s.defaultValue,e,t,r,n);if(i!==Ty)r.default=i},Ey=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);if(o.ref=s.innerType,t.io!=="input")return;let i=Fk(s.defaultValue,e,t,r,n);if(i!==Ty)r._prefault=i},Iy=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{Lt(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},Ay=(e,t,r,n)=>{let s=e._zod.def,o=s.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?o?s.out:s.in:s.out;Ge(i,t,n);let a=t.seen.get(e);a.ref=i},Ry=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType,r.readOnly=!0},Vk=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},Vu=(e,t,r,n)=>{let s=e._zod.def;Ge(s.innerType,t,n);let o=t.seen.get(e);o.ref=s.innerType},Zk=(e,t,r,n)=>{let s=e._zod.innerType;Ge(s,t,n);let o=t.seen.get(e);o.ref=s},Sk;var Zu=b(()=>{ic();ag();Fu();rr();AD={greater_than:(e,t)=>hi(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>gi(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>$k(e,t.value),number_format:xk(fu),bigint_format:xk(Xm),min_length:vk,max_length:_k,length_equals:(e,t)=>bk(e,t.length),min_size:vk,max_size:_k,size_equals:(e,t)=>bk(e,t.size),string_format:(e,t)=>{if(Pk(e,t.format),t.pattern)kk(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Tk(e,t.mime)};RD={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},CD=new Map([[Mh,s$],[Pu,o$]]);cy=new WeakMap;Ty=Symbol();Sk={string:ly,number:uy,boolean:dy,bigint:Ik,symbol:Ak,null:py,undefined:Rk,void:Ck,never:fy,any:Ok,unknown:my,date:zk,enum:hy,literal:gy,nan:Mk,template_literal:Nk,file:Lk,success:Dk,custom:yy,function:jk,transform:wy,map:Uk,set:Bk,array:by,object:vy,union:_y,intersection:xy,tuple:qk,record:Sy,nullable:$y,nonoptional:ky,default:Py,prefault:Ey,catch:Iy,pipe:Ay,readonly:Ry,promise:Vk,optional:Vu,lazy:Zk}});var Hk=()=>{};var yr=b(()=>{rr();ic();Nu();Hk();Eo();qS();ah();ag();sk();Su();yh();fg();lk();pk();Fu()});var Cy=b(()=>{yr()});function Hu(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var Gk,BD=(e,t)=>{RS.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(Gk.has(r))return;Gk.add(r),Hu(r,"format",(n)=>(s)=>ih(n,s)),Hu(r,"flatten",(n)=>(s)=>oh(n,s)),Hu(r,"addIssue",(n)=>(s)=>{n.issues.push(s),n.message=JSON.stringify(n.issues,Ka,2)}),Hu(r,"addIssues",(n)=>(s)=>{n.issues.push(...s),n.message=JSON.stringify(n.issues,Ka,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},Cr;var Oy=b(()=>{yr();yr();rr();Gk=new WeakSet([Object.prototype,Error.prototype]);Cr=R("ZodError",BD,void 0,{Parent:Error})});var Kk,Wk,Jk,Qk,Xk,Yk,eT,tT,rT,nT,sT,oT;var zy=b(()=>{yr();Oy();yr();Kk=Ya(Cr),Wk=ec(Cr),Jk=tc(Cr),Qk=nc(Cr),Xk=zS(Cr),Yk=MS(Cr),eT=NS(Cr),tT=LS(Cr),rT=DS(Cr),nT=jS(Cr),sT=US(Cr),oT=BS(Cr)});function O3(){if(!mr.localeError)hr(dg())}function Ku(){if(!mr.memoizer)hr({memoizer:ug()})}function E(e){return mg(z3,e)}function xe(e){return Ug(mT,e)}function iT(e){return Bg(Y3,e)}function St(e){return qg(ej,e)}function hT(e){return Fg(tj,e)}function Qe(){return Vg(rj)}function sj(e){return Zg(nj,e)}function $e(e,t){return dk(oj,e,t)}function Z(e,t){let r={type:"object",shape:e??{},...ee(t)};return new gT(r)}function sr(e,t){return new gT({type:"object",shape:e,catchall:Qe(),...ee(t)})}function Xe(e,t){return new yT({type:"union",options:e,...ee(t)})}function Ly(e,t,r){return new ij({type:"union",options:t,discriminator:e,...ee(r)})}function Wu(e,t){return new aj({type:"intersection",left:e,right:t})}function Ke(e,t,r){if(!t||!t._zod)return new aT({type:"record",keyType:E(),valueType:e,...ee(t)});return new aT({type:"record",keyType:e,valueType:t,...ee(r)})}function or(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new My({type:"enum",entries:r,...ee(t)})}function oe(e,t){return new cj({type:"literal",values:Array.isArray(e)?e:[e],...ee(t)})}function wT(e){return new lj({type:"transform",transform:e})}function et(e){return new Ju({type:"optional",innerType:e})}function uj(e){return new bT({type:"optional",innerType:e})}function cT(e){return new dj({type:"nullable",innerType:e})}function fj(e,t){return new pj({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():pu(t)}})}function hj(e,t){return new mj({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():pu(t)}})}function gj(e,t){return new vT({type:"nonoptional",innerType:e,...ee(t)})}function wj(e,t){return new yj({type:"catch",innerType:e,catchValue:typeof t==="function"?t:TS(t)})}function lT(e,t){return new _T({type:"pipe",in:e,out:t})}function _j(e){return new vj({type:"readonly",innerType:e})}function ST(e,t){return ny(xT,e??(()=>!0),t)}function xj(e,t={}){return sy(xT,e,t)}function Sj(e,t){return oy(e,t)}function Dy(e,t){return new bj({type:"pipe",in:wT(e),out:t})}var tt,uT,z3,it,Ny,dT,pT,fT,M3,N3,Gu,L3,D3,j3,U3,B3,q3,F3,V3,Z3,H3,G3,K3,W3,J3,Q3,X3,mT,Y3,ej,tj,rj,nj,oj,gT,yT,ij,aj,aT,My,cj,lj,Ju,bT,dj,pj,mj,vT,yj,_T,bj,vj,xT;var jy=b(()=>{yr();yr();Zu();Fu();ok();Cy();zy();tt=R("ZodType",(e,t)=>(O3(),He.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(dr(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return pr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(xj(e,t))},superRefine(e,t){return this.check(Sj(e,t))},overwrite(e){return this.check(Is(e))},optional(){return et(this)},exactOptional(){return uj(this)},nullable(){return cT(this)},nullish(){return et(cT(this))},nonoptional(e){return gj(this,e)},array(){return $e(this)},or(e){return Xe([this,e])},and(e){return Wu(this,e)},transform(e){return lT(this,wT(e))},default(e){return fj(this,e)},prefault(e){return hj(this,e)},catch(e){return wj(this,e)},pipe(e){return lT(this,e)},readonly(){return _j(this)},describe(e){let t=this.clone();return Es.add(t,{description:e}),t},meta(...e){if(e.length===0)return Es.get(this);let t=this.clone();return Es.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return wu(this,"~standard",{...bh(this),jsonSchema:{input:mc(this,"input"),output:mc(this,"output")}})},set "~standard"(e){sn(this,"~standard",e)},parse:function e(t,r){return Kk(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Wk(this,t,r,{callee:e})},safeParse(e,t){return Jk(this,e,t)},async safeParseAsync(e,t){return Qk(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){sn(this,"spa",e)},validate(e,t){return vu(this,e,t)},validateAsync(e,t){return _u(this,e,t)},encode:function e(t,r){return Xk(this,t,r,{callee:e})},decode:function e(t,r){return Yk(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await eT(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await tT(this,t,r,{callee:e})},safeEncode(e,t){return rT(this,e,t)},safeDecode(e,t){return nT(this,e,t)},async safeEncodeAsync(e,t){return sT(this,e,t)},async safeDecodeAsync(e,t){return oT(this,e,t)},toJSONSchema(e){return wk(this,{})(e)},get description(){return Es.get(this)?.description},get _def(){return this._zod.def}}),uT=R("_ZodString",(e,t)=>{cc.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>ly(e,r,n,s)},kS({format:(e)=>gr(e).format??null,minLength:(e)=>gr(e).minimum??null,maxLength:(e)=>gr(e).maximum??null},{regex(...e){return this.check(Hg(...e))},includes(...e){return this.check(Wg(...e))},startsWith(...e){return this.check(Jg(...e))},endsWith(...e){return this.check(Qg(...e))},min(...e){return this.check(mi(...e))},max(...e){return this.check(Bu(...e))},length(...e){return this.check(qu(...e))},nonempty(...e){return this.check(mi(1,...e))},lowercase(e){return this.check(Gg(e))},uppercase(e){return this.check(Kg(e))},trim(){return this.check(Yg())},normalize(...e){return this.check(Xg(...e))},toLowerCase(){return this.check(ey())},toUpperCase(){return this.check(ty())},slugify(){return this.check(ry())}})),z3=R("ZodString",(e,t)=>{cc.init(e,t),uT.init(e,t)},{email(e){return this.check(hg(M3,e))},url(e){return this.check(_g(L3,e))},jwt(e){return this.check(Ng(X3,e))},emoji(e){return this.check(xg(D3,e))},guid(e){return this.check(gg(N3,e))},uuid(e){return this.check(yg(Gu,e))},uuidv4(e){return this.check(wg(Gu,e))},uuidv6(e){return this.check(bg(Gu,e))},uuidv7(e){return this.check(vg(Gu,e))},nanoid(e){return this.check(Sg(j3,e))},cuid(e){return this.check($g(U3,e))},cuid2(e){return this.check(kg(B3,e))},ulid(e){return this.check(Tg(q3,e))},base64(e){return this.check(Og(W3,e))},base64url(e){return this.check(zg(J3,e))},xid(e){return this.check(Pg(F3,e))},ksuid(e){return this.check(Eg(V3,e))},ipv4(e){return this.check(Ig(Z3,e))},ipv6(e){return this.check(Ag(H3,e))},cidrv4(e){return this.check(Rg(G3,e))},cidrv6(e){return this.check(Cg(K3,e))},e164(e){return this.check(Mg(Q3,e))},datetime(e){return this.check(Lu(Ny,e))},date(e){return this.check(Lg(dT,e))},time(e){return this.check(Dg(pT,e))},duration(e){return this.check(jg(fT,e))}});it=R("ZodStringFormat",(e,t)=>{We.init(e,t),uT.init(e,t)}),Ny=R("ZodISODateTime",(e,t)=>{V$.init(e,t),it.init(e,t)}),dT=R("ZodISODate",(e,t)=>{Z$.init(e,t),it.init(e,t)}),pT=R("ZodISOTime",(e,t)=>{H$.init(e,t),it.init(e,t)}),fT=R("ZodISODuration",(e,t)=>{G$.init(e,t),it.init(e,t)}),M3=R("ZodEmail",(e,t)=>{xh.init(e,t),it.init(e,t)}),N3=R("ZodGUID",(e,t)=>{vh.init(e,t),it.init(e,t)}),Gu=R("ZodUUID",(e,t)=>{_h.init(e,t),it.init(e,t)}),L3=R("ZodURL",(e,t)=>{Sh.init(e,t),it.init(e,t)}),D3=R("ZodEmoji",(e,t)=>{$h.init(e,t),it.init(e,t)}),j3=R("ZodNanoID",(e,t)=>{kh.init(e,t),it.init(e,t)}),U3=R("ZodCUID",(e,t)=>{Th.init(e,t),it.init(e,t)}),B3=R("ZodCUID2",(e,t)=>{Ph.init(e,t),it.init(e,t)}),q3=R("ZodULID",(e,t)=>{Eh.init(e,t),it.init(e,t)}),F3=R("ZodXID",(e,t)=>{Ih.init(e,t),it.init(e,t)}),V3=R("ZodKSUID",(e,t)=>{Ah.init(e,t),it.init(e,t)}),Z3=R("ZodIPv4",(e,t)=>{Rh.init(e,t),it.init(e,t)}),H3=R("ZodIPv6",(e,t)=>{Ch.init(e,t),it.init(e,t)}),G3=R("ZodCIDRv4",(e,t)=>{Oh.init(e,t),it.init(e,t)}),K3=R("ZodCIDRv6",(e,t)=>{zh.init(e,t),it.init(e,t)}),W3=R("ZodBase64",(e,t)=>{Nh.init(e,t),it.init(e,t)}),J3=R("ZodBase64URL",(e,t)=>{Lh.init(e,t),it.init(e,t)}),Q3=R("ZodE164",(e,t)=>{Dh.init(e,t),it.init(e,t)}),X3=R("ZodJWT",(e,t)=>{jh.init(e,t),it.init(e,t)}),mT=R("ZodNumber",(e,t)=>{Eu.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>uy(e,r,n,s),e.isFinite=!0},kS({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=gr(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=gr(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=gr(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>gr(e).format??null},{gt(e,t){return this.check(ju(e,t))},gte(e,t){return this.check(pc(e,t))},min(e,t){return this.check(pc(e,t))},lt(e,t){return this.check(Du(e,t))},lte(e,t){return this.check(dc(e,t))},max(e,t){return this.check(dc(e,t))},int(e){return this.check(iT(e))},safe(e){return this.check(iT(e))},positive(e){return this.check(ju(0,e))},nonnegative(e){return this.check(pc(0,e))},negative(e){return this.check(Du(0,e))},nonpositive(e){return this.check(dc(0,e))},multipleOf(e,t){return this.check(Uu(e,t))},step(e,t){return this.check(Uu(e,t))},finite(){return this}}));Y3=R("ZodNumberFormat",(e,t)=>{Uh.init(e,t),mT.init(e,t)});ej=R("ZodBoolean",(e,t)=>{Bh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>dy(e,r,n,s)});tj=R("ZodNull",(e,t)=>{qh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>py(e,r,n,s)});rj=R("ZodUnknown",(e,t)=>{Fh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>my(e,r,n,s)});nj=R("ZodNever",(e,t)=>{Vh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>fy(e,r,n,s)});oj=R("ZodArray",(e,t)=>{Ku(),Zh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>by(e,r,n,s),e.element=t.element},{min(e,t){return this.check(mi(e,t))},nonempty(e){return this.check(mi(1,e))},max(e,t){return this.check(Bu(e,t))},length(e,t){return this.check(qu(e,t))},unwrap(){return this.element}});gT=R("ZodObject",(e,t)=>{Ku(),X$.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>vy(e,r,n,s),th(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return or(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(dr(this._zod.def,{catchall:e}))},passthrough(){return this.clone(dr(this._zod.def,{catchall:Qe()}))},loose(){return this.clone(dr(this._zod.def,{catchall:Qe()}))},strict(){return this.clone(dr(this._zod.def,{catchall:sj()}))},strip(){return this.clone(dr(this._zod.def,{catchall:void 0}))},extend(e){return yS(this,e)},safeExtend(e){return bS(this,e)},merge(e){return vS(this,e)},pick(e){return hS(this,e)},omit(e){return gS(this,e)},partial(...e){return Ym(Ju,this,e[0])},exactPartial(...e){return Ym(bT,this,e[0],"exactPartial")},required(...e){return _S(vT,this,e[0])}});yT=R("ZodUnion",(e,t)=>{Iu.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>_y(e,r,n,s),e.options=t.options});ij=R("ZodDiscriminatedUnion",(e,t)=>{yT.init(e,t),Gh.init(e,t)});aj=R("ZodIntersection",(e,t)=>{Kh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>xy(e,r,n,s)});aT=R("ZodRecord",(e,t)=>{Ku(),Wh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Sy(e,r,n,s),e.keyType=t.keyType,e.valueType=t.valueType});My=R("ZodEnum",(e,t)=>{Jh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(n,s,o)=>hy(e,n,s,o),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new My({...t,checks:[],...ee(s),entries:o})},e.exclude=(n,s)=>{let o={...t.entries};for(let i of n)if(r.has(i))delete o[i];else throw Error(`Key ${i} not found in enum`);return new My({...t,checks:[],...ee(s),entries:o})}});cj=R("ZodLiteral",(e,t)=>{Qh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>gy(e,r,n,s),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});lj=R("ZodTransform",(e,t)=>{Ku(),Xh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>wy(e,r,n,s),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Qa(e.constructor.name);r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(Po(o,r.value,t));else{let i=o;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(Po(i))}};let s=t.transform(r.value,r);if(s instanceof Promise)return s.then((o)=>(r.value=o,r));return r.value=s,r}});Ju=R("ZodOptional",(e,t)=>{Au.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Vu(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});bT=R("ZodExactOptional",(e,t)=>{Yh.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Vu(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});dj=R("ZodNullable",(e,t)=>{eg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>$y(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});pj=R("ZodDefault",(e,t)=>{tg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Py(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});mj=R("ZodPrefault",(e,t)=>{rg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ey(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});vT=R("ZodNonOptional",(e,t)=>{ng.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>ky(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});yj=R("ZodCatch",(e,t)=>{sg.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Iy(e,r,n,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});_T=R("ZodPipe",(e,t)=>{Ru.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ay(e,r,n,s),e.in=t.in,e.out=t.out});bj=R("ZodPreprocess",(e,t)=>{_T.init(e,t),Y$.init(e,t)}),vj=R("ZodReadonly",(e,t)=>{og.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>Ry(e,r,n,s),e.unwrap=()=>e._zod.def.innerType});xT=R("ZodCustom",(e,t)=>{ig.init(e,t),tt.init(e,t),e._zod.processJSONSchema=(r,n,s)=>yy(e,r,n,s)})});var $T;var kT=b(()=>{(function(e){})($T||($T={}))});function $j(e){return Lu(Ny,e)}var PT=b(()=>{yr();jy()});var ET=()=>{};var Xu=b(()=>{yr();yr();Zu();Nu();PT();ET();jy();Cy();Oy();zy();kT()});var vc=b(()=>{Xu();Xu()});function xc(e){return Hy.includes(e)}function Rs(e){return td.includes(e)}var As,Yu,Uy,IT,By="hl_",qy=0.7,Fy=0.85,Vy,_c=4,Zy,AT,RT,ed,Hy,td;var Br=b(()=>{vc();As={userId:"local"},Yu=["owner","admin","member"],Uy=["read","generate","paid","train"],IT=[30,90,365,null],Vy=/^[a-z0-9][a-z0-9-]{0,63}$/,Zy=["sd1","sdxl","flux","wan","z-image"],AT=["sd1","sdxl"],RT=Z({prompt:E().trim().min(1),aspectRatio:E().regex(/^\d+:\d+$/).optional(),seed:xe().int().nonnegative().optional(),count:xe().int().min(1).max(8).default(1),durationSeconds:xe().int().min(1).max(120).optional(),referenceAssetIds:$e(E()).default([]),strength:xe().min(0.05).max(1).optional(),maskAssetId:E().optional(),loras:$e(Z({id:E().regex(Vy),weight:xe().min(-2).max(2).default(1)})).max(_c*Zy.length).optional(),extras:Ke(E(),Qe()).default({})}),ed=["succeeded","failed","canceled"],Hy=["local","openai","google","openrouter","off"];td=["auto","local","openai","google","openrouter"]});import{createHash as Wy,timingSafeEqual as Tj}from"crypto";async function NT(e,t){if(t?.throwIfAborted(),Gy>=Aj){if(Sc.length>=Rj)throw new be("The server is busy. Try again in a few seconds","serverBusy",503);await new Promise((r,n)=>{let s=()=>{t?.removeEventListener("abort",o),r()},o=()=>{let i=Sc.indexOf(s);if(i>=0)Sc.splice(i,1);n(t?.reason)};Sc.push(s),t?.addEventListener("abort",o,{once:!0})})}else Gy++;try{return await e()}finally{let r=Sc.shift();if(r)r();else Gy--}}function yi(){return Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("base64url")}function Sn(e){return Wy("sha256").update(e).digest("hex")}function zj(e,t){return Tj(Wy("sha256").update(e).digest(),Wy("sha256").update(t).digest())}function Mj(e){return{id:e.id,username:e.username,displayName:e.displayName,role:e.role,canUsePaid:wi(e),canTrain:sd(e),monthlyLimitUsd:e.monthlyLimitUsd,totp:e.totpSecret!=null,mustChangePassword:e.mustChangePassword,disabled:e.disabledAt!=null,createdAt:e.createdAt,lastReset:null,resetNotice:null,storage:{usedBytes:0,quotaBytes:null}}}class $c{repo;options;now;hasher;code=null;dummy=null;constructor(e,t={}){this.repo=e;this.options=t;this.now=t.now??Date.now,this.hasher=t.hasher??Cj}async verifyPassword(e,t,r){if(e.length<rd||e.length>DT)return!1;return NT(()=>this.hasher.verify(e,t),r)}hashPassword(e,t){return Lj(e),NT(()=>this.hasher.hash(e),t)}needsSetup(){return this.repo.countUsers()===0}setupCode(){if(!this.needsSetup())return null;if(!this.code){let r=[...crypto.getRandomValues(new Uint8Array(12))].map((n)=>"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"[n>>3]);this.code=[0,4,8].map((n)=>r.slice(n,n+4).join("")).join("-")}return this.code}async setup(e,t={}){let r=this.setupCode(),n=e.code.trim().toUpperCase();if(!r||!zj(r,n))throw new be("The setup code is not right","badSetupCode",403);let s=await this.newUser(e.username,e.password,{role:"owner",canUsePaid:!0,canTrain:!0,monthlyLimitUsd:null},t.signal);if(!this.repo.createFirstOwner(s))throw new be("The server is already set up","forbidden",403);return this.code=null,await this.options.adoptLocal?.(s.id),this.startSession(s,t)}async resumeAdoption(){let e=this.repo.listUsers()[0];if(e)await this.options.adoptLocal?.(e.id)}async login(e,t={}){t.signal?.throwIfAborted();let r=this.repo.findUser(e.username.trim()),n=e.password;if(!r)throw await this.verifyPassword(n,await this.dummyHash(),t.signal),LT();if(!await this.verifyPassword(n,r.passwordHash,t.signal)||r.disabledAt!=null)throw LT();if(r.totpSecret){if(!e.totp)throw new be("Enter the code from your authenticator app","totpRequired",401);this.useTotpCode(r,e.totp,401)}return this.startSession(r,t)}dummyHash(){return this.dummy??=this.hasher.hash(yi()),this.dummy}startSession(e,t){let r=yi(),n=this.now(),s=n+CT;return this.repo.createSession({id:Sn(r),userId:e.id,createdAt:n,lastSeenAt:n,expiresAt:s,userAgent:t.userAgent?.slice(0,300)??null,ip:t.ip??null}),{user:e,token:r,expiresAt:s}}resolveSession(e){let t=this.repo.getSession(Sn(e)),r=this.now();if(!t||t.expiresAt<r)return null;let n=this.repo.getUser(t.userId);if(!n||n.disabledAt!=null)return null;let s=t.expiresAt;if(r-t.lastSeenAt>=OT)s=r+CT,this.repo.touchSession(t.id,r,s);return{user:n,sessionId:t.id,apiToken:null,expiresAt:s}}resolveApiToken(e){if(!e.startsWith(By))return null;let t=this.repo.getToken(Sn(e)),r=this.now();if(!t||t.expiresAt!=null&&t.expiresAt<r)return null;let n=this.repo.getUser(t.userId);if(!n||n.disabledAt!=null)return null;if(t.lastUsedAt==null||r-t.lastUsedAt>=OT)this.repo.touchToken(t.id,r);return{user:n,sessionId:null,apiToken:t}}logout(e,t){this.repo.deleteSession(e,t)}sessions(e,t){return this.repo.listSessions(e,this.now()).map((r)=>({id:r.id,createdAt:r.createdAt,lastSeenAt:r.lastSeenAt,userAgent:r.userAgent,ip:r.ip,current:r.id===t}))}revokeSession(e,t){if(!this.repo.deleteSession(e,t))throw new Ee("Session not found")}revokeOtherSessions(e,t,r={}){if(this.repo.deleteSessionsOf(e,t??void 0),r.tokens)this.repo.deleteTokensOf(e)}async changePassword(e,t,r,n){let s=this.mustGet(e);if(!await this.verifyPassword(t.current,s.passwordHash,n))throw new be("The current password is not right","badPassword",403);this.repo.updateUser(e,{passwordHash:await this.hashPassword(t.next,n),mustChangePassword:!1}),this.repo.deleteSessionsOf(e,r??void 0),this.repo.deleteTokensOf(e)}startTotp(e){let t=this.mustGet(e),r=nS();return{secret:r,uri:sS(r,t.username,"Hatchlight")}}useTotpCode(e,t,r){let n=e.totpSecret?Hm(e.totpSecret,t,this.now()):null;if(n===null||!this.repo.advanceTotpCounter(e.id,n))throw new be("The code is not right","badTotp",r);e.totpLastCounter=n}async assertOwnsAccount(e,t,r,n){if(!await this.verifyPassword(t,e.passwordHash,n))throw new be("The current password is not right","badPassword",403);if(e.totpSecret){if(!r)throw new be("Enter the code from your authenticator app","totpRequired",403);this.useTotpCode(e,r,403)}}async enableTotp(e,t,r){let n=this.mustGet(e);await this.assertOwnsAccount(n,t.password,t.current,r);let s=/^[A-Z2-7]{32}$/.test(t.secret)?Hm(t.secret,t.code,this.now()):null;if(s===null)throw new be("The code is not right","badTotp",403);this.repo.updateUser(e,{totpSecret:t.secret,totpLastCounter:s})}async disableTotp(e,t,r){let n=this.mustGet(e);await this.assertOwnsAccount(n,t.password,t.code,r),this.repo.updateUser(e,{totpSecret:null,totpLastCounter:null})}createInvite(e,t){this.assertMayGrant(e,t.role);let r=yi(),n=this.now(),s={id:Sn(r),role:t.role,canUsePaid:t.canUsePaid,canTrain:t.canTrain,monthlyLimitUsd:t.monthlyLimitUsd,expiresAt:n+Pj,createdBy:e.id,createdAt:n,usedBy:null,usedAt:null};return this.repo.createInvite(s),{token:r,invite:Ky(s)}}invites(){return this.repo.listInvites().map(Ky)}deleteInvite(e){if(!this.repo.deleteInvite(e))throw new Ee("Invite not found")}inviteFor(e){let t=this.repo.getInvite(Sn(e));if(!t||t.usedAt!=null||t.expiresAt<this.now())return null;return Ky(t)}async acceptInvite(e,t,r={}){let n=()=>new be("This invite has expired or was already used","inviteInvalid",403),s=this.repo.getInvite(Sn(e));if(!s||s.usedAt!=null||s.expiresAt<this.now())throw n();let o=await this.newUser(t.username,t.password,s,r.signal);if(!this.repo.acceptInvite(s.id,o))throw n();return this.startSession(o,r)}users(){return this.repo.listUsers().map((e)=>this.view(e))}view(e,t=!1){let r=this.repo.lastUsedReset(e.id),n=r&&{by:r.by,at:r.at};return{...Mj(e),lastReset:n,resetNotice:t&&r&&r.noticedAt==null?n:null,storage:{usedBytes:this.repo.assetBytes(e.id),quotaBytes:this.assetQuota(e)}}}assetQuota(e){return e.role==="member"?this.options.assetQuotaBytes??null:null}storageRefusal(e,t=0){let r=this.repo.getUser(e),n=r?this.assetQuota(r):null;if(n==null)return null;let s=this.repo.assetBytes(e);if(s<n&&(t===0||s+t<=n))return null;return new be("Your pictures take all the room you have on this server","storageFull",403,{maxBytes:n})}dismissResetNotice(e){let t=this.repo.lastUsedReset(e);if(t&&t.noticedAt==null)this.repo.markResetNoticed(t.id,this.now())}updateUser(e,t,r){let n=this.mustGet(t);if(this.assertMayManage(e,n),r.role!==void 0)this.assertMayGrant(e,r.role);let s={};if(r.role!==void 0)s.role=r.role;if(r.canUsePaid!==void 0)s.canUsePaid=r.canUsePaid;if(r.canTrain!==void 0)s.canTrain=r.canTrain;if(r.monthlyLimitUsd!==void 0)s.monthlyLimitUsd=r.monthlyLimitUsd;if(r.displayName!==void 0)s.displayName=Nj(r.displayName,n.username);if(r.disabled!==void 0)s.disabledAt=r.disabled?n.disabledAt??this.now():null;if(n.role==="owner"&&n.disabledAt==null&&(s.role!==void 0&&s.role!=="owner"||s.disabledAt!=null)&&this.repo.countActiveOwners()<=1)throw new be("The server needs at least one owner who can sign in","lastOwner",403);if(Object.keys(s).length>0)this.repo.updateUser(t,s);if(s.disabledAt!=null)this.repo.deleteSessionsOf(t);if(s.disabledAt!=null||s.role!==void 0&&s.role!==n.role)this.repo.deleteTokensOf(t);return this.view(this.mustGet(t))}async resetPasswordFromConsole(e){this.mustGet(e);let t=yi().slice(0,16);return this.repo.updateUser(e,{passwordHash:await this.hashPassword(t),mustChangePassword:!0,totpSecret:null,totpLastCounter:null}),this.repo.deleteSessionsOf(e),this.repo.deleteTokensOf(e),t}createPasswordReset(e,t){let r=this.mustGet(t);this.assertMayManage(e,r);let n=yi(),s=this.now(),o=s+Ij;return this.repo.expireUnusedResets(t,s),this.repo.createPasswordReset({id:Sn(n),userId:t,createdBy:e.id,createdAt:s,expiresAt:o,usedAt:null,noticedAt:null}),{token:n,expiresAt:o}}passwordResetFor(e){let t=this.repo.getPasswordReset(Sn(e));if(!t||t.usedAt!=null||t.expiresAt<this.now())return null;let r=this.repo.getUser(t.userId);return r&&r.disabledAt==null?{username:r.username}:null}async usePasswordReset(e,t,r){let n=()=>new be("This link has expired or was already used","resetInvalid",403),s=this.repo.getPasswordReset(Sn(e));if(!s||s.usedAt!=null||s.expiresAt<this.now())throw n();let o=this.repo.getUser(s.userId);if(!o||o.disabledAt!=null)throw n();let i=await this.hashPassword(t,r);if(!this.repo.usePasswordReset(s.id,this.now()))throw n();this.repo.updateUser(o.id,{passwordHash:i,mustChangePassword:!1}),this.repo.deleteSessionsOf(o.id),this.repo.deleteTokensOf(o.id)}findUser(e){return this.repo.findUser(e)}getUser(e){return this.repo.getUser(e)}createApiToken(e,t){let r=this.mustGet(e),n=t.name.trim();if(!n||n.length>MT)throw new O(`A token needs a name of at most ${MT} characters`);let s=[...new Set(t.scopes)];if(s.length===0||s.some((u)=>!Uy.includes(u)))throw new O(`A token needs scopes among ${Uy.join(", ")}`);if(s.includes("paid")&&!wi(r))throw new be("This account cannot use paid models","paidNotAllowed",403);if(s.includes("train")&&!sd(r))throw new be("This account cannot train","forbidden",403);let o=t.spendLimitUsd??null;if(o!==null&&!(Number.isFinite(o)&&o>=0))throw new O("The spending limit must be 0 or more");let i=t.expiresInDays===void 0?Ej:t.expiresInDays;if(!IT.includes(i))throw new O("A token lasts 30, 90 or 365 days, or until revoked");if(this.repo.listTokensOf(e).length>=zT)throw new O(`At most ${zT} tokens each: revoke one first`);let a=`${By}${yi()}`,c=this.now(),l={id:Sn(a),ref:Ft("tok"),userId:e,name:n,scopes:s,spendLimitUsd:o,createdAt:c,lastUsedAt:null,expiresAt:i===null?null:c+i*nd};return this.repo.createToken(l),{token:a,view:this.tokenView(l)}}async createApiTokenConfirmed(e,t,r,n){let s=this.mustGet(e);return await this.assertOwnsAccount(s,t.password,t.code,n),this.createApiToken(e,r)}listApiTokens(e){return this.mustGet(e),this.repo.listTokensOf(e).map((t)=>this.tokenView(t))}revokeApiToken(e,t){if(!this.repo.deleteToken(e,t))throw new Ee("Token not found","tokenNotFound")}listApiTokensOf(e,t){return this.assertMayManage(e,this.mustGet(t)),this.listApiTokens(t)}revokeApiTokenOf(e,t,r){this.assertMayManage(e,this.mustGet(t)),this.revokeApiToken(t,r)}liveToken(e){let t=this.repo.getTokenByRef(e);if(!t||t.expiresAt!=null&&t.expiresAt<this.now())return null;return t}spentByToken(e){return this.repo.spentByToken(e)}tokenView(e){return{id:e.ref??"",name:e.name,scopes:e.scopes,spendLimitUsd:e.spendLimitUsd,spentUsd:e.ref?this.repo.spentByToken(e.ref):0,createdAt:e.createdAt,lastUsedAt:e.lastUsedAt,expiresAt:e.expiresAt}}recordLoraUpload(e,t,r){this.repo.recordLoraUpload({loraId:t,userId:e,sizeBytes:r,createdAt:this.now()})}loraUsage(e,t){let r=this.repo.loraUploadsOf(e).filter((n)=>t.has(n.loraId));return{files:r.length,bytes:r.reduce((n,s)=>n+s.sizeBytes,0)}}forgetLoraUpload(e){this.repo.forgetLoraUpload(e)}spentThisMonth(e){let t=new Date(this.now());return this.repo.spentSince(e,Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1))}mustGet(e){let t=this.repo.getUser(e);if(!t)throw new Ee("User not found");return t}assertMayManage(e,t){if(e.role==="owner")return;if(e.role==="admin"&&t.role==="member"&&t.id!==e.id)return;throw new be("Only an owner can change this account","forbidden",403)}assertMayGrant(e,t){if(!Yu.includes(t))throw new O(`Unknown role: ${t}`);if(e.role==="owner")return;if(e.role==="admin"&&t==="member")return;throw new be("Only an owner can make admins and owners","forbidden",403)}async newUser(e,t,r,n){let s=e.trim().toLowerCase();if(!Oj.test(s))throw new O("A username is 3 to 32 letters a to z, digits, dots, dashes or underscores","usernameInvalid");if(this.repo.findUser(s))throw new O("That username is taken","usernameTaken");return{id:Ft("usr"),username:s,displayName:s,passwordHash:await this.hashPassword(t,n),role:r.role,canUsePaid:r.canUsePaid,canTrain:r.canTrain,monthlyLimitUsd:r.monthlyLimitUsd,totpSecret:null,totpLastCounter:null,mustChangePassword:!1,disabledAt:null,createdAt:this.now()}}}function Nj(e,t){return e.trim().slice(0,64)||t}function Lj(e){if(e.length<rd)throw new O(`A password needs at least ${rd} characters`,"passwordTooShort",{min:rd});if(e.length>DT)throw new O("That password is too long")}function Ky(e){return{id:e.id,role:e.role,canUsePaid:e.canUsePaid,canTrain:e.canTrain,monthlyLimitUsd:e.monthlyLimitUsd,expiresAt:e.expiresAt,createdAt:e.createdAt,usedAt:e.usedAt}}var rd=10,DT=256,nd=86400000,CT,OT=60000,Pj,Ej=90,zT=50,MT=64,Ij,Aj=4,Rj=64,Gy=0,Sc,Cj,Oj,sd=(e)=>e.role!=="member"||e.canTrain,wi=(e)=>e.role!=="member"||e.canUsePaid,LT=()=>new be("The username or password is not right","badCredentials",401);var jT=b(()=>{Ar();Gm();Br();CT=30*nd,Pj=7*nd,Ij=nd,Sc=[];Cj={hash:(e)=>Bun.password.hash(e,{algorithm:"argon2id"}),verify:(e,t)=>Bun.password.verify(e,t)},Oj=/^[a-z0-9._-]{3,32}$/});import{mkdir as Jy,readdir as UT,rename as Qy,rm as BT}from"fs/promises";import{dirname as Dj,join as Ro}from"path";class Xy{root;onAdded;constructor(e,t){this.root=e;this.onAdded=t}path(e,t){if(!/^[a-f0-9]{64}$/.test(t))throw Error("Invalid asset hash");if(!/^[\w-]+$/.test(e.userId))throw Error("Invalid user id");return Ro(this.root,e.userId,t.slice(0,2),t)}async put(e,t){let r=new Bun.CryptoHasher("sha256").update(t).digest("hex"),n=this.path(e,r);if(await Bun.file(n).exists())return{hash:r,size:t.byteLength,added:!1};await Jy(Dj(n),{recursive:!0});let s=`${n}.${crypto.randomUUID()}.tmp`;return await Bun.write(s,t),await Qy(s,n),this.onAdded?.(e.userId,t.byteLength),{hash:r,size:t.byteLength,added:!0}}async remove(e,t){let r=Bun.file(this.path(e,t));if(!await r.exists())return;let n=r.size;await BT(this.path(e,t),{force:!0}),this.onAdded?.(e.userId,-n)}async get(e,t){let r=Bun.file(this.path(e,t));return await r.exists()?r:null}async moveUser(e,t){let r=Ro(this.root,e),n=Ro(this.root,t),s=await UT(r).catch(()=>null);if(!s)return;if(await Jy(this.root,{recursive:!0}),!await Qy(r,n).then(()=>!0,()=>!1)){for(let o of s){await Jy(Ro(n,o),{recursive:!0});for(let i of await UT(Ro(r,o)))await Qy(Ro(r,o,i),Ro(n,o,i))}await BT(r,{recursive:!0,force:!0})}}}var qT=()=>{};function od(e,t,r){let n=(a)=>a.map((c)=>c.type==="text"?{type:"text",text:c.text}:r?{type:"image_url",image_url:{url:jj(c)}}:{type:"text",text:"[a picture you cannot see]"}),s=[{role:"system",content:e}],o=[],i=()=>{if(o.length===0)return;s.push({role:"user",content:[{type:"text",text:"Previews of the results above:"},...n(o)]}),o=[]};for(let a of t){if(a.role!=="tool")i();if(a.role==="user")s.push({role:"user",content:n(a.content)});else if(a.role==="assistant")s.push({role:"assistant",content:a.text||null,...a.toolCalls.length>0&&{tool_calls:a.toolCalls.map((c)=>({id:c.id,type:"function",function:{name:c.name,arguments:JSON.stringify(c.arguments)}}))}});else if(s.push({role:"tool",tool_call_id:a.callId,content:Uj(a.content)||"(no text)"}),r)o.push(...a.content.filter((c)=>c.type==="image"))}return i(),s}function id(e){return e.map((t)=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}))}function ad(e){let t=e.choices?.[0]?.message;if(!t)throw Error("No answer came back");let r=(t.tool_calls??[]).flatMap((n,s)=>{let o=n.function?.name;if(!o)return[];return[{id:n.id||`call_${s}`,name:o,arguments:Bj(n.function?.arguments)}]});return{text:(t.content??"").trim(),toolCalls:r}}function Bj(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return{}}}var jj=(e)=>`data:${e.mimeType};base64,${e.data}`,Uj=(e)=>e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
|
|
61
|
+
`);function z(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,A))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(A in r&&r[A]===t[A])return!0;r=Object.getPrototypeOf(r)}return!1}var A;var ye=b(()=>{A=Symbol.for("drizzle:entityKind")});var Be;var $n=b(()=>{ye();Be=class Be{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[A]="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 Yy;var ew=b(()=>{ye();Yy=class Yy{static[A]="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 on;var cd=b(()=>{on=Symbol.for("drizzle:Name")});function FT(e,...t){return e(...t)}var VT=()=>{};function HT(e){return!!e&&typeof e==="function"&&ZT in e&&e[ZT]===!0}var ZT;var GT=b(()=>{ZT=Symbol.for("drizzle:isPgEnum")});var at,kc;var an=b(()=>{ye();at=class at{static[A]="Subquery";constructor(e,t,r,n=!1,s=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:n,usedTables:s}}};kc=class kc extends at{static[A]="WithSubquery"}});var KT="0.45.4";var WT=()=>{};var tw,rw,JT;var QT=b(()=>{VT();WT();JT={startActiveSpan(e,t){if(!tw)return t();if(!rw)rw=tw.trace.getTracer("drizzle-orm",KT);return FT((r,n)=>n.startActiveSpan(e,(s)=>{try{return t(s)}catch(o){throw s.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{s.end()}}),tw,rw)}}});var ct;var Wn=b(()=>{ct=Symbol.for("drizzle:ViewBaseConfig")});function Cs(e){return e[on]}function Co(e){return`${e[ld]??"public"}.${e[on]}`}var ld,ud,XT,nw,sw,Tc,YT,qj,U;var Jt=b(()=>{ye();cd();ld=Symbol.for("drizzle:Schema"),ud=Symbol.for("drizzle:Columns"),XT=Symbol.for("drizzle:ExtraConfigColumns"),nw=Symbol.for("drizzle:OriginalName"),sw=Symbol.for("drizzle:BaseName"),Tc=Symbol.for("drizzle:IsAlias"),YT=Symbol.for("drizzle:ExtraConfigBuilder"),qj=Symbol.for("drizzle:IsDrizzleTable");U=class U{static[A]="Table";static Symbol={Name:on,Schema:ld,OriginalName:nw,Columns:ud,ExtraConfigColumns:XT,BaseName:sw,IsAlias:Tc,ExtraConfigBuilder:YT};[on];[nw];[ld];[ud];[XT];[sw];[Tc]=!1;[qj]=!0;[YT]=void 0;constructor(e,t,r){this[on]=this[nw]=e,this[ld]=t,this[sw]=r}}});function ow(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Fj(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 eP(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function S(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Rt(e[0]));for(let[n,s]of t.entries())r.push(s,new Rt(e[n+1]));return new X(r)}function Pc(e,t){return e.map((r)=>{if(z(r,Os)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(z(r,Or)&&z(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 Rt,X,dd,tP,rP,ere,Or,Os,Vj,qr;var Vt=b(()=>{ye();GT();an();QT();Wn();$n();Jt();Rt=class Rt{static[A]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new X([this])}};X=class X{constructor(e){this.queryChunks=e;for(let t of e)if(z(t,U)){let r=t[U.Symbol.Schema];this.usedTables.push(r===void 0?t[U.Symbol.Name]:r+"."+t[U.Symbol.Name])}}static[A]="SQL";decoder=tP;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return JT.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:n,escapeName:s,escapeParam:o,prepareTyping:i,inlineParams:a,paramStartIndex:c}=r;return Fj(e.map((l)=>{if(z(l,Rt))return{sql:l.value.join(""),params:[]};if(z(l,dd))return{sql:s(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Rt("(")];for(let[d,p]of l.entries())if(u.push(p),d<l.length-1)u.push(new Rt(", "));return u.push(new Rt(")")),this.buildQueryFromSourceParams(u,r)}if(z(l,X))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(z(l,U)){let u=l[U.Symbol.Schema],d=l[U.Symbol.Name];return{sql:u===void 0||l[Tc]?s(d):s(u)+"."+s(d),params:[]}}if(z(l,Be)){let u=n.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:s(u),params:[]};let d=l.table[U.Symbol.Schema];return{sql:l.table[Tc]||d===void 0?s(l.table[U.Symbol.Name])+"."+s(u):s(d)+"."+s(l.table[U.Symbol.Name])+"."+s(u),params:[]}}if(z(l,qr)){let u=l[ct].schema,d=l[ct].name;return{sql:u===void 0||l[ct].isAlias?s(d):s(u)+"."+s(d),params:[]}}if(z(l,Or)){if(z(l.value,Os))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(z(u,X))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let d=["none"];if(i)d=[i(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:d}}if(z(l,Os))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(z(l,X.Aliased)&&l.fieldAlias!==void 0)return{sql:s(l.fieldAlias),params:[]};if(z(l,at)){if(l._.isWith)return{sql:s(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Rt("("),l._.sql,new Rt(") "),new dd(l._.alias)],r)}if(HT(l)){if(l.schema)return{sql:s(l.schema)+"."+s(l.enumName),params:[]};return{sql:s(l.enumName),params:[]}}if(ow(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Rt("("),l.getSQL(),new Rt(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new X.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}};dd=class dd{constructor(e){this.value=e}static[A]="Name";brand;getSQL(){return new X([this])}};tP={mapFromDriverValue:(e)=>e},rP={mapToDriverValue:(e)=>e},ere={...tP,...rP};Or=class Or{constructor(e,t=rP){this.value=e,this.encoder=t}static[A]="Param";brand;getSQL(){return new X([this])}};((e)=>{function t(){return new X([])}e.empty=t;function r(c){return new X(c)}e.fromList=r;function n(c){return new X([new Rt(c)])}e.raw=n;function s(c,l){let u=[];for(let[d,p]of c.entries()){if(d>0&&l!==void 0)u.push(l);u.push(p)}return new X(u)}e.join=s;function o(c){return new dd(c)}e.identifier=o;function i(c){return new Os(c)}e.placeholder=i;function a(c,l){return new Or(c,l)}e.param=a})(S||(S={}));((e)=>{class t{constructor(r,n){this.sql=r,this.fieldAlias=n}static[A]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(X||(X={}));Os=class Os{constructor(e){this.name=e}static[A]="Placeholder";getSQL(){return new X([this])}};Vj=Symbol.for("drizzle:IsDrizzleView");qr=class qr{static[A]="View";[ct];[Vj]=!0;constructor({name:e,schema:t,selectedFields:r,query:n}){this[ct]={name:e,originalName:e,schema:t,selectedFields:r,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new X([this])}};Be.prototype.getSQL=function(){return new X([this])};U.prototype.getSQL=function(){return new X([this])};at.prototype.getSQL=function(){return new X([this])}});function pd(e,t){return new Proxy(e,new Ec(t,!1))}function kn(e,t){return new Proxy(e,new bi(new Proxy(e.table,new Ec(t,!1))))}function iw(e,t){return new X.Aliased(Ic(e.sql,t),e.fieldAlias)}function Ic(e,t){return S.join(e.queryChunks.map((r)=>{if(z(r,Be))return kn(r,t);if(z(r,X))return Ic(r,t);if(z(r,X.Aliased))return iw(r,t);return r}))}var bi,Ec;var fd=b(()=>{$n();ye();Vt();Jt();Wn();bi=class bi{constructor(e){this.table=e}static[A]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Ec=class Ec{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[A]="TableAliasProxyHandler";get(e,t){if(t===U.Symbol.IsAlias)return!0;if(t===U.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===U.Symbol.OriginalName)return this.alias;if(t===ct)return{...e[ct],name:this.alias,isAlias:!0};if(t===U.Symbol.Columns){let n=e[U.Symbol.Columns];if(!n)return n;let s={};return Object.keys(n).map((o)=>{s[o]=new Proxy(n[o],new bi(new Proxy(e,this)))}),s}let r=e[t];if(z(r,Be))return new Proxy(r,new bi(new Proxy(e,this)));return r}}});var vi,Jn,aw;var md=b(()=>{ye();vi=class vi extends Error{static[A]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Jn=class Jn extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
62
|
+
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Jn),r)this.cause=r}};aw=class aw extends vi{static[A]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var nP,cw,lw;var hd=b(()=>{ye();nP=class nP{static[A]="ConsoleLogWriter";write(e){console.log(e)}};cw=class cw{static[A]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new nP}logQuery(e,t){let r=t.map((s)=>{try{return JSON.stringify(s)}catch{return String(s)}}),n=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${n}`)}};lw=class lw{static[A]="NoopLogger";logQuery(){}}});var ir;var Qn=b(()=>{ye();ir=class ir{static[A]="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)}}});function uw(e,t,r){let n={},s=e.reduce((o,{path:i,field:a},c)=>{let l;if(z(a,Be))l=a;else if(z(a,X))l=a.decoder;else if(z(a,at))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[d,p]of i.entries())if(d<i.length-1){if(!(p in u))u[p]={};u=u[p]}else{let f=t[c],m=u[p]=f===null?null:l.mapFromDriverValue(f);if(r&&z(a,Be)&&i.length===2){let h=i[0];if(!(h in n))n[h]=m===null?Cs(a.table):!1;else if(typeof n[h]==="string"&&n[h]!==Cs(a.table))n[h]=!1}}return o},{});if(r&&Object.keys(n).length>0){for(let[o,i]of Object.entries(n))if(typeof i==="string"&&!r[i])s[o]=null}return s}function Fr(e,t){return Object.entries(e).reduce((r,[n,s])=>{if(typeof n!=="string")return r;let o=t?[...t,n]:[n];if(z(s,Be)||z(s,X)||z(s,X.Aliased)||z(s,at))r.push({path:o,field:s});else if(z(s,U))r.push(...Fr(s[U.Symbol.Columns],o));else r.push(...Fr(s,o));return r},[])}function Ac(e,t){let r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(let[s,o]of r.entries())if(o!==n[s])return!1;return!0}function gd(e,t){let r=Object.entries(t).filter(([,n])=>n!==void 0).map(([n,s])=>{if(z(s,X)||z(s,Be))return[n,s];else return[n,new Or(s,e[U.Symbol.Columns][n])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function sP(e,t){for(let r of t)for(let n of Object.getOwnPropertyNames(r.prototype)){if(n==="constructor")continue;Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(r.prototype,n)||Object.create(null))}}function oP(e){return e[U.Symbol.Columns]}function Rc(e){return z(e,at)?e._.alias:z(e,qr)?e[ct].name:z(e,X)?void 0:e[U.Symbol.IsAlias]?e[U.Symbol.Name]:e[U.Symbol.BaseName]}function Tn(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function iP(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 dw;var wr=b(()=>{$n();ye();Vt();an();Jt();Wn();dw=typeof TextDecoder>"u"?null:new TextDecoder});var aP,cP,pw;var lP=b(()=>{ye();Jt();aP=Symbol.for("drizzle:PgInlineForeignKeys"),cP=Symbol.for("drizzle:EnableRLS");pw=class pw extends U{static[A]="PgTable";static Symbol=Object.assign({},U.Symbol,{InlineForeignKeys:aP,EnableRLS:cP});[aP]=[];[cP]=!1;[U.Symbol.ExtraConfigBuilder]=void 0;[U.Symbol.ExtraConfigColumns]={}}});var fw,uP;var dP=b(()=>{ye();lP();fw=class fw{static[A]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new uP(e,this.columns,this.name)}};uP=class uP{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[A]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[pw.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function br(e,t){if(eP(t)&&!ow(e)&&!z(e,Or)&&!z(e,Os)&&!z(e,Be)&&!z(e,U)&&!z(e,qr))return new Or(e,t);return e}function dt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new X(t);return new X([new Rt("("),S.join(t,new Rt(" and ")),new Rt(")")])}function wd(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new X(t);return new X([new Rt("("),S.join(t,new Rt(" or ")),new Rt(")")])}function pP(e){return S`not ${e}`}function _i(e,t){if(Array.isArray(t)){if(t.length===0)return S`false`;return S`${e} in ${t.map((r)=>br(r,e))}`}return S`${e} in ${br(t,e)}`}function bd(e,t){if(Array.isArray(t)){if(t.length===0)return S`true`;return S`${e} not in ${t.map((r)=>br(r,e))}`}return S`${e} not in ${br(t,e)}`}function vd(e){return S`${e} is null`}function hP(e){return S`${e} is not null`}function gP(e){return S`exists ${e}`}function yP(e){return S`not exists ${e}`}function wP(e,t,r){return S`${e} between ${br(t,e)} and ${br(r,e)}`}function bP(e,t,r){return S`${e} not between ${br(t,e)} and ${br(r,e)}`}function vP(e,t){return S`${e} like ${t}`}function _P(e,t){return S`${e} not like ${t}`}function xP(e,t){return S`${e} ilike ${t}`}function SP(e,t){return S`${e} not ilike ${t}`}var ae=(e,t)=>S`${e} = ${br(t,e)}`,yd=(e,t)=>S`${e} <> ${br(t,e)}`,fP=(e,t)=>S`${e} > ${br(t,e)}`,Cc=(e,t)=>S`${e} >= ${br(t,e)}`,Oc=(e,t)=>S`${e} < ${br(t,e)}`,mP=(e,t)=>S`${e} <= ${br(t,e)}`;var $P=b(()=>{$n();ye();Jt();Vt()});function _d(e){return S`${e} asc`}function xi(e){return S`${e} desc`}var kP=b(()=>{Vt()});var mw=b(()=>{$P();kP()});function PP(){return{and:dt,between:wP,eq:ae,exists:gP,gt:fP,gte:Cc,ilike:xP,inArray:_i,isNull:vd,isNotNull:hP,like:vP,lt:Oc,lte:mP,ne:yd,not:pP,notBetween:bP,notExists:yP,notLike:_P,notIlike:SP,notInArray:bd,or:wd,sql:S}}function EP(){return{sql:S,asc:_d,desc:xi}}function IP(e,t){if(Object.keys(e).length===1&&"default"in e&&!z(e.default,U))e=e.default;let r={},n={},s={};for(let[o,i]of Object.entries(e))if(z(i,U)){let a=Co(i),c=n[a];r[a]=o,s[o]={tsName:o,dbName:i[U.Symbol.Name],schema:i[U.Symbol.Schema],columns:i[U.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(i[U.Symbol.Columns]))if(u.primary)s[o].primaryKey.push(u);let l=i[U.Symbol.ExtraConfigBuilder]?.(i[U.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(z(u,fw))s[o].primaryKey.push(...u.columns)}}else if(z(i,TP)){let a=Co(i.table),c=r[a],l=i.config(t(i.table)),u;for(let[d,p]of Object.entries(l))if(c){let f=s[c];if(f.relations[d]=p,u)f.primaryKey.push(...u)}else{if(!(a in n))n[a]={relations:{},primaryKey:u};n[a].relations[d]=p}}return{tables:s,tableNamesMap:r}}function Zj(e){return function(r,n){return new zs(e,r,n,n?.fields.reduce((s,o)=>s&&o.notNull,!0)??!1)}}function Hj(e){return function(r,n){return new zc(e,r,n)}}function AP(e,t,r){if(z(r,zs)&&r.config)return{fields:r.config.fields,references:r.config.references};let n=t[Co(r.referencedTable)];if(!n)throw Error(`Table "${r.referencedTable[U.Symbol.Name]}" not found in schema`);let s=e[n];if(!s)throw Error(`Table "${n}" not found in schema`);let o=r.sourceTable,i=t[Co(o)];if(!i)throw Error(`Table "${o[U.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(s.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${n}"`):Error(`There are multiple relations between "${n}" and "${r.sourceTable[U.Symbol.Name]}". Please specify relation name`);if(a[0]&&z(a[0],zs)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${i}.${r.fieldName}"`)}function RP(e){return{one:Zj(e),many:Hj(e)}}function xd(e,t,r,n,s=(o)=>o){let o={};for(let[i,a]of n.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[i],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=z(c,zs)?u&&xd(e,e[a.relationTableTsKey],u,a.selection,s):u.map((d)=>xd(e,e[a.relationTableTsKey],d,a.selection,s))}else{let c=s(r[i]),l=a.field,u;if(z(l,Be))u=l;else if(z(l,X))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var hw,TP,zs,zc;var Mc=b(()=>{Jt();$n();ye();dP();mw();Vt();hw=class hw{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[U.Symbol.Name]}static[A]="Relation";referencedTableName;fieldName};TP=class TP{constructor(e,t){this.table=e,this.config=t}static[A]="Relations"};zs=class zs extends hw{constructor(e,t,r,n){super(e,t,r?.relationName);this.config=r,this.isNullable=n}static[A]="One";withFieldName(e){let t=new zs(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};zc=class zc extends hw{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[A]="Many";withFieldName(e){let t=new zc(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});var CP=()=>{};var OP=()=>{};var zP=b(()=>{CP();OP()});var gw=b(()=>{mw();zP();Vt()});var Sd=b(()=>{fd();ew();$n();ye();md();hd();Qn();Mc();gw();an();Jt();wr();Wn()});var $t;var Si=b(()=>{fd();$n();ye();Vt();an();Wn();$t=class $t{static[A]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ct)return{...e[ct],selectedFields:new Proxy(e[ct].selectedFields,this)};if(typeof t==="symbol")return e[t];let n=(z(e,at)?e._.selectedFields:z(e,qr)?e[ct].selectedFields:e)[t];if(z(n,X.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!n.isSelectionField)return n.sql;let s=n.clone();return s.isSelectionField=!0,s}if(z(n,X)){if(this.config.sqlBehavior==="sql")return n;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(z(n,Be)){if(this.config.alias)return new Proxy(n,new bi(new Proxy(n.table,new Ec(this.config.alias,this.config.replaceOriginalName??!1))));return n}if(typeof n!=="object"||n===null)return n;return new Proxy(n,new $t(this.config))}}});var yw,MP;var ww=b(()=>{ye();cd();yw=class yw{static[A]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:n,foreignColumns:s}=e();return{name:r,columns:n,foreignTable:s[0].table,foreignColumns:s}},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 MP(e,this)}};MP=class MP{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[A]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),n=t.map((i)=>i.name),s=r.map((i)=>i.name),o=[this.table[on],...n,r[0].table[on],...s];return e??`${o.join("_")}_fk`}}});function NP(e,t){return`${e[on]}_${t.join("_")}_unique`}var bw=b(()=>{cd()});var Dt,pt;var Ms=b(()=>{ew();$n();ye();ww();bw();Dt=class Dt extends Yy{static[A]="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:n})=>((s,o)=>{let i=new yw(()=>{let a=s();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)i.onUpdate(o.onUpdate);if(o.onDelete)i.onDelete(o.onDelete);return i.build(t)})(r,n))}};pt=class pt extends Be{constructor(e,t){if(!t.uniqueName)t.uniqueName=NP(e,[t.name]);super(e,t);this.table=e}static[A]="SQLiteColumn"}});function FP(e,t){let{name:r,config:n}=Tn(e,t);if(n?.mode==="json")return new jP(r);if(n?.mode==="bigint")return new LP(r);return new BP(r)}var LP,DP,jP,UP,BP,qP;var vw=b(()=>{ye();wr();Ms();LP=class LP extends Dt{static[A]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new DP(e,this.config)}};DP=class DP extends pt{static[A]="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(dw.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};jP=class jP extends Dt{static[A]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new UP(e,this.config)}};UP=class UP extends pt{static[A]="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(dw.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};BP=class BP extends Dt{static[A]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new qP(e,this.config)}};qP=class qP extends pt{static[A]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function HP(e){return(t,r)=>{let{name:n,config:s}=Tn(t,r);return new VP(n,s,e)}}var VP,ZP;var _w=b(()=>{ye();wr();Ms();VP=class VP extends Dt{static[A]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new ZP(e,this.config)}};ZP=class ZP extends pt{static[A]="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 ke(e,t){let{name:r,config:n}=Tn(e,t);if(n?.mode==="timestamp"||n?.mode==="timestamp_ms")return new WP(r,n.mode);if(n?.mode==="boolean")return new QP(r,n.mode);return new GP(r)}var $d,kd,GP,KP,WP,JP,QP,XP;var xw=b(()=>{ye();Vt();wr();Ms();$d=class $d extends Dt{static[A]="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()}};kd=class kd extends pt{static[A]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};GP=class GP extends $d{static[A]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new KP(e,this.config)}};KP=class KP extends kd{static[A]="SQLiteInteger"};WP=class WP extends $d{static[A]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(S`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new JP(e,this.config)}};JP=class JP extends kd{static[A]="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}};QP=class QP extends $d{static[A]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new XP(e,this.config)}};XP=class XP extends kd{static[A]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function oE(e,t){let{name:r,config:n}=Tn(e,t),s=n?.mode;return s==="number"?new tE(r):s==="bigint"?new nE(r):new YP(r)}var YP,eE,tE,rE,nE,sE;var Sw=b(()=>{ye();wr();Ms();YP=class YP extends Dt{static[A]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new eE(e,this.config)}};eE=class eE extends pt{static[A]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};tE=class tE extends Dt{static[A]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new rE(e,this.config)}};rE=class rE extends pt{static[A]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};nE=class nE extends Dt{static[A]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new sE(e,this.config)}};sE=class sE extends pt{static[A]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function Ns(e){return new iE(e??"")}var iE,aE;var $w=b(()=>{ye();Ms();iE=class iE extends Dt{static[A]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new aE(e,this.config)}};aE=class aE extends pt{static[A]="SQLiteReal";getSQLType(){return"real"}}});function Y(e,t={}){let{name:r,config:n}=Tn(e,t);if(n.mode==="json")return new uE(r);return new cE(r,n)}var cE,lE,uE,dE;var kw=b(()=>{ye();wr();Ms();cE=class cE extends Dt{static[A]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new lE(e,this.config)}};lE=class lE extends pt{static[A]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};uE=class uE extends Dt{static[A]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new dE(e,this.config)}};dE=class dE extends pt{static[A]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function pE(){return{blob:FP,customType:HP,integer:ke,numeric:oE,real:Ns,text:Y}}var fE=b(()=>{vw();_w();xw();Sw();$w();kw()});function Gj(e,t,r,n,s=e){let o=new jt(e,n,s),i=typeof t==="function"?t(pE()):t,a=Object.fromEntries(Object.entries(i).map(([l,u])=>{let d=u;d.setName(l);let p=d.build(o);return o[Tw].push(...d.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[U.Symbol.Columns]=a,c[U.Symbol.ExtraConfigColumns]=a,r)c[jt.Symbol.ExtraConfigBuilder]=r;return c}var Tw,jt,vr=(e,t,r)=>Gj(e,t,r);var Oo=b(()=>{ye();Jt();fE();Tw=Symbol.for("drizzle:SQLiteInlineForeignKeys");jt=class jt extends U{static[A]="SQLiteTable";static Symbol=Object.assign({},U.Symbol,{InlineForeignKeys:Tw});[U.Symbol.Columns];[Tw]=[];[U.Symbol.ExtraConfigBuilder]=void 0}});var mE=()=>{};function zr(e){return new Pw(e,!1)}function Ew(e){return new Pw(e,!0)}var Pw,hE,gE;var yE=b(()=>{ye();Pw=class Pw{constructor(e,t){this.name=e,this.unique=t}static[A]="SQLiteIndexBuilderOn";on(...e){return new hE(this.name,e,this.unique)}};hE=class hE{static[A]="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 gE(this.config,e)}};gE=class gE{static[A]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var wE=()=>{};function cn(e){if(z(e,jt))return[`${e[U.Symbol.BaseName]}`];if(z(e,at))return e._.usedTables??[];if(z(e,X))return e.usedTables??[];return[]}var $i=b(()=>{ye();Vt();an();Jt();Oo()});var Td;var bE=b(()=>{ye();Qn();Si();Oo();Jt();wr();$i();Td=class Td extends ir{constructor(e,t,r,n){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:n}}static[A]="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[U.Symbol.Columns],new $t({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[jt.Symbol.Columns]){return this.config.returning=Fr(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:cn(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 Kj(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Wj(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,n,s)=>{let o=s===0?n.toLowerCase():`${n[0].toUpperCase()}${n.slice(1)}`;return r+o},"")}function Jj(e){return e}var Iw;var vE=b(()=>{ye();Jt();Iw=class Iw{static[A]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Kj:e==="camelCase"?Wj:Jj}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[U.Symbol.Schema]??"public",r=e.table[U.Symbol.OriginalName],n=`${t}.${r}.${e.name}`;if(!this.cache[n])this.cacheTable(e.table);return this.cache[n]}cacheTable(e){let t=e[U.Symbol.Schema]??"public",r=e[U.Symbol.OriginalName],n=`${t}.${r}`;if(!this.cachedTables[n]){for(let s of Object.values(e[U.Symbol.Columns])){let o=`${n}.${s.name}`;this.cache[o]=this.convert(s.name)}this.cachedTables[n]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Aw=b(()=>{vw();Ms();_w();xw();Sw();$w();kw()});var zo;var Pd=b(()=>{ye();Vt();zo=class zo extends qr{static[A]="SQLiteViewBase"}});var Nc,Lc;var Ed=b(()=>{fd();vE();$n();ye();md();Mc();gw();Vt();Aw();Oo();an();Jt();wr();Wn();Pd();Nc=class Nc{static[A]="SQLiteDialect";casing;constructor(e){this.casing=new Iw(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=[S`with `];for(let[r,n]of e.entries())if(t.push(S`${S.identifier(n._.alias)} as (${n._.sql})`),r<e.length-1)t.push(S`, `);return t.push(S` `),S.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:n,limit:s,orderBy:o}){let i=this.buildWithCTE(n),a=r?S` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?S` where ${t}`:void 0,l=this.buildOrderBy(o),u=this.buildLimit(s);return S`${i}delete from ${e}${c}${a}${l}${u}`}buildUpdateSet(e,t){let r=e[U.Symbol.Columns],n=Object.keys(r).filter((o)=>t[o]!==void 0||r[o]?.onUpdateFn!==void 0),s=n.length;return S.join(n.flatMap((o,i)=>{let a=r[o],c=a.onUpdateFn?.(),l=t[o]??(z(c,X)?c:S.param(c,a)),u=S`${S.identifier(this.casing.getColumnCasing(a))} = ${l}`;if(i<s-1)return[u,S.raw(", ")];return[u]}))}buildUpdateQuery({table:e,set:t,where:r,returning:n,withList:s,joins:o,from:i,limit:a,orderBy:c}){let l=this.buildWithCTE(s),u=this.buildUpdateSet(e,t),d=i&&S.join([S.raw(" from "),this.buildFromTable(i)]),p=this.buildJoins(o),f=n?S` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,m=r?S` where ${r}`:void 0,h=this.buildOrderBy(c),g=this.buildLimit(a);return S`${l}update ${e} set ${u}${d}${p}${m}${f}${h}${g}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,n=e.flatMap(({field:s},o)=>{let i=[];if(z(s,X.Aliased)&&s.isSelectionField)i.push(S.identifier(s.fieldAlias));else if(z(s,X.Aliased)||z(s,X)){let a=z(s,X.Aliased)?s.sql:s;if(t)i.push(new X(a.queryChunks.map((c)=>{if(z(c,Be))return S.identifier(this.casing.getColumnCasing(c));return c})));else i.push(a);if(z(s,X.Aliased))i.push(S` as ${S.identifier(s.fieldAlias)}`)}else if(z(s,Be)){let a=s.table[U.Symbol.Name];if(s.columnType==="SQLiteNumericBigInt")if(t)i.push(S`cast(${S.identifier(this.casing.getColumnCasing(s))} as text)`);else i.push(S`cast(${S.identifier(a)}.${S.identifier(this.casing.getColumnCasing(s))} as text)`);else if(t)i.push(S.identifier(this.casing.getColumnCasing(s)));else i.push(S`${S.identifier(a)}.${S.identifier(this.casing.getColumnCasing(s))}`)}else if(z(s,at)){let a=Object.entries(s._.selectedFields);if(a.length===1){let c=a[0][1],l=z(c,X)?c.decoder:z(c,Be)?{mapFromDriverValue:(u)=>c.mapFromDriverValue(u)}:c.sql.decoder;if(l)s._.sql.decoder=l}i.push(s)}if(o<r-1)i.push(S`, `);return i});return S.join(n)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,n]of e.entries()){if(r===0)t.push(S` `);let s=n.table,o=n.on?S` on ${n.on}`:void 0;if(z(s,jt)){let i=s[jt.Symbol.Name],a=s[jt.Symbol.Schema],c=s[jt.Symbol.OriginalName],l=i===c?void 0:n.alias;t.push(S`${S.raw(n.joinType)} join ${a?S`${S.identifier(a)}.`:void 0}${S.identifier(c)}${l&&S` ${S.identifier(l)}`}${o}`)}else t.push(S`${S.raw(n.joinType)} join ${s}${o}`);if(r<e.length-1)t.push(S` `)}return S.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?S` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,n]of e.entries())if(t.push(n),r<e.length-1)t.push(S`, `)}return t.length>0?S` order by ${S.join(t)}`:void 0}buildFromTable(e){if(z(e,U)&&e[U.Symbol.IsAlias])return S`${S`${S.identifier(e[U.Symbol.Schema]??"")}.`.if(e[U.Symbol.Schema])}${S.identifier(e[U.Symbol.OriginalName])} ${S.identifier(e[U.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:n,having:s,table:o,joins:i,orderBy:a,groupBy:c,limit:l,offset:u,distinct:d,setOperators:p}){let f=r??Fr(t);for(let se of f)if(z(se.field,Be)&&Cs(se.field.table)!==(z(o,at)?o._.alias:z(o,zo)?o[ct].name:z(o,X)?void 0:Cs(o))&&!((we)=>i?.some(({alias:de})=>de===(we[U.Symbol.IsAlias]?Cs(we):we[U.Symbol.BaseName])))(se.field.table)){let we=Cs(se.field.table);throw Error(`Your "${se.path.join("->")}" field references a column "${we}"."${se.field.name}", but the table "${we}" is not part of the query! Did you forget to join it?`)}let m=!i||i.length===0,h=this.buildWithCTE(e),g=d?S` distinct`:void 0,w=this.buildSelection(f,{isSingleTable:m}),v=this.buildFromTable(o),_=this.buildJoins(i),C=n?S` where ${n}`:void 0,k=s?S` having ${s}`:void 0,P=[];if(c){for(let[se,we]of c.entries())if(P.push(we),se<c.length-1)P.push(S`, `)}let y=P.length>0?S` group by ${S.join(P)}`:void 0,x=this.buildOrderBy(a),T=this.buildLimit(l),I=u?S` offset ${u}`:void 0,j=S`${h}select${g} ${w} from ${v}${_}${C}${y}${k}${x}${T}${I}`;if(p.length>0)return this.buildSetOperations(j,p);return j}buildSetOperations(e,t){let[r,...n]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(n.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),n)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:n,limit:s,orderBy:o,offset:i}}){let a=S`${e.getSQL()} `,c=S`${n.getSQL()}`,l;if(o&&o.length>0){let f=[];for(let m of o)if(z(m,pt))f.push(S.identifier(m.name));else if(z(m,X)){for(let h=0;h<m.queryChunks.length;h++){let g=m.queryChunks[h];if(z(g,pt))m.queryChunks[h]=S.identifier(this.casing.getColumnCasing(g))}f.push(S`${m}`)}else f.push(S`${m}`);l=S` order by ${S.join(f,S`, `)}`}let u=typeof s==="object"||typeof s==="number"&&s>=0?S` limit ${s}`:void 0,d=S.raw(`${t} ${r?"all ":""}`),p=i?S` offset ${i}`:void 0;return S`${a}${d}${c}${l}${u}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:n,withList:s,select:o}){let i=[],a=e[U.Symbol.Columns],c=Object.entries(a).filter(([m,h])=>!h.shouldDisableInsert()),l=c.map(([,m])=>S.identifier(this.casing.getColumnCasing(m)));if(o){let m=t;if(z(m,X))i.push(m);else i.push(m.getSQL())}else{let m=t;i.push(S.raw("values "));for(let[h,g]of m.entries()){let w=[];for(let[v,_]of c){let C=g[v];if(C===void 0||z(C,Or)&&C.value===void 0){let k;if(_.default!==null&&_.default!==void 0)k=z(_.default,X)?_.default:S.param(_.default,_);else if(_.defaultFn!==void 0){let P=_.defaultFn();k=z(P,X)?P:S.param(P,_)}else if(!_.default&&_.onUpdateFn!==void 0){let P=_.onUpdateFn();k=z(P,X)?P:S.param(P,_)}else k=S`null`;w.push(k)}else w.push(C)}if(i.push(w),h<m.length-1)i.push(S`, `)}}let u=this.buildWithCTE(s),d=S.join(i),p=n?S` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,f=r?.length?S.join(r):void 0;return S`${u}insert into ${e} ${l} ${d}${f}${p}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:n,tableConfig:s,queryConfig:o,tableAlias:i,nestedQueryRelation:a,joinOn:c}){let l=[],u,d,p=[],f,m=[];if(o===!0)l=Object.entries(s.columns).map(([w,v])=>({dbKey:v.name,tsKey:w,field:kn(v,i),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let g=Object.fromEntries(Object.entries(s.columns).map(([P,y])=>[P,kn(y,i)]));if(o.where){let P=typeof o.where==="function"?o.where(g,PP()):o.where;f=P&&Ic(P,i)}let w=[],v=[];if(o.columns){let P=!1;for(let[y,x]of Object.entries(o.columns)){if(x===void 0)continue;if(y in s.columns){if(!P&&x===!0)P=!0;v.push(y)}}if(v.length>0)v=P?v.filter((y)=>o.columns?.[y]===!0):Object.keys(s.columns).filter((y)=>!v.includes(y))}else v=Object.keys(s.columns);for(let P of v){let y=s.columns[P];w.push({tsKey:P,value:y})}let _=[];if(o.with)_=Object.entries(o.with).filter((P)=>!!P[1]).map(([P,y])=>({tsKey:P,queryConfig:y,relation:s.relations[P]}));let C;if(o.extras){C=typeof o.extras==="function"?o.extras(g,{sql:S}):o.extras;for(let[P,y]of Object.entries(C))w.push({tsKey:P,value:iw(y,i)})}for(let{tsKey:P,value:y}of w)l.push({dbKey:z(y,X.Aliased)?y.fieldAlias:s.columns[P].name,tsKey:P,field:z(y,Be)?kn(y,i):y,relationTableTsKey:void 0,isJson:!1,selection:[]});let k=typeof o.orderBy==="function"?o.orderBy(g,EP()):o.orderBy??[];if(!Array.isArray(k))k=[k];p=k.map((P)=>{if(z(P,Be))return kn(P,i);return Ic(P,i)}),u=o.limit,d=o.offset;for(let{tsKey:P,queryConfig:y,relation:x}of _){let T=AP(t,r,x),I=Co(x.referencedTable),j=r[I],se=`${i}_${P}`,we=dt(...T.fields.map((Ye,Fe)=>ae(kn(T.references[Fe],se),kn(Ye,i)))),de=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:z(x,zs)?y===!0?{limit:1}:{...y,limit:1}:y,tableAlias:se,joinOn:we,nestedQueryRelation:x}),qe=S`(${de.sql})`.as(P);l.push({dbKey:P,tsKey:P,field:qe,relationTableTsKey:j,isJson:!0,selection:de.selection})}}if(l.length===0)throw new vi({message:`No fields selected for table "${s.tsName}" ("${i}"). 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 h;if(f=dt(c,f),a){let g=S`json_array(${S.join(l.map(({field:_})=>z(_,pt)?S.identifier(this.casing.getColumnCasing(_)):z(_,X.Aliased)?_.sql:_),S`, `)})`;if(z(a,zc))g=S`coalesce(json_group_array(${g}), json_array())`;let w=[{dbKey:"data",tsKey:"data",field:g.as("data"),isJson:!0,relationTableTsKey:s.tsName,selection:l}];if(u!==void 0||d!==void 0||p.length>0)h=this.buildSelectQuery({table:pd(n,i),fields:{},fieldsFlat:[{path:[],field:S.raw("*")}],where:f,limit:u,offset:d,orderBy:p,setOperators:[]}),f=void 0,u=void 0,d=void 0,p=void 0;else h=pd(n,i);h=this.buildSelectQuery({table:z(h,jt)?h:new at(h,{},i),fields:{},fieldsFlat:w.map(({field:_})=>({path:[],field:z(_,Be)?kn(_,i):_})),joins:m,where:f,limit:u,offset:d,orderBy:p,setOperators:[]})}else h=this.buildSelectQuery({table:pd(n,i),fields:{},fieldsFlat:l.map(({field:g})=>({path:[],field:z(g,Be)?kn(g,i):g})),joins:m,where:f,limit:u,offset:d,orderBy:p,setOperators:[]});return{tableTsKey:s.tsName,sql:h,selection:l}}};Lc=class Lc extends Nc{static[A]="SQLiteSyncDialect";migrate(e,t,r){let n=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",s=S`
|
|
63
|
+
CREATE TABLE IF NOT EXISTS ${S.identifier(n)} (
|
|
64
|
+
id SERIAL PRIMARY KEY,
|
|
65
|
+
hash text NOT NULL,
|
|
66
|
+
created_at numeric
|
|
67
|
+
)
|
|
68
|
+
`;t.run(s);let i=t.values(S`SELECT id, hash, created_at FROM ${S.identifier(n)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;t.run(S`BEGIN`);try{for(let a of e)if(!i||Number(i[2])<a.folderMillis){for(let c of a.sql)t.run(S.raw(c));t.run(S`INSERT INTO ${S.identifier(n)} ("hash", "created_at") VALUES(${a.hash}, ${a.folderMillis})`)}t.run(S`COMMIT`)}catch(a){throw t.run(S`ROLLBACK`),a}}}});var Rw;var _E=b(()=>{ye();Rw=class Rw{static[A]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Id(e,t){return(r,n,...s)=>{let o=[n,...s].map((i)=>({type:e,isAll:t,rightSelect:i}));for(let i of o)if(!Ac(r.getSelectedFields(),i.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(o)}}var ln,xE,Cw,Qj=()=>({union:Xj,unionAll:Yj,intersect:eU,except:tU}),Xj,Yj,eU,tU;var Ow=b(()=>{ye();_E();Qn();Si();Vt();an();Jt();wr();Wn();$i();Pd();ln=class ln{static[A]="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(z(e,at))r=Object.fromEntries(Object.keys(e._.selectedFields).map((n)=>[n,e[n]]));else if(z(e,zo))r=e[ct].selectedFields;else if(z(e,X))r={};else r=oP(e);return new Cw({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};xE=class xE extends Rw{static[A]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:n,dialect:s,withList:o,distinct:i}){super();this.config={withList:o,table:e,fields:{...t},distinct:i,setOperators:[]},this.isPartialSelect=r,this.session=n,this.dialect=s,this._={selectedFields:t,config:this.config},this.tableName=Rc(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of cn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let n=this.tableName,s=Rc(t);for(let o of cn(t))this.usedTables.add(o);if(typeof s==="string"&&this.config.joins?.some((o)=>o.alias===s))throw Error(`Alias "${s}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof n==="string")this.config.fields={[n]:this.config.fields};if(typeof s==="string"&&!z(t,X)){let o=z(t,at)?t._.selectedFields:z(t,qr)?t[ct].selectedFields:t[U.Symbol.Columns];this.config.fields[s]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new $t({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:s}),typeof s==="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([o])=>[o,!1])),this.joinsNotNullableMap[s]=!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 n=typeof r==="function"?r(Qj()):r;if(!Ac(this.getSelectedFields(),n.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:n}),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 $t({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new $t({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 $t({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 $t({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(...cn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...cn(r.table));return new Proxy(new at(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new $t({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new $t({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};Cw=class Cw extends xE{static[A]="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=Fr(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()}};sP(Cw,[ir]);Xj=Id("union",!1),Yj=Id("union",!0),eU=Id("intersect",!1),tU=Id("except",!1)});var Dc;var zw=b(()=>{ye();Si();Ed();an();Ow();Dc=class Dc{static[A]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=z(e,Nc)?e:void 0,this.dialectConfig=z(e,Nc)?void 0:e}$with=(e,t)=>{let r=this;return{as:(s)=>{if(typeof s==="function")s=s(r);return new Proxy(new kc(s.getSQL(),t??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),e,!0),new $t({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(s){return new ln({fields:s??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function n(s){return new ln({fields:s??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:n}}select(e){return new ln({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new ln({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new Lc(this.dialectConfig);return this.dialect}}});var Ad,Mw;var SE=b(()=>{ye();Qn();Vt();Oo();Jt();wr();$i();zw();Ad=class Ad{constructor(e,t,r,n){this.table=e,this.session=t,this.dialect=r,this.withList=n}static[A]="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 n={},s=this.table[U.Symbol.Columns];for(let o of Object.keys(r)){let i=r[o];n[o]=z(i,X)?i:new Or(i,s[o])}return n});return new Mw(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Dc):e;if(!z(t,X)&&!Ac(this.table[ud],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 Mw(this.table,t,this.session,this.dialect,this.withList,!0)}};Mw=class Mw extends ir{constructor(e,t,r,n,s,o){super();this.session=r,this.dialect=n,this.config={table:e,values:t,withList:s,select:o}}static[A]="SQLiteInsert";config;returning(e=this.config.table[jt.Symbol.Columns]){return this.config.returning=Fr(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(S` on conflict do nothing`);else{let t=Array.isArray(e.target)?S`${e.target}`:S`${[e.target]}`,r=e.where?S` where ${e.where}`:S``;this.config.onConflict.push(S` 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?S` where ${e.where}`:void 0,r=e.targetWhere?S` where ${e.targetWhere}`:void 0,n=e.setWhere?S` where ${e.setWhere}`:void 0,s=Array.isArray(e.target)?S`${e.target}`:S`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,gd(this.config.table,e.set));return this.config.onConflict.push(S` on conflict ${s}${r} do update set ${o}${t}${n}`),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:cn(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 Rd,$E;var kE=b(()=>{ye();Qn();Si();Oo();an();Jt();wr();Wn();$i();Pd();Rd=class Rd{constructor(e,t,r,n){this.table=e,this.session=t,this.dialect=r,this.withList=n}static[A]="SQLiteUpdateBuilder";set(e){return new $E(this.table,gd(this.table,e),this.session,this.dialect,this.withList)}};$E=class $E extends ir{constructor(e,t,r,n,s){super();this.session=r,this.dialect=n,this.config={set:t,table:e,withList:s,joins:[]}}static[A]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let n=Rc(t);if(typeof n==="string"&&this.config.joins.some((s)=>s.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(typeof r==="function"){let s=this.config.from?z(t,jt)?t[U.Symbol.Columns]:z(t,at)?t._.selectedFields:z(t,zo)?t[ct].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[U.Symbol.Columns],new $t({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),s&&new Proxy(s,new $t({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:n}),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[U.Symbol.Columns],new $t({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[jt.Symbol.Columns]){return this.config.returning=Fr(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:cn(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 Nw=b(()=>{bE();SE();zw();Ow();kE()});var jc;var TE=b(()=>{ye();Vt();jc=class jc extends X{constructor(e){super(jc.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=jc.buildCount(e.source,e.filters)}sql;static[A]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return S`(select count(*) from ${e}${S.raw(" where ").if(t)}${t})`}static buildCount(e,t){return S`select count(*) from ${e}${S.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 Dw,Cd,Lw;var PE=b(()=>{ye();Qn();Mc();Dw=class Dw{constructor(e,t,r,n,s,o,i,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=n,this.table=s,this.tableConfig=o,this.dialect=i,this.session=a}static[A]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new Lw(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new Cd(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new Lw(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new Cd(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};Cd=class Cd extends ir{constructor(e,t,r,n,s,o,i,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=n,this.tableConfig=s,this.dialect=o,this.session=i,this.config=a,this.mode=c}static[A]="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,(n,s)=>{let o=n.map((i)=>xd(this.schema,this.tableConfig,i,t.selection,s));if(this.mode==="first")return o[0];return o})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};Lw=class Lw extends Cd{static[A]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var ki;var EE=b(()=>{ye();Qn();ki=class ki extends ir{constructor(e,t,r,n,s){super();this.execute=e,this.getSQL=t,this.dialect=n,this.mapBatchResult=s,this.config={action:r}}static[A]="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 Uc;var Od=b(()=>{ye();Si();Vt();Nw();an();TE();PE();EE();Uc=class Uc{constructor(e,t,r,n){this.resultKind=e,this.dialect=t,this.session=r,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let s=this.query;if(this._.schema)for(let[o,i]of Object.entries(this._.schema))s[o]=new Dw(e,n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[o],i,t,r);this.$cache={invalidate:async(o)=>{}}}static[A]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(s)=>{if(typeof s==="function")s=s(new Dc(r.dialect));return new Proxy(new kc(s.getSQL(),t??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),e,!0),new $t({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new jc({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new ln({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function n(a){return new ln({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function s(a){return new Rd(a,t.session,t.dialect,e)}function o(a){return new Ad(a,t.session,t.dialect,e)}function i(a){return new Td(a,t.session,t.dialect,e)}return{select:r,selectDistinct:n,update:s,insert:o,delete:i}}select(e){return new ln({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new ln({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new Rd(e,this.session,this.dialect)}$cache;insert(e){return new Ad(e,this.session,this.dialect)}delete(e){return new Td(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?S.raw(e):e.getSQL();if(this.resultKind==="async")return new ki(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"?S.raw(e):e.getSQL();if(this.resultKind==="async")return new ki(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"?S.raw(e):e.getSQL();if(this.resultKind==="async")return new ki(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"?S.raw(e):e.getSQL();if(this.resultKind==="async")return new ki(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)}}});var IE=()=>{};async function Uw(e,t){let r=`${e}-${JSON.stringify(t)}`,s=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",s);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var AE,jw;var RE=b(()=>{ye();AE=class AE{static[A]="Cache"};jw=class jw extends AE{strategy(){return"all"}static[A]="NoopCache";async get(e){return}async put(e,t,r,n){}async onMutate(e){}}});var CE,Bw,qw,Fw;var Vw=b(()=>{RE();ye();md();Qn();Od();CE=class CE extends ir{constructor(e){super();this.resultCb=e}static[A]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};Bw=class Bw{constructor(e,t,r,n,s,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=n,this.queryMetadata=s,this.cacheConfig=o,n&&n.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[A]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||z(this.cache,jw)||this.queryMetadata===void 0)try{return await r()}catch(n){throw new Jn(e,t,n)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(n){throw new Jn(e,t,n)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[n]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return n}catch(n){throw new Jn(e,t,n)}if(!this.cacheConfig)try{return await r()}catch(n){throw new Jn(e,t,n)}if(this.queryMetadata.type==="select"){let n=await this.cache.get(this.cacheConfig.tag??await Uw(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(n===void 0){let s;try{s=await r()}catch(o){throw new Jn(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await Uw(e,t),s,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),s}return n}try{return await r()}catch(n){throw new Jn(e,t,n)}}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 CE(()=>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)}}};qw=class qw{constructor(e){this.dialect=e}static[A]="SQLiteSession";prepareOneTimeQuery(e,t,r,n,s,o,i){return this.prepareQuery(e,t,r,n,s,o,i)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new vi({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")}};Fw=class Fw extends Uc{constructor(e,t,r,n,s=0){super(e,t,r,n);this.schema=n,this.nestedIndex=s}static[A]="SQLiteTransaction";rollback(){throw new aw}}});var OE=()=>{};var Zw=b(()=>{IE();mE();Aw();Od();Ed();ww();yE();wE();Nw();Vw();Oo();bw();$i();OE()});var Hw,Gw,zE;var Kw=b(()=>{ye();hd();Vt();Zw();Vw();wr();Hw=class Hw extends qw{constructor(e,t,r,n={}){super(t);this.client=e,this.schema=r,this.logger=n.logger??new lw}static[A]="SQLiteBunSession";logger;exec(e){this.client.exec(e)}prepareQuery(e,t,r,n,s){let o=this.client.prepare(e.sql);return new zE(o,e,this.logger,t,r,n,s)}transaction(e,t={}){let r=new Gw("sync",this.dialect,this,this.schema),n;return this.client.transaction(()=>{n=e(r)})[t.behavior??"deferred"](),n}};Gw=class Gw extends Fw{static[A]="SQLiteBunTransaction";transaction(e){let t=`sp${this.nestedIndex}`,r=new Gw("sync",this.dialect,this.session,this.schema,this.nestedIndex+1);this.session.run(S.raw(`savepoint ${t}`));try{let n=e(r);return this.session.run(S.raw(`release savepoint ${t}`)),n}catch(n){throw this.session.run(S.raw(`rollback to savepoint ${t}`)),n}}};zE=class zE extends Bw{constructor(e,t,r,n,s,o,i){super("sync",s,t);this.stmt=e,this.logger=r,this.fields=n,this._isResponseInArrayMode=o,this.customResultMapper=i}static[A]="SQLiteBunPreparedQuery";run(e){let t=Pc(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),this.stmt.run(...t)}all(e){let{fields:t,query:r,logger:n,joinsNotNullableMap:s,stmt:o,customResultMapper:i}=this;if(!t&&!i){let c=Pc(r.params,e??{});return n.logQuery(r.sql,c),o.all(...c)}let a=this.values(e);if(i)return i(a);return a.map((c)=>uw(t,c,s))}get(e){let t=Pc(this.query.params,e??{});this.logger.logQuery(this.query.sql,t);let r=this.stmt.values(...t)[0];if(!r)return;let{fields:n,joinsNotNullableMap:s,customResultMapper:o}=this;if(!n&&!o)return r;if(o)return o([r]);return uw(n,r,s)}values(e){let t=Pc(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),this.stmt.values(...t)}isResponseInArrayMode(){return this._isResponseInArrayMode}}});import{Database as zd}from"bun:sqlite";function Ti(e,t={}){let r=new Lc({casing:t.casing}),n;if(t.logger===!0)n=new cw;else if(t.logger!==!1)n=t.logger;let s;if(t.schema){let a=IP(t.schema,RP);s={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new Hw(e,r,s,{logger:n}),i=new ME("sync",r,o,s);return i.$client=e,i}function Pi(...e){if(e[0]===void 0||typeof e[0]==="string"){let t=e[0]===void 0?new zd:new zd(e[0]);return Ti(t,e[1])}if(iP(e[0])){let{connection:t,client:r,...n}=e[0];if(r)return Ti(r,n);if(typeof t==="object"){let{source:o,...i}=t,a=Object.values(i).filter((l)=>l!==void 0).length?i:void 0,c=new zd(o,a);return Ti(c,n)}let s=new zd(t);return Ti(s,n)}return Ti(e[0],e[1])}var ME;var NE=b(()=>{ye();hd();Mc();Od();Ed();wr();Kw();ME=class ME extends Uc{static[A]="BunSQLiteDatabase"};((e)=>{function t(r){return Ti({},r)}e.mock=t})(Pi||(Pi={}))});var Ww=b(()=>{NE();Kw()});var Ii={};j6(Ii,{apiTokens:()=>xr,assetUsage:()=>Ei,assets:()=>Tt,authSessions:()=>_r,invites:()=>Xn,jobs:()=>Zt,loraUploads:()=>Ls,messages:()=>un,passwordResets:()=>Mo,sessions:()=>kt,spending:()=>Ct,turns:()=>Pn,users:()=>rt});var kt,Pn,Zt,Tt,un,rt,_r,Xn,xr,Ct,Mo,Ls,Ei;var Jw=b(()=>{Sd();Zw();kt=vr("sessions",{id:Y("id").primaryKey(),userId:Y("user_id").notNull(),title:Y("title").notNull(),createdAt:ke("created_at").notNull(),updatedAt:ke("updated_at").notNull()},(e)=>[zr("sessions_user_updated").on(e.userId,e.updatedAt)]),Pn=vr("turns",{id:Y("id").primaryKey(),sessionId:Y("session_id").notNull().references(()=>kt.id,{onDelete:"cascade"}),userId:Y("user_id").notNull(),prompt:Y("prompt").notNull(),referenceAssetIds:Y("reference_asset_ids",{mode:"json"}).$type().notNull(),createdAt:ke("created_at").notNull()},(e)=>[zr("turns_session_created").on(e.sessionId,e.createdAt)]),Zt=vr("jobs",{id:Y("id").primaryKey(),turnId:Y("turn_id").notNull().references(()=>Pn.id,{onDelete:"cascade"}),position:ke("position").notNull(),userId:Y("user_id").notNull(),providerId:Y("provider_id").notNull(),modelId:Y("model_id").notNull(),params:Y("params",{mode:"json"}).$type().notNull(),status:Y("status").$type().notNull(),handle:Y("handle",{mode:"json"}).$type(),error:Y("error"),errorCode:Y("error_code"),errorParams:Y("error_params",{mode:"json"}).$type(),costUsd:Ns("cost_usd"),createdAt:ke("created_at").notNull(),startedAt:ke("started_at"),finishedAt:ke("finished_at"),tokenId:Y("token_id")},(e)=>[zr("jobs_turn").on(e.turnId),zr("jobs_status").on(e.status)]),Tt=vr("assets",{id:Y("id").primaryKey(),userId:Y("user_id").notNull(),jobId:Y("job_id").references(()=>Zt.id,{onDelete:"set null"}),kind:Y("kind").$type().notNull(),hash:Y("hash").notNull(),mime:Y("mime").notNull(),size:ke("size").notNull(),prompt:Y("prompt"),modelId:Y("model_id"),params:Y("params",{mode:"json"}).$type(),createdAt:ke("created_at").notNull()},(e)=>[zr("assets_user_kind_created").on(e.userId,e.kind,e.createdAt),zr("assets_job").on(e.jobId)]),un=vr("messages",{id:Y("id").primaryKey(),sessionId:Y("session_id").notNull().references(()=>kt.id,{onDelete:"cascade"}),userId:Y("user_id").notNull(),body:Y("body",{mode:"json"}).$type().notNull(),createdAt:ke("created_at").notNull()},(e)=>[zr("messages_session_created").on(e.sessionId,e.createdAt)]),rt=vr("users",{id:Y("id").primaryKey(),username:Y("username").notNull(),displayName:Y("display_name").notNull(),passwordHash:Y("password_hash").notNull(),role:Y("role").$type().notNull(),canUsePaid:ke("can_use_paid",{mode:"boolean"}).notNull(),canTrain:ke("can_train",{mode:"boolean"}).notNull(),monthlyLimitUsd:Ns("monthly_limit_usd"),totpSecret:Y("totp_secret"),totpLastCounter:ke("totp_last_counter"),mustChangePassword:ke("must_change_password",{mode:"boolean"}).notNull().default(!1),disabledAt:ke("disabled_at"),createdAt:ke("created_at").notNull()},(e)=>[Ew("users_username").on(S`lower(${e.username})`)]),_r=vr("auth_sessions",{id:Y("id").primaryKey(),userId:Y("user_id").notNull().references(()=>rt.id,{onDelete:"cascade"}),createdAt:ke("created_at").notNull(),lastSeenAt:ke("last_seen_at").notNull(),expiresAt:ke("expires_at").notNull(),userAgent:Y("user_agent"),ip:Y("ip")},(e)=>[zr("auth_sessions_user").on(e.userId)]),Xn=vr("invites",{id:Y("id").primaryKey(),role:Y("role").$type().notNull(),canUsePaid:ke("can_use_paid",{mode:"boolean"}).notNull(),canTrain:ke("can_train",{mode:"boolean"}).notNull(),monthlyLimitUsd:Ns("monthly_limit_usd"),expiresAt:ke("expires_at").notNull(),createdBy:Y("created_by").notNull().references(()=>rt.id,{onDelete:"cascade"}),createdAt:ke("created_at").notNull(),usedBy:Y("used_by").references(()=>rt.id,{onDelete:"set null"}),usedAt:ke("used_at")}),xr=vr("api_tokens",{id:Y("id").primaryKey(),ref:Y("ref"),userId:Y("user_id").notNull().references(()=>rt.id,{onDelete:"cascade"}),name:Y("name").notNull(),scopes:Y("scopes",{mode:"json"}).$type().notNull(),spendLimitUsd:Ns("spend_limit_usd"),createdAt:ke("created_at").notNull(),lastUsedAt:ke("last_used_at"),expiresAt:ke("expires_at")},(e)=>[zr("api_tokens_user").on(e.userId),Ew("api_tokens_ref").on(e.ref)]),Ct=vr("spending",{id:Y("id").primaryKey(),userId:Y("user_id").notNull(),kind:Y("kind").$type().notNull(),jobId:Y("job_id"),tokenId:Y("token_id"),pending:ke("pending",{mode:"boolean"}).notNull().default(!1),keySource:Y("key_source").$type().notNull().default("server"),costUsd:Ns("cost_usd").notNull(),createdAt:ke("created_at").notNull()},(e)=>[zr("spending_user_created").on(e.userId,e.createdAt),zr("spending_token").on(e.tokenId)]),Mo=vr("password_resets",{id:Y("id").primaryKey(),userId:Y("user_id").notNull().references(()=>rt.id,{onDelete:"cascade"}),createdBy:Y("created_by").notNull().references(()=>rt.id,{onDelete:"cascade"}),createdAt:ke("created_at").notNull(),expiresAt:ke("expires_at").notNull(),usedAt:ke("used_at"),noticedAt:ke("noticed_at")}),Ls=vr("lora_uploads",{loraId:Y("lora_id").primaryKey(),userId:Y("user_id").notNull(),sizeBytes:ke("size_bytes").notNull(),createdAt:ke("created_at").notNull()},(e)=>[zr("lora_uploads_user").on(e.userId)]),Ei=vr("asset_usage",{userId:Y("user_id").primaryKey(),bytes:ke("bytes").notNull()})});class Qw{sqlite;db;constructor(e){this.sqlite=e;this.db=Pi(e,{schema:Ii})}countUsers(){return this.db.select({n:S`count(*)`}).from(rt).get()?.n??0}countActiveOwners(){return this.db.select({n:S`count(*)`}).from(rt).where(dt(ae(rt.role,"owner"),vd(rt.disabledAt))).get()?.n??0}createUser(e){this.db.insert(rt).values(e).run()}getUser(e){return this.db.select().from(rt).where(ae(rt.id,e)).get()??null}findUser(e){return this.db.select().from(rt).where(S`lower(${rt.username}) = lower(${e})`).get()??null}listUsers(){return this.db.select().from(rt).orderBy(_d(rt.createdAt)).all()}updateUser(e,t){this.db.update(rt).set(t).where(ae(rt.id,e)).run()}createSession(e){this.db.insert(_r).values(e).run()}getSession(e){return this.db.select().from(_r).where(ae(_r.id,e)).get()??null}touchSession(e,t,r){this.db.update(_r).set({lastSeenAt:t,expiresAt:r}).where(ae(_r.id,e)).run()}listSessions(e,t){return this.db.select().from(_r).where(dt(ae(_r.userId,e),Cc(_r.expiresAt,t))).orderBy(S`${_r.lastSeenAt} desc`).all()}deleteSession(e,t){return this.sqlite.prepare("delete from auth_sessions where id = ? and user_id = ?").run(t,e).changes>0}deleteSessionsOf(e,t){this.db.delete(_r).where(dt(ae(_r.userId,e),t?yd(_r.id,t):void 0)).run()}createInvite(e){this.db.insert(Xn).values(e).run()}getInvite(e){return this.db.select().from(Xn).where(ae(Xn.id,e)).get()??null}listInvites(){return this.db.select().from(Xn).orderBy(S`${Xn.createdAt} desc`).all()}deleteInvite(e){return this.sqlite.prepare("delete from invites where id = ?").run(e).changes>0}acceptInvite(e,t){return this.sqlite.transaction(()=>{if(this.sqlite.prepare("update invites set used_at = ? where id = ? and used_at is null").run(t.createdAt,e).changes===0)return!1;return this.db.insert(rt).values(t).run(),this.db.update(Xn).set({usedBy:t.id}).where(ae(Xn.id,e)).run(),!0})()}advanceTotpCounter(e,t){return this.sqlite.prepare("update users set totp_last_counter = ? where id = ? and (totp_last_counter is null or totp_last_counter < ?)").run(t,e,t).changes>0}deleteTokensOf(e){this.db.delete(xr).where(ae(xr.userId,e)).run()}createPasswordReset(e){this.db.insert(Mo).values(e).run()}getPasswordReset(e){return this.db.select().from(Mo).where(ae(Mo.id,e)).get()??null}expireUnusedResets(e,t){this.sqlite.prepare("update password_resets set expires_at = ? where user_id = ? and used_at is null and expires_at > ?").run(t-1,e,t)}lastUsedReset(e){return this.sqlite.prepare(`select r.id as id, coalesce(u.display_name, '') as by, r.used_at as at, r.noticed_at as noticedAt
|
|
69
|
+
from password_resets r left join users u on u.id = r.created_by
|
|
70
|
+
where r.user_id = ? and r.used_at is not null
|
|
71
|
+
order by r.used_at desc limit 1`).get(e)??null}markResetNoticed(e,t){this.db.update(Mo).set({noticedAt:t}).where(ae(Mo.id,e)).run()}usePasswordReset(e,t){return this.sqlite.prepare("update password_resets set used_at = ? where id = ? and used_at is null").run(t,e).changes>0}createToken(e){this.db.insert(xr).values(e).run()}getToken(e){return this.db.select().from(xr).where(ae(xr.id,e)).get()??null}listTokensOf(e){return this.db.select().from(xr).where(ae(xr.userId,e)).orderBy(S`${xr.createdAt} desc, rowid desc`).all()}deleteToken(e,t){return this.sqlite.prepare("delete from api_tokens where user_id = ? and ref = ?").run(e,t).changes>0}getTokenByRef(e){return this.db.select().from(xr).where(ae(xr.ref,e)).get()??null}spentByToken(e){return this.db.select({total:S`coalesce(sum(${Ct.costUsd}), 0)`}).from(Ct).where(ae(Ct.tokenId,e)).get()?.total??0}touchToken(e,t){this.db.update(xr).set({lastUsedAt:t}).where(ae(xr.id,e)).run()}createFirstOwner(e){return this.db.transaction((t)=>{if((t.select({n:S`count(*)`}).from(rt).get()?.n??0)>0)return!1;t.insert(rt).values(e).run();for(let n of[kt,Pn,Zt,Tt,un,Ei])t.update(n).set({userId:e.id}).where(ae(n.userId,As.userId)).run();return!0})}recordLoraUpload(e){this.db.insert(Ls).values(e).onConflictDoUpdate({target:Ls.loraId,set:e}).run()}loraUploadsOf(e){return this.db.select().from(Ls).where(ae(Ls.userId,e)).all()}forgetLoraUpload(e){this.db.delete(Ls).where(ae(Ls.loraId,e)).run()}addAssetBytes(e,t){this.sqlite.prepare("insert into asset_usage (user_id, bytes) values (?, max(?, 0)) on conflict(user_id) do update set bytes = max(bytes + ?, 0)").run(e,t,t)}assetBytes(e){return this.db.select({bytes:Ei.bytes}).from(Ei).where(ae(Ei.userId,e)).get()?.bytes??0}spentSince(e,t){return this.db.select({total:S`coalesce(sum(${Ct.costUsd}), 0)`}).from(Ct).where(dt(ae(Ct.userId,e),ae(Ct.keySource,"server"),Cc(Ct.createdAt,t))).get()?.total??0}}var Xw=b(()=>{Sd();Ww();Br();Jw()});import rU from"crypto";import Yw from"fs";function LE(e){let t=e.migrationsFolder,r=[],n=`${t}/meta/_journal.json`;if(!Yw.existsSync(n))throw Error("Can't find meta/_journal.json file");let s=Yw.readFileSync(`${t}/meta/_journal.json`).toString(),o=JSON.parse(s);for(let i of o.entries){let a=`${t}/${i.tag}.sql`;try{let c=Yw.readFileSync(`${t}/${i.tag}.sql`).toString(),l=c.split("--> statement-breakpoint").map((u)=>u);r.push({sql:l,bps:i.breakpoints,folderMillis:i.when,hash:rU.createHash("sha256").update(c).digest("hex")})}catch{throw Error(`No file ${a} found in ${t} folder`)}}return r}var DE=()=>{};function jE(e,t){let r=LE(t);e.dialect.migrate(r,e.session,t)}var UE=b(()=>{DE()});import{Database as nU}from"bun:sqlite";import{join as sU}from"path";class Bc{sqlite;db;constructor(e,t=oU){this.sqlite=new nU(e,{create:!0}),this.sqlite.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;"),this.db=Pi(this.sqlite,{schema:Ii}),jE(this.db,{migrationsFolder:t})}close(){this.sqlite.close()}accounts(){return new Qw(this.sqlite)}async createSession(e){this.db.insert(kt).values(e).run()}async listSessions(e){return this.db.select().from(kt).where(ae(kt.userId,e.userId)).orderBy(xi(kt.updatedAt)).all()}async getSession(e,t){return this.db.select().from(kt).where(dt(ae(kt.id,t),ae(kt.userId,e.userId))).get()??null}async deleteSession(e,t){this.db.delete(kt).where(dt(ae(kt.id,t),ae(kt.userId,e.userId))).run()}async createTurn(e,t){this.db.transaction((r)=>{if(r.insert(Pn).values(e).run(),t.length>0)r.insert(Zt).values(t).run();r.update(kt).set({updatedAt:e.createdAt}).where(ae(kt.id,e.sessionId)).run()})}async addEntry(e,t){let{id:r,sessionId:n,createdAt:s,...o}=e;this.db.transaction((i)=>{i.insert(un).values({id:r,sessionId:n,userId:t,body:o,createdAt:s}).run(),i.update(kt).set({updatedAt:s}).where(ae(kt.id,n)).run()})}async updateEntry(e,t,r){this.db.update(un).set({body:r}).where(dt(ae(un.id,t),ae(un.userId,e.userId))).run()}async listEntries(e,t){return this.db.select().from(un).where(dt(ae(un.sessionId,t),ae(un.userId,e.userId))).orderBy(S`rowid`).all().map(({id:r,sessionId:n,createdAt:s,body:o})=>({...o,id:r,sessionId:n,createdAt:s}))}async listTurns(e,t){let r=this.db.select().from(Pn).where(dt(ae(Pn.sessionId,t),ae(Pn.userId,e.userId))).orderBy(Pn.createdAt).all();if(r.length===0)return[];let n=this.db.select().from(Zt).where(_i(Zt.turnId,r.map((o)=>o.id))).orderBy(Zt.position).all(),s=this.withAssets(n);return r.map((o)=>({...o,jobs:s.filter((i)=>i.turnId===o.id)}))}withAssets(e){if(e.length===0)return[];let t=this.db.select().from(Tt).where(_i(Tt.jobId,e.map((r)=>r.id))).orderBy(Tt.createdAt,Tt.id).all();return e.map((r)=>({...r,assets:t.filter((n)=>n.jobId===r.id)}))}async addSpending(e){this.db.insert(Ct).values(e).run()}async settleSpending(e,t){if(t>0)this.db.update(Ct).set({pending:!1,costUsd:t}).where(ae(Ct.id,e)).run();else await this.releaseSpending(e)}async releaseSpending(e){this.db.delete(Ct).where(dt(ae(Ct.id,e),ae(Ct.pending,!0))).run()}async releasePendingSpending(){this.db.delete(Ct).where(ae(Ct.pending,!0)).run()}async createAsset(e){this.db.insert(Tt).values(e).run()}async getAssets(e,t){if(t.length===0)return[];return this.db.select().from(Tt).where(dt(_i(Tt.id,t),ae(Tt.userId,e.userId))).all()}async deleteAsset(e,t){return this.db.transaction((r)=>{let n=r.select().from(Tt).where(dt(ae(Tt.id,t),ae(Tt.userId,e.userId))).get();if(!n)return{sharing:0};return r.delete(Tt).where(ae(Tt.id,t)).run(),{sharing:r.select({n:S`count(*)`}).from(Tt).where(dt(ae(Tt.userId,e.userId),ae(Tt.hash,n.hash))).get()?.n??0}})}async listGallery(e,t){let{assets:r}=Ii;return this.db.select().from(r).where(dt(ae(r.userId,e.userId),ae(r.kind,"output"),t.before?wd(Oc(r.createdAt,t.before.createdAt),dt(ae(r.createdAt,t.before.createdAt),Oc(r.id,t.before.id))):void 0,t.query?S`${r.prompt} like ${`%${t.query.replace(/[%_\\]/g,"\\$&")}%`} escape '\\'`:void 0)).orderBy(xi(r.createdAt),xi(r.id)).limit(t.limit).all()}async findJob(e){let t=this.db.select().from(Zt).where(ae(Zt.id,e)).get();return t?this.withAssets([t])[0]??null:null}async updateJob(e,t){this.db.update(Zt).set(t).where(ae(Zt.id,e)).run()}async listUnfinishedJobs(){return this.db.select().from(Zt).where(bd(Zt.status,[...ed])).orderBy(Zt.createdAt,Zt.position).all()}}var oU;var BE=b(()=>{Sd();Ww();UE();Br();Xw();Jw();oU=sU(import.meta.dir,"..","..","drizzle")});function Yn(e){let t=(n,s=0)=>n.every((o,i)=>e[s+i]===o),r=(n,s=0)=>t(Array.from(n,(o)=>o.charCodeAt(0)),s);if(t([137,80,78,71,13,10,26,10]))return"image/png";if(t([255,216,255]))return"image/jpeg";if(r("RIFF")&&r("WEBP",8))return"image/webp";if(r("GIF8"))return"image/gif";if(r("ftyp",4))return r("qt ",8)?"video/quicktime":"video/mp4";if(t([26,69,223,163]))return"video/webm";return null}function qE(e,t){let r=(n)=>n.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim();return r(e)===r(t)}function FE(e){let t=e.toLowerCase().replace(/[\u2018\u2019\u201C\u201D]/g,"'");if(/[^ -~\s]/.test(t))return!1;let r=(t.match(/[a-z0-9]+/g)??[]).filter((s)=>!/\d/.test(s));if(r.some((s)=>s.length<=3&&!cU.has(s)))return!1;if(r.some((s)=>lU.has(s)))return!1;let n=r.filter((s)=>iU.has(s)).length;return n>=2&&n/r.length>=0.2&&r.some((s)=>aU.has(s))}function uU(e){let n="",s=0;for(;;){let o=e.indexOf("<think>",s),i=o<0?-1:e.indexOf("</think>",o+7);if(i<0)return n+e.slice(s);n+=e.slice(s,o),s=i+8}}function qc(e){let t=uU(e).trim();t=t.replace(/^(english|translation|prompt)\s*:\s*/i,"").trim();let r=t.match(/^["\u201C'\u00AB](.*)["\u201D'\u00BB]$/s);if(r?.[1]&&!/["\u201C\u201D\u00AB\u00BB]/.test(r[1]))t=r[1].trim();return t}var Md,iU,aU,cU,lU;var Fc=b(()=>{Md=["You translate prompts for an image and video generator into English.","Translate word for word, as literally as reads naturally: do not add words, adjectives or details, and do not leave any out.","Keep every color, number and detail exactly as given, in the same order.","Keep names, brands and any text in quotes exactly as written: the quoted text is meant to appear in the picture.","Reply with the English prompt only: no notes, no quotes around it, no explanations.","If the prompt is already in English, reply with it unchanged.",'Example: "um carro azul numa rua molhada \xE0 noite" becomes "a blue car on a wet street at night".'].join(" ");iU=new Set("a an the of in on at to by for with and or from into onto over under near behind above below through across between while is are was its his her their this that these those wearing holding".split(" ")),aU=new Set("the of with and from into onto through across between while behind above below their this that these those wearing holding".split(" ")),cU=new Set("a an the of in on at to by for and or as is are was be it its his her he she we you they him our my me up out off all one two six ten few new old big red tan sky sun sea day man men boy guy cat dog fox owl cow pig bee ant bug hat cap car bus van toy box cup mug pot pan jar bed rug map pen key art oil ink eye ear arm leg lip toe fur ice fog mud air sad mad shy wet dry hot raw low far top end way set mix no not but how who why yet now fly run sit see led tv pc hd uhd hdr rgb pov bw dof cg cgi ai ui gui s t d ll re ve m".split(" ")),lU=new Set("para pela pelo pelas pelos uma umas sobre entre avec dans sous pour eine einer einem einen della dello degli nella sulla unos unas desde".split(" "))});function ZE(e,t){return e.isResumable?.(t)??e.resumable}function HE(e,t,r){let{usdPerSecond:n,usdPerOutput:s}=e.pricing??{};if(n!=null&&t.durationSeconds!=null)return n*t.durationSeconds*r;return s==null?null:s*r}function GE(e,t){let r=0,n=Number.POSITIVE_INFINITY;return e.forEach((s,o)=>{let i=t.get(s.userId)??0;if(i<n)r=o,n=i}),r}function Ai(e){return new be(dU[e],e,403)}function gU(e){let t=new Promise((r,n)=>{if(e.aborted)return n(e.reason);e.addEventListener("abort",()=>n(e.reason),{once:!0})});return t.catch(()=>{}),t}function yU(e,t){return new Promise((r,n)=>{if(t.aborted)return n(t.reason);let s=setTimeout(()=>{t.removeEventListener("abort",o),r()},e),o=()=>{clearTimeout(s),n(t.reason)};t.addEventListener("abort",o,{once:!0})})}class tb{deps;listeners=new Set;controllers=new Map;previews=new Map;waiting=new Map;active=new Map;lastStart=new Map;starts=0;owned=new Set;translations=new WeakMap;inflight=new Set;limit;constructor(e){this.deps=e;this.limit=e.concurrencyPerProvider??4}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async start(){await this.deps.repo.releasePendingSpending();for(let e of await this.deps.repo.listUnfinishedJobs()){let t=this.deps.registry.adapter(e.providerId);if(e.status==="queued"||t!=null&&e.handle!=null&&ZE(t,e.handle))this.enqueue(e);else await this.update(e.id,{status:"failed",error:"Interrupted by a restart",errorCode:"interrupted",errorParams:null,finishedAt:Date.now()})}}enqueue(e){if(this.owned.has(e.id))return;this.owned.add(e.id),this.schedule(e)}schedule(e){let t=this.deps.registry.adapter(e.providerId),r=t?.lineOf?`${e.providerId}#${t.lineOf(e.modelId)}`:e.providerId,n=this.waiting.get(r)??[];n.push({id:e.id,userId:e.userId}),this.waiting.set(r,n),this.pump(r,e.providerId),this.tellPlaces(r)}tellPlaces(e){let t=[...this.waiting.get(e)??[]],r=new Map(this.lastStart.get(e)),n=this.starts;for(let s=1;t.length>0;s++){let[o]=t.splice(GE(t,r),1);if(!o)break;r.set(o.userId,++n),this.emit(o.userId,{type:"job.progress",jobId:o.id,stage:"queued",position:s})}}preview(e,t){let r=this.previews.get(t);return r?.userId===e?{data:r.data,mime:r.mime}:void 0}async cancel(e){let t=this.controllers.get(e);if(t){t.abort();return}for(let[r,n]of this.waiting){let s=n.findIndex((o)=>o.id===e);if(s===-1)continue;n.splice(s,1),this.owned.delete(e),await this.update(e,{status:"canceled",finishedAt:Date.now()}),this.tellPlaces(r);return}}async retry(e,t=null){if(e.status!=="failed"&&e.status!=="canceled")throw new O("Only a job that failed or was canceled can be tried again","jobNotRetryable");if(this.owned.has(e.id))return;this.owned.add(e.id);try{await this.update(e.id,{status:"queued",error:null,errorCode:null,errorParams:null,costUsd:null,startedAt:null,finishedAt:null,tokenId:t})}catch(r){throw this.owned.delete(e.id),r}this.schedule(e)}async idle(){while(this.inflight.size>0)await Promise.all(this.inflight)}pump(e,t){let r=this.waiting.get(e)??[],n=this.deps.registry.adapter(t),s=Math.min(this.limit,n?.maxConcurrency??this.limit),o=!1,i=this.lastStart.get(e)??new Map;this.lastStart.set(e,i);while((this.active.get(e)??0)<s){let[a]=r.splice(GE(r,i),1),c=a?.id;if(!a||!c)break;i.set(a.userId,++this.starts),o=!0,this.active.set(e,(this.active.get(e)??0)+1);let l=this.run(c).catch((u)=>console.error(`Job ${c} could not be settled`,u)).finally(()=>{if(this.owned.delete(c),this.inflight.delete(l),this.active.set(e,(this.active.get(e)??1)-1),this.pump(e,t))this.tellPlaces(e)});this.inflight.add(l)}return o}async run(e){let t=await this.deps.repo.findJob(e);if(!t||ed.includes(t.status))return;let r=new AbortController;this.controllers.set(e,r);let n=!1,s="server",{registry:o,keys:i}=this.deps,a=o.adapter(t.providerId),c={userId:t.userId},l=t.handle,u=null,d={apiKey:void 0,signal:r.signal};try{let p=o.model(t.modelId);if(!a||!p)throw new le(`Model is not available: ${t.modelId}`,"modelUnavailable",{model:t.modelId});let f=a.keyEnv?process.env[a.keyEnv]:void 0,m=await i.find(c,a.id)??(f?{key:f,source:"server"}:void 0);s=m?.source??"server";let h=a.requiresKey?this.deps.paidRefusal?.({userId:t.userId,tokenId:t.tokenId??null},s):null;if(h)throw Ai(h);if(a.requiresKey)u=Ft("spd"),await this.deps.repo.addSpending({id:u,userId:t.userId,kind:"generation",keySource:s,tokenId:t.tokenId??null,jobId:e,costUsd:HE(p,t.params,t.params.count??1)??eb,pending:!0,createdAt:Date.now()});let g=m?.key;if(a.requiresKey&&!g)throw new le(`No API key configured for ${a.name}`,"noApiKey",{provider:a.name});d={apiKey:g,signal:r.signal};for(let w=1;;w++){n=!1;try{if(l!=null&&w===1&&t.status==="queued")await this.update(e,{status:"running",startedAt:Date.now()});if(l==null){await this.update(e,{status:"running",startedAt:Date.now()});let v=await this.loadReferences(c,t.params.referenceAssetIds),[_]=t.params.maskAssetId!=null?await this.loadReferences(c,[t.params.maskAssetId]):[],C=await this.inEnglish(t,p,r.signal);if(l=await a.submit({model:p,params:C,references:v,..._&&{mask:_}},d),ZE(a,l))await this.update(e,{handle:l})}for await(let v of a.events(l,d))if(v.type==="progress"){let _;if(v.preview)_=(this.previews.get(e)?.version??0)+1,this.previews.set(e,{userId:t.userId,...v.preview,version:_});this.emit(t.userId,{type:"job.progress",jobId:e,fraction:v.fraction,message:v.message,stage:v.stage,position:v.position,step:v.step,steps:v.steps,busyBytes:v.busyBytes,..._!=null&&{preview:_}})}else if(v.type==="failed")throw n=v.code!=="connectionLost",new le(v.error,v.code,v.params,v.retry);else{for(let C of v.outputs)await this.storeOutput(c,t,C,r.signal);let _=v.costUsd??HE(p,t.params,v.outputs.length);if(await this.update(e,{status:"succeeded",error:null,errorCode:null,errorParams:null,finishedAt:Date.now(),costUsd:_}),u)await this.deps.repo.settleSpending(u,_??0),u=null;else if(_!=null&&_>0)await this.deps.repo.addSpending({id:Ft("spd"),userId:t.userId,kind:"generation",keySource:s,tokenId:t.tokenId??null,jobId:e,costUsd:_,createdAt:Date.now()});return}throw new le("The provider ended without a result","noResult")}catch(v){let _=v instanceof le?v.retry:void 0;if(!_||r.signal.aborted||w>=(_.attempts??fU)||(_.afterMs??0)>hU)throw v;this.emit(t.userId,{type:"job.progress",jobId:e,message:"Trying again",stage:"retrying"}),await yU(_.afterMs??(this.deps.retryDelayMs??mU)*2**(w-1),r.signal)}}}catch(p){if(r.signal.aborted){if(l!=null)await a?.cancel?.(l,{...d,signal:new AbortController().signal}).catch(()=>{});await this.update(e,{status:"canceled",finishedAt:Date.now()})}else{let{message:f,code:m,params:h}=$s(p);await this.update(e,{status:"failed",error:f,errorCode:m,errorParams:h,finishedAt:Date.now(),...n&&{handle:null}})}}finally{if(u)await this.deps.repo.releaseSpending(u).catch(()=>{});if(this.controllers.get(e)===r)this.controllers.delete(e),this.previews.delete(e)}}async inEnglish(e,t,r){if(!t.capabilities.englishPrompts)return e.params;if(e.params.translatedPrompt)return{...e.params,prompt:e.params.translatedPrompt};let{prompt:n}=e.params;if(FE(n))return e.params;let s=await this.deps.translator?.({userId:e.userId,tokenId:e.tokenId??null});if(!s)return e.params;this.emit(e.userId,{type:"job.progress",jobId:e.id,message:"Translating the prompt",stage:"translating"});let o=this.translations.get(s);if(!o)o=new Map,this.translations.set(s,o);let i=o,a=i.get(n);if(!a){a=s.toEnglish(n,AbortSignal.timeout(pU)).then((d)=>qc(d)||null,(d)=>(console.error("Could not translate a prompt",d),null)),i.set(n,a);let u=()=>i.delete(n);a.then((d)=>{if(!d)u();else setTimeout(u,60000).unref?.()})}let c=await Promise.race([a,gU(r)]);if(r.throwIfAborted(),!c||qE(c,n))return e.params;let l={...e.params,translatedPrompt:c};return await this.update(e.id,{params:l}),{...l,prompt:c}}async loadReferences(e,t){let r=await this.deps.repo.getAssets(e,t);return Promise.all(t.map(async(n)=>{let s=r.find((i)=>i.id===n),o=s&&await this.deps.assets.get(e,s.hash);if(!s||!o)throw Error(`Reference image is missing: ${n}`);return{data:await o.bytes(),mime:s.mime}}))}async storeOutput(e,t,r,n){let s,o=r.mime;if("url"in r){if(!r.url.startsWith("https://"))throw new le("The provider returned a result URL that is not HTTPS","resultNotHttps");let a=await fetch(r.url,{headers:r.headers,signal:n});if(!a.ok)throw new le(`Could not download the result (HTTP ${a.status})`,"resultDownloadFailed",{status:a.status});if(Number(a.headers.get("content-length"))>VE)throw new le("The result is too large to store","resultTooLarge");s=await a.bytes(),o??=a.headers.get("content-type")?.split(";")[0]}else s=r.data;if(s.byteLength>VE)throw new le("The result is too large to store","resultTooLarge");let i=await this.deps.assets.put(e,s);if(t.assets.some((a)=>a.hash===i.hash))return;await this.deps.repo.createAsset({id:Ft("ast"),userId:e.userId,kind:"output",jobId:t.id,prompt:t.params.prompt,modelId:t.modelId,params:t.params,hash:i.hash,mime:Yn(s)??o??"application/octet-stream",size:i.size,createdAt:Date.now()})}async update(e,t){await this.deps.repo.updateJob(e,t);let r=await this.deps.repo.findJob(e);if(r)this.emit(r.userId,{type:"job.updated",job:r})}emit(e,t){for(let r of this.listeners)try{r(e,t)}catch(n){console.error("A job event listener failed",n)}}}var VE=209715200,eb=0.01,dU,pU=60000,fU=3,mU=2000,hU=60000;var KE=b(()=>{Ar();Fc();Br();dU={paidNotAllowed:"This account cannot use paid models",monthlyLimitReached:"This month's limit for paid models is reached",tokenNotPaid:"This API token cannot use paid models",tokenLimitReached:"This API token's spending limit is reached"}});function QE(e,t=!1,r){return{phrases:e.length>0&&e.every((n)=>wU.has(n.profile?.family??"")),video:e.some((n)=>n.media==="video"),text:e.some((n)=>n.profile?.text===!0),editing:t,...r&&{language:r}}}function bU(e,t=!1){let r=e.video?"a video":"a picture";return[`You write prompts for ${e.video?"a video":"an image"} generator.`,"Turn the person's idea into one richer prompt that keeps everything they asked for: the subject, every color, number and name, and any text in quotes, exactly as given.",`Where the idea leaves it open, add what makes ${r} good: the setting, the light, the style or camera, the composition and the mood.`,"Do not change what the idea says and do not add a second subject. Give the subject the look people usually picture, unless the idea says otherwise.",t?"Keep the text in quotes exactly as written, in quotes, and add no other words to the picture.":"The idea has no text to show: put no words, letters, captions or quotes in the prompt.",e.phrases?"This model reads short phrases best: write 15 to 40 words as phrases separated by commas, the most important first, no full sentences.":"This model reads plain language best: write two to four sentences, 40 to 90 words in all.",...e.video?["Describe what moves and how the camera moves, as one continuous shot of a few seconds. Describe only what is seen: no sounds."]:[],...e.text&&t?["This model can write words inside pictures: say where the text appears and how it looks."]:[],...e.editing?["The person is changing a picture they gave, which you cannot see: keep their request at the heart of the prompt and add only style and light; do not describe what the picture shows."]:[],JE(e.language)?`Write the prompt in ${JE(e.language)}, whatever language the idea is in.`:"Write in the same language as the idea.","Reply with the prompt only: no title, no notes, no quotes around it."].join(" ")}function JE(e){if(!e)return;try{let t=new Intl.DisplayNames(["en"],{type:"language"}).of(e);return t&&t!==e?t:void 0}catch{return}}async function XE(e,t,r,n){let s=t.trim(),o=WE.test(s),i=()=>e.reply(bU(r,o),s,n,{temperature:vU}),a;try{a=await i()}catch(l){if(n.aborted||l instanceof le&&l.code)throw l;throw new le(`Could not improve the prompt: ${l instanceof Error?l.message:String(l)}`,"improveFailed")}if(!o&&WE.test(qc(a)))try{a=await i()}catch(l){if(n.aborted)throw l}let c=qc(a);if(!c)throw new le("Could not improve the prompt: no answer","improveFailed");return c}function YE(e,t,r=()=>!0){let{improveWith:n,translateWith:s}=e;if(n==="local")return t?"local":null;if(n!=="auto"&&r(n))return n;if(t)return"local";if(s==="off"||s==="local")return null;return r(s)?s:null}function e1(e,t,r){let{assistantWith:n,translateWith:s}=e;if(n==="local")return t?"local":null;if(n!=="auto"&&r(n))return n;let o=["openai","google","openrouter"],a=o.find((c)=>c===s&&r(c))??o.find(r);if(a)return a;return t?"local":null}var wU,WE,vU=0.7;var t1=b(()=>{Ar();Fc();wU=new Set(["sdxl","sdxl-turbo","sd-1.5"]);WE=/["\u201C\u00AB\u201E][^"\u201C\u201D\u00AB\u00BB\u201E]+["\u201D\u00BB\u201C]|\u2018[^\u2018\u2019]+\u2019|\u300C[^\u300C\u300D]+\u300D|\u300E[^\u300E\u300F]+\u300F|(?<![\p{L}\p{N}])'[^'\n]+'(?![\p{L}\p{N}])/u});function lt(e,t){return e[Ri("hatchlight",t)]||e[Ri("open-reel",t)]||void 0}var es="open-reel",Ds="hatchlight",Ri=(e,t)=>`${e.toUpperCase().replaceAll("-","_")}_${t}`,Vc=(e)=>e.startsWith("hatchlight")?"open-reel"+e.slice(10):e;import{hkdfSync as _U}from"crypto";import{chmodSync as xU,existsSync as r1,readFileSync as n1,statSync as SU,writeFileSync as $U}from"fs";import{join as kU}from"path";function s1(e,t=process.env,r=process.platform){let n=lt(t,"SECRET_FILE"),s=n??kU(e,"secret.key"),o;if(n){if(!r1(n))throw new ts(`HATCHLIGHT_SECRET_FILE names ${n}, which does not exist`);o=n1(n)}else if(r1(s))o=n1(s);else o=crypto.getRandomValues(new Uint8Array(32)),$U(s,o,{mode:384,flag:"wx"}),xU(s,384);if(r!=="win32"&&(SU(s).mode&63)!==0)throw new ts(`${s} can be read by other users of this machine. Make it private with: chmod 600 ${s}`);if(o.byteLength<16)throw new ts(`${s} is too short to be a secret: it needs at least 16 bytes, better 32 random ones`);return new Uint8Array(_U("sha256",o,new Uint8Array(0),"hatchlight api keys",32))}var ts;var rb=b(()=>{ts=class ts extends Error{}});import{createCipheriv as TU,createDecipheriv as PU}from"crypto";import{mkdir as EU,rename as o1,writeFile as IU}from"fs/promises";import{dirname as AU}from"path";function js(e){return e==="__proto__"||e==="constructor"||e==="prototype"}class nb{path;secret;pending=Promise.resolve();constructor(e,t){this.path=e;this.secret=t;if(t.byteLength!==32)throw Error("The secret must be 32 bytes")}seal(e,t,r){let n=crypto.getRandomValues(new Uint8Array(12)),s=TU("aes-256-gcm",this.secret,n);s.setAAD(Buffer.from(`${e}
|
|
72
|
+
${t}`));let o=Buffer.concat([s.update(r,"utf8"),s.final(),s.getAuthTag()]);return`${Nd}${Buffer.from(n).toString("base64url")}.${o.toString("base64url")}`}open(e,t,r){if(!r.startsWith(Nd))return r;let[n="",s=""]=r.slice(Nd.length).split("."),o=Buffer.from(s,"base64url");try{let i=PU("aes-256-gcm",this.secret,Buffer.from(n,"base64url"));return i.setAAD(Buffer.from(`${e}
|
|
73
|
+
${t}`)),i.setAuthTag(o.subarray(o.byteLength-16)),Buffer.concat([i.update(o.subarray(0,o.byteLength-16)),i.final()]).toString("utf8")}catch{throw new ts(`The API keys in ${this.path} cannot be read with this secret: it is not the one they were saved with. Restore that secret (HATCHLIGHT_SECRET_FILE, or secret.key in the data directory); the file is left as it is`)}}async prepare(){try{await this.read()}catch(r){if(!(r instanceof ts))throw r;let n=Object.keys(await this.readRaw()),s=`${this.path.replace(/\.json$/,"")}.unreadable-${new Date().toISOString().replace(/[:.]/g,"-")}.json`;return await o1(this.path,s),{file:s,owners:n}}let e=await this.readRaw();if(Object.values(e).some((r)=>Object.values(r??{}).some((n)=>!n.startsWith(Nd))))await this.change(()=>{});return null}change(e){let t=this.pending.then(async()=>{let r=await this.read();e(r),await this.write(r)});return this.pending=t.catch(()=>{}),t}async readRaw(){let e=Bun.file(this.path);if(!await e.exists())return{};return await e.json()}async read(){let e=await this.readRaw(),t={};for(let[r,n]of Object.entries(e)){if(js(r))continue;t[r]={};for(let[s,o]of Object.entries(n??{})){if(js(s))continue;t[r][s]=this.open(r,s,o)}}return t}async write(e){await EU(AU(this.path),{recursive:!0});let t=`${this.path}.${crypto.randomUUID()}.tmp`,r={};for(let[n,s]of Object.entries(e)){r[n]={};for(let[o,i]of Object.entries(s??{}))r[n][o]=this.seal(n,o,i)}await IU(t,JSON.stringify(r,null,2),{mode:384}),await o1(t,this.path)}async get(e,t){let r=await this.read();if(!Object.hasOwn(r,e.userId))return;let n=r[e.userId];return n&&Object.hasOwn(n,t)?n[t]:void 0}async find(e,t){let r=await this.get(e,t);return r===void 0?void 0:{key:r,source:"personal"}}async set(e,t,r){if(js(e.userId)||js(t))throw Error(`Not a provider: ${t}`);await this.change((n)=>{n[e.userId]={...n[e.userId],[t]:r}})}async delete(e,t){if(js(e.userId)||js(t))return;await this.change((r)=>{if(!Object.hasOwn(r,e.userId))return;let n=r[e.userId];if(n&&Object.hasOwn(n,t))delete n[t]})}async list(e){let t=await this.read();return Object.hasOwn(t,e.userId)?Object.keys(t[e.userId]??{}):[]}async moveUser(e,t){if(js(e)||js(t))return;await this.change((r)=>{if(!Object.hasOwn(r,e))return;r[t]={...r[e],...r[t]},delete r[e]})}}class sb{inner;mayUse;constructor(e,t){this.inner=e;this.mayUse=t}async get(e,t){return(await this.find(e,t))?.key}async find(e,t){if(!this.mayUse(e.userId))return;let r=e.userId===rs.userId?void 0:await this.inner.get(e,t);if(r!==void 0)return{key:r,source:"personal"};let n=await this.inner.get(rs,t);return n===void 0?void 0:{key:n,source:"server"}}set(e,t,r){return this.inner.set(e,t,r)}delete(e,t){return this.inner.delete(e,t)}async list(e){if(!this.mayUse(e.userId))return[];let{personal:t,server:r}=await this.sources(e);return[...new Set([...t,...r])]}async sources(e){return{personal:e.userId===rs.userId?[]:await this.inner.list(e),server:await this.inner.list(rs)}}}var Nd="enc:v1:",rs;var i1=b(()=>{rb();rs={userId:"server"}});import{mkdir as RU,readdir as ob,rename as a1,rm as Ci,stat as c1}from"fs/promises";import{join as No}from"path";async function zU(e,t){if(e.size<8)throw t();let r=new DataView(await e.slice(0,8).arrayBuffer()),n=Number(r.getBigUint64(0,!0));if(n<2||n>CU||8+n>e.size)throw t();let s;try{s=JSON.parse(await e.slice(8,8+n).text())}catch{throw t()}if(!s||typeof s!=="object"||Array.isArray(s))throw t();let{__metadata__:o,...i}=s,a={};if(o&&typeof o==="object"){for(let[c,l]of Object.entries(o))if(typeof l==="string")a[c]=l}return{keys:Object.keys(i),metadata:a}}function Ld(e,t,r){let n=e["modelspec.title"]?.trim()||e.ss_output_name?.trim(),s=t.replace(/\.safetensors$/i,"").trim();return(n||s||r).slice(0,80)}function l1(e,t,r){let n=e.normalize("NFKD").replace(/[\u0300-\u036F]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,56)||r;if(!t(n))return n;for(let s=2;;s++){let o=`${n}-${s}`;if(!t(o))return o}}class Zc{kind;options;uploads=0;naming=Promise.resolve();constructor(e,t){this.kind=e;this.options=t}get busy(){return this.uploads>0}get dir(){return No(this.options.root(),this.kind.folder)}missing(e){return new Ee("Not found",this.kind.errors.missing,{id:e})}unreadable(){return new O("This file cannot be read as a safetensors model",this.kind.errors.unreadable)}path(e){if(!ib.test(e))throw this.missing(e);return No(this.dir,`${e}.safetensors`)}notes(e){return No(this.dir,`${e}.json`)}async writeNotes(e,t){let r=`${e}.${crypto.randomUUID()}.tmp`;await Bun.write(r,JSON.stringify(t,null,"\t"));try{await a1(r,e)}catch(n){throw await Ci(r,{force:!0}),n}}async sweep(){for(let e of await ob(this.dir).catch(()=>[])){if(!e.endsWith(".part"))continue;let t=No(this.dir,e),r=await c1(t).catch(()=>null);if(r&&Date.now()-r.mtimeMs>OU)await Ci(t,{force:!0})}}async list(){let e=await ob(this.dir).catch(()=>[]),t=[];for(let r of e){let n=r.replace(/\.json$/,"");if(n===r||!ib.test(n))continue;let s=await this.read(n);if(s)t.push(s)}return t.sort((r,n)=>n.addedAt-r.addedAt)}async get(e){let t=ib.test(e)?await this.read(e):null;if(!t)throw this.missing(e);return t}async read(e){let t=await c1(this.path(e)).catch(()=>null);if(!t?.isFile())return null;let r=await Bun.file(this.notes(e)).json().catch(()=>null);if(!r||typeof r!=="object"||Array.isArray(r))return null;let n=this.kind.parse(r);if(!n)return null;let{addedAt:s}=r;return{...n,id:e,size:t.size,addedAt:typeof s==="number"?s:t.mtimeMs}}async add(e,t,r){this.options.check?.(),this.uploads++,await this.sweep().catch(()=>{});let n=this.dir;await RU(n,{recursive:!0}).catch((o)=>{throw this.uploads--,o});let s=No(n,`${crypto.randomUUID()}.part`);try{let o=()=>new O("This file is too large",this.kind.errors.tooLarge),i=Math.min(this.kind.maxBytes,r?.maxBytes??1/0),a=0,c=null,l=(e instanceof Blob?e.stream():e).pipeThrough(new TransformStream({transform:(g,w)=>{if(a+=g.byteLength,a>i){c=a>this.kind.maxBytes||!r?o():r.error(),w.error(c);return}w.enqueue(g)}})),u=await Bun.write(s,new Response(l)).catch((g)=>{throw c??g});if(u>this.kind.maxBytes)throw new O("This file is too large",this.kind.errors.tooLarge);let d=await zU(Bun.file(s),()=>this.unreadable()),p=this.kind.inspect(d,t),f=async()=>{let g=new Set((await ob(n).catch(()=>[])).map((C)=>C.replace(/\.(safetensors|json)$/,""))),w=l1(p.name,(C)=>g.has(C),this.kind.folder.replace(/s$/,"")),v=Date.now(),_=No(n,`${w}.json`);await this.writeNotes(_,{...p,addedAt:v});try{await a1(s,No(n,`${w}.safetensors`))}catch(C){throw await Ci(_,{force:!0}),C}return{...p,id:w,size:u,addedAt:v}},m=this.naming.then(f,f);this.naming=m.catch(()=>{});let h=await m;return this.options.changed?.(),h}finally{this.uploads--,await Ci(s,{force:!0})}}async update(e,t){this.options.check?.();let r=await this.get(e),{id:n,size:s,...o}=r,i=this.kind.parse({...o,...t});if(!i)throw new O("These settings are not valid",this.kind.errors.invalid);return await this.writeNotes(this.notes(e),{...i,addedAt:r.addedAt}),this.options.changed?.(),this.get(e)}async remove(e){this.options.check?.(),await this.get(e),await this.options.release?.(),await Ci(this.path(e),{force:!0}),await Ci(this.notes(e),{force:!0}),this.options.changed?.()}}var ib,CU=104857600,OU=3600000;var Dd=b(()=>{Ar();Br();ib=Vy});function cb(e){let t=[e["modelspec.architecture"],e.ss_base_model_version].filter(Boolean).join(" ").toLowerCase();if(!t)return null;if(/stable-diffusion-xl|sdxl/.test(t))return"sdxl";if(/stable-diffusion-v1|sd_v1|sd-v1/.test(t))return"sd1";if(/flux/.test(t))return"flux";if(/wan/.test(t))return"wan";if(/z-image|zimage/.test(t))return"z-image";return"unknown"}function MU(e){let t=(r)=>e.some((n)=>r.test(n));if(t(/double_blocks|single_blocks|single_transformer_blocks/))return"flux";if(t(/noise_refiner|context_refiner/))return"z-image";if(t(/blocks[._]\d+[._](cross_attn|self_attn)/))return"wan";if(t(/lora_te2_|text_encoder_2/)||t(/lora_unet_(input_blocks|output_blocks|middle_block)_/)||t(/(down|up)_blocks[._]\d+[._]attentions[._]\d+[._]transformer_blocks[._][2-9]/))return"sdxl";if(t(/lora_unet_down_blocks_|lora_te_text_model|unet\.down_blocks/))return"sd1";return null}function NU(e){let t=cb(e.metadata);if(t==="unknown")return null;return t??MU(e.keys)}function LU(e){try{let t=JSON.parse(e.ss_tag_frequency??"null");if(!t||typeof t!=="object")return null;let r=JSON.parse(e.ss_dataset_dirs??"null"),n=new Map;for(let i of Object.values(t))for(let[a,c]of Object.entries(i??{})){if(typeof c!=="number")continue;n.set(a.trim(),(n.get(a.trim())??0)+c)}let s=r?Object.values(r).reduce((i,a)=>i+(a?.img_count??0),0):Math.max(0,...n.values());if(s<2)return null;let[o]=[...n].filter(([i,a])=>a>=s&&i.length<=40&&!/[<>:]/.test(i)).map(([i])=>i);return o||null}catch{return null}}var ab=4294967296,lb;var jd=b(()=>{Ar();Br();Dd();lb=class lb extends Zc{constructor(e){super({folder:"loras",maxBytes:ab,errors:{missing:"loraMissing",tooLarge:"loraTooLarge",unreadable:"loraUnreadable",invalid:"loraUnreadable"},inspect(t,r){let n=NU(t);if(!n)throw new O("This file does not look like a LoRA for a model Hatchlight knows","loraUnknownBase");return{name:Ld(t.metadata,r,"LoRA"),base:n,trigger:LU(t.metadata)}},parse(t){let{name:r,base:n,trigger:s}=t;if(typeof r!=="string"||!Zy.includes(n))return null;return{name:r,base:n,trigger:typeof s==="string"?s:null}}},e)}}});function jU(e){let t=cb(e.metadata);if(t!==null&&t!=="sdxl"&&t!=="sd1")return null;let r=(n)=>e.keys.some((s)=>s.startsWith(n));if(!r("model.diffusion_model.")||!r("first_stage_model."))return null;if(r("conditioner.embedders.1."))return"sdxl";if(r("cond_stage_model.transformer."))return"sd1";return null}function ub(e,t,r,n){if(typeof e!=="number"||!Number.isFinite(e))return null;if(n&&!Number.isInteger(e))return null;return e>=t&&e<=r?e:null}var Hc=17179869184,DU,u1,d1=(e)=>`ckpt-${e}`,db=(e)=>e.startsWith("ckpt-")?e.slice(5):null,pb;var Ud=b(()=>{Ar();Br();jd();Dd();DU={sdxl:{steps:30,cfgScale:7},sd1:{steps:20,cfgScale:7}},u1={sdxl:"sdxl-base",sd1:"sd-1.5"};pb=class pb extends Zc{constructor(e){super({folder:"checkpoints",maxBytes:Hc,errors:{missing:"checkpointMissing",tooLarge:"checkpointTooLarge",unreadable:"checkpointUnreadable",invalid:"checkpointSettingsInvalid"},inspect(t,r){let n=jU(t);if(!n)throw new O("This file is not a whole SDXL or SD 1.5 model with its VAE","checkpointUnknownBase");let s=Ld(t.metadata,r,"Model");return{name:s,base:n,...DU[n],clipSkip:/pony/i.test(`${s} ${r}`)?2:null}},parse(t){let{name:r,base:n}=t,s=ub(t.steps,1,150,!0),o=ub(t.cfgScale,0,30,!1),i=t.clipSkip==null?null:ub(t.clipSkip,1,12,!0);if(typeof r!=="string"||!r.trim()||r.length>80||!AT.includes(n)||s==null||o==null||t.clipSkip!=null&&i==null)return null;return{name:r.trim(),base:n,steps:s,cfgScale:o,clipSkip:i}}},e)}}});function qU(e,t){if(!e)return!1;let[r=0,n=0]=e.split(".").map(Number),[s=0,o=0]=t.split(".").map(Number);return r>s||r===s&&n>=o}function FU(e,t){return e.gpus.filter((r)=>BU[t].includes(r.vendor)).sort((r,n)=>n.memoryBytes-r.memoryBytes)[0]}function p1(e,t,r){let n=r.wsl?[{os:"win32",throughWindows:!0},{os:"linux",throughWindows:!1}]:[{os:r.os,throughWindows:!1}];for(let s of UU){let o=FU(r,s);if(s!=="cpu"&&!o)continue;for(let{os:i,throughWindows:a}of n){let c=t.find((l)=>l.engine===e&&l.backend===s&&l.os===i&&l.arch===r.arch&&(!l.minNvidiaDriver||qU(o?.driver,l.minNvidiaDriver)));if(!c)continue;if(r.wsl&&!a&&s!=="cpu")continue;return{build:c,...o&&{gpu:o},throughWindows:a}}}return null}function Oi(e,t,r){if(!r)return"none";let n=t.memoryBytes*VU;if(!r.gpu)return e.memoryBytes<=n?"cpu":"none";if(e.memoryBytes<=r.gpu.memoryBytes)return"gpu";if(r.gpu.vendor==="apple")return"none";return e.memoryBytes<=r.gpu.memoryBytes+n?"offload":"none"}function fb(e,t,r){let n=e.flatMap((s)=>{let o=r(s.engine);if(!o)return[];let i=Oi(s,t,o);return i==="none"?[]:[{variant:s,fit:i,build:o}]});return n.find((s)=>s.fit==="gpu")??n.sort((s,o)=>s.variant.memoryBytes-o.variant.memoryBytes)[0]??null}var UU,BU,VU=0.8;var mb=b(()=>{UU=["cuda","rocm","metal","vulkan","cpu"],BU={cuda:["nvidia"],rocm:["amd"],metal:["apple"],vulkan:["nvidia","amd","intel"],cpu:[]}});import{existsSync as f1}from"fs";import{readFile as ZU}from"fs/promises";import{totalmem as HU}from"os";async function GU(e){return(await e(["nvidia-smi","--query-gpu=name,memory.total,driver_version","--format=csv,noheader,nounits"])??"").split(`
|
|
74
|
+
`).map((r)=>r.split(",").map((n)=>n.trim())).filter(([r,n])=>r&&Number(n)>0).map(([r,n,s])=>({vendor:"nvidia",name:r,memoryBytes:Number(n)*hb,...s&&{driver:s}}))}function KU(e){let t=e?.split(`
|
|
75
|
+
`).find((o)=>o.trim());if(!t)return null;let[r,n,...s]=t.split(",").map((o)=>o.trim());if(s.length>0||!r||!n)return null;if(!/^\d+$/.test(r)||!/^\d+$/.test(n))return null;if(Number(n)<=0||Number(r)>Number(n))return null;return{freeBytes:Number(r)*hb,totalBytes:Number(n)*hb}}async function Bd(e=m1){try{return KU(await e(["nvidia-smi","--query-gpu=memory.free,memory.total","--format=csv,noheader,nounits"]))}catch{return null}}async function WU(e,t){let r=(await e(["sysctl","-n","machdep.cpu.brand_string"]))?.trim();if(!r?.startsWith("Apple"))return[];return[{vendor:"apple",name:`${r} GPU`,memoryBytes:Math.floor(t*0.75)}]}async function JU(e){let t=await e(["rocm-smi","--showproductname","--showmeminfo","vram","--json"]);if(!t)return[];try{let r=JSON.parse(t);return Object.values(r).flatMap((n)=>{let s=Number(n["VRAM Total Memory (B)"]),o=n["Card Series"]??n["Card series"]??"AMD GPU";return s>0?[{vendor:"amd",name:o,memoryBytes:s}]:[]})}catch{return[]}}async function qd(e={}){let t=e.run??m1,r=e.platform??process.platform,n=e.arch??process.arch,s=e.memoryBytes??HU(),o=e.procVersion??(r==="linux"?await ZU("/proc/version","utf8").catch(()=>""):""),i=r==="darwin"?await WU(t,s):[...await GU(t),...r==="linux"?await JU(t):[]];return{os:r==="linux"||r==="darwin"||r==="win32"?r:"other",arch:n==="x64"||n==="arm64"?n:"other",wsl:r==="linux"&&/microsoft/i.test(o)&&!(e.container??(f1("/.dockerenv")||f1("/run/.containerenv"))),memoryBytes:s,gpus:i}}var m1=async(e)=>{try{let t=Bun.spawn(e,{stdout:"pipe",stderr:"ignore"}),r=setTimeout(()=>t.kill(),5000),[n,s]=await Promise.all([new Response(t.stdout).text(),t.exited]);return clearTimeout(r),s===0?n:null}catch{return null}},hb=1048576;var Gc=()=>{};async function QU(){let e=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response}),t=e.port;return e.stop(!0),t}class gb{running=null;starting=null;idle;spawn;fetch;freePort;idleMs;gpu;hold=null;held=0;busy=0;constructor(e){this.spawn=e.spawn,this.fetch=e.fetch??((t,r)=>fetch(t,r)),this.freePort=e.freePort??QU,this.idleMs=e.idleMs??600000,this.gpu=e.gpu}get unused(){return this.busy===0}get loaded(){return this.running?.key??null}async server(e,t,r){if(this.running?.key===e)return this.running;if(this.starting)await this.starting.catch(()=>{});if(this.running?.key===e)return this.running;this.running?.stop(),this.running=null,this.starting=this.start(e,t,r);try{return this.running=await this.starting,this.running}finally{this.starting=null}}async start(e,t,r){let n=await this.freePort(),s=this.spawn([...t,"--listen-ip","127.0.0.1","--listen-port",String(n)]),o=`http://127.0.0.1:${n}`,i=[],a=!1;(async()=>{for await(let d of s.output){if(d.trim())i.push(d.trim());if(i.length>20)i.shift();if(/listening on/i.test(d))a=!0}})().catch(()=>{});let l=!1;s.exited.then(()=>{if(l=!0,this.running?.exited===s.exited)this.stop()});let u=Date.now();while(!a){if(l||r.aborted||Date.now()-u>300000){s.kill();let d=i.filter((p)=>/error|fail/i.test(p)).at(-1)??(r.aborted?"canceled":"the engine server did not start");throw Error(d.replace(/^\[\w\]\s*/,""))}await Bun.sleep(250)}return{key:e,url:o,stop:()=>s.kill(),exited:s.exited}}stop(){clearTimeout(this.idle),this.running?.stop(),this.running=null,this.hold?.release(),this.hold=null,this.held=0}async stopAndWait(){let e=this.running;this.stop(),await e?.exited}async*run(e,t,r,n,s=0,o){clearTimeout(this.idle),this.busy++;try{if(this.running?.key!==e||this.gpu?.wanted(this.held)){let a=this.held;if(this.stop(),this.gpu)this.hold=yield*this.gpu.acquire(s,n,{onWanted:()=>{if(this.busy===0)this.stop()}}),this.held=s;if(o)yield*o(a);yield{type:"progress",message:"Loading the model",stage:"loading"}}let i;try{i=await this.server(e,t,n)}catch(a){throw this.stop(),a}yield*this.job(i,r,n)}finally{if(this.busy--,clearTimeout(this.idle),this.running)this.idle=setTimeout(()=>this.stop(),this.idleMs);else if(this.busy===0)this.stop()}}async*job(e,t,r){let n={prompt:t.prompt,negative_prompt:t.negativePrompt??"",width:t.width,height:t.height,seed:t.seed,sample_params:{sample_steps:t.steps,guidance:{txt_cfg:t.cfgScale},...t.sampler&&{sample_method:t.sampler},...t.flowShift!=null&&{flow_shift:t.flowShift}},...t.video?{video_frames:t.frames,fps:t.fps,output_format:"webm"}:{batch_count:1,output_format:"png"},...t.initImage!=null&&{init_image:t.initImage},...t.refImages?.length&&{ref_images:t.refImages},...t.maskImage!=null&&{mask_image:t.maskImage},...t.strength!=null&&{strength:t.strength},...t.previewInterval!=null&&{preview:"vae",preview_interval:t.previewInterval}},s=await this.fetch(`${e.url}/sdcpp/v1/${t.video?"vid_gen":"img_gen"}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw Error(`The engine refused the job (HTTP ${s.status})`);let{id:o}=await s.json(),i=()=>void this.fetch(`${e.url}/sdcpp/v1/jobs/${o}/cancel`,{method:"POST"}).catch(()=>{});r.addEventListener("abort",i,{once:!0});try{let a=-1,c=-1;for(;;){if(r.aborted)return;let u=await(await this.fetch(`${e.url}/sdcpp/v1/jobs/${o}`)).json(),{completed:d,total:p,unit:f}=u.progress??{},m=u.preview?.b64_json&&u.preview.step!==c;if(u.status==="generating"&&f==="steps"&&p&&d!=null&&(d!==a||m)){if(a=d,m)c=u.preview?.step??c;yield{type:"progress",fraction:Math.min(1,d/p),message:"Generating",stage:"generating",step:Math.min(d,p),steps:p,...m&&{preview:{data:Uint8Array.from(Buffer.from(u.preview?.b64_json??"","base64")),mime:"image/png"}}}}if(u.status==="completed"){let h=t.video?u.result?.b64_json:u.result?.images?.[0]?.b64_json;if(!h){yield{type:"failed",error:"The engine produced no result",code:"engineNoResult"};return}yield{type:"completed",outputs:[{data:Uint8Array.from(Buffer.from(h,"base64")),mime:t.video?u.result?.mime_type??"video/webm":"image/png"}],costUsd:0};return}if(u.status==="failed"){let h=u.error?.message??"unknown error";yield{type:"failed",error:`The engine stopped: ${h}`,code:"engineStopped",params:{reason:h},retry:{attempts:2}};return}if(u.status==="cancelled")return;await Bun.sleep(250)}}finally{r.removeEventListener("abort",i)}}}import{mkdir as XU,rm as yb}from"fs/promises";import{basename as YU,dirname as y1,join as bb}from"path";function e9(e){let t=/<(?:lora|lyco|hypernet):/gi,r="",n=0;for(;;){t.lastIndex=n;let s=t.exec(e),o=s?e.indexOf(">",s.index):-1;if(!s||o<0)return r+e.slice(n);r+=`${e.slice(n,s.index)} `,n=o+1}}function w1(e,t){let r=e9(e).replace(/\s{2,}/g," ").trim(),n=t.filter((c)=>c.weight!==0);if(n.length===0)return r;let s=(c)=>new RegExp(`(^|[^\\p{L}\\p{N}])${c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}($|[^\\p{L}\\p{N}])`,"iu").test(r),o=[...new Set(n.map((c)=>c.trigger).filter((c)=>!!c&&!s(c)))],i=o.length?`${o.join(", ")}, ${r}`:r,a=n.map((c)=>`<lora:${c.id}:${Math.round(c.weight*100)/100}>`);return`${i} ${a.join(" ")}`}function vb(e){let t=t9[e];if(!t)throw Error(`No engine option for a ${e} file`);return t}function r9(e){return Math.max(1,Math.round(e/1073741824)-4)}function Fd(e){let t=e.model.defaults.vramBudget&&e.gpuMemoryBytes?["--max-vram",String(r9(e.gpuMemoryBytes))]:[];return[...e.model.defaults.engineArgs??[],...e.fit==="offload"?["--offload-to-cpu"]:[],...t]}function b1(e,t,r=64){let[n=1,s=1]=(t??"1:1").split(":").map(Number),o=(i)=>Math.max(r,Math.round(i/r)*r);return n>=s?{width:o(e),height:o(e*s/n)}:{width:o(e*n/s),height:o(e)}}function _b(e){return e.media==="image"&&e.defaults.references?.as==="init"&&e.defaults.upscale==null}function n9(e,t){return Math.max(e,Math.ceil(4/t))}function v1(e,t,r,n,s,o){let i=e.model.media==="video",{width:a,height:c}=s??b1(t.size,r.aspectRatio??t.aspectRatios[0],i?16:64),l=_b(e.model)&&n>0,u=l&&o,d=r.strength??(u?Fy:qy),p=l?n9(t.steps,d):t.steps;return{width:a,height:c,redrawing:l,masked:u,strength:d,steps:p}}async function s9(e,t,r,n,s,o=[],i,a,c=[]){if(t.upscale!=null){let[v]=o;if(!v)throw Error("An upscaler needs a picture");let _=["-M","upscale"];for(let[C,k]of Object.entries(e.files))_.push(vb(C),await s(k));return _.push("-i",await s(v),"-o",await s(n)),[..._,...Fd(e)]}let l=e.model.media==="video",{width:u,height:d,redrawing:p,masked:f,strength:m,steps:h}=v1(e,t,r,o.length,i,a!=null),g=["-M",l?"vid_gen":"img_gen"];for(let[v,_]of Object.entries(e.files))g.push(vb(v),await s(_));if(g.push("-p",w1(r.prompt,c),"--steps",String(h),"--cfg-scale",String(t.cfgScale),"-W",String(u),"-H",String(d),"-s",String(r.seed??Math.floor(Math.random()*2147483648)),"-o",await s(n)),t.sampler)g.push("--sampling-method",t.sampler);if(t.negativePrompt)g.push("-n",t.negativePrompt);if(t.flowShift!=null)g.push("--flow-shift",String(t.flowShift));if(t.references){let v=t.references.as==="init"?"-i":"-r";for(let _ of o.slice(0,t.references.max))g.push(v,await s(_))}if(p)g.push("--strength",String(m));if(f&&a)g.push("--mask",await s(a));let[w]=c;if(w)g.push("--lora-model-dir",await s(y1(w.path)));if(g.push(...Fd(e)),l){let v=t.fps??16,_=r.durationSeconds??t.durations?.[0]??2,C=Math.round(v*_/4)*4+1;g.push("--video-frames",String(C),"--fps",String(v))}return g}function o9(e){let t=e.match(/\|[=> ]*\|\s*(\d+)\/(\d+)\s+-\s+[\d.]+\s*(?:s\/it|it\/s)/);if(!t)return null;let r=Number(t[2]);return r>0?{step:Math.min(Number(t[1]),r),steps:r}:null}function a9(e,t,r){return new Promise((n,s)=>{let o=()=>{clearTimeout(a),t.removeEventListener("abort",i)},i=()=>{o(),s(t.reason)},a=setTimeout(()=>{o(),n(null)},r);if(t.aborted)return i();t.addEventListener("abort",i,{once:!0}),e.then((c)=>{o(),n(c)},()=>{o(),n(null)})})}function c9(e,t,r=0){if(!e)return null;let n=e.freeBytes+r;return n<t?Math.max(0,e.totalBytes-n):null}function h1(e,t){return t===0||e.previewsWhileFollowing!==!1}function g1(e){return e>1?Math.ceil(e/_1):null}function l9(e){let t=[73,69,78,68,174,66,96,130];return e.length>t.length&&t.every((r,n)=>e[e.length-t.length+n]===r)}function u9(e){let t=[];if(e.tasks.some((r)=>r==="text-to-image"||r==="text-to-video"))t.push("generate");if(e.defaults.references)t.push("edit");return t}function d9(e,t){let[r]=t.variants,n=r?.files.reduce((o,i)=>o+i.size,0)??0,s=n>0?Math.max(1,e.size/n):1;return{...t,id:d1(e.id),name:e.name,author:"",summary:"",homepage:"",license:"",licenseUrl:"",commercial:{kind:"none"},demos:[],profile:void 0,variants:r?[{...r,id:"file",label:"file",files:[],memoryBytes:Math.round(r.memoryBytes*s)}]:[],defaults:{...t.defaults,steps:e.steps,cfgScale:e.cfgScale,engineArgs:[...t.defaults.engineArgs??[],...e.clipSkip!=null?["--clip-skip",String(e.clipSkip)]:[]]}}}function p9(e){return bb(y1(e),YU(e).replace("sd-cli","sd-server"))}class Sb{id="local";name="This computer";requiresKey=!1;resumable=!1;maxConcurrency=1;onChange=null;installed=[];checkpoints=[];loading=Promise.resolve();store;catalog;spawn;windowsPath;warm;freeMemory;constructor(e){this.store=e.store,this.catalog=e.catalog,this.spawn=e.spawn??xb,this.windowsPath=e.windowsPath??Kc,this.freeMemory=e.freeMemory??(()=>Bd()),this.warm=e.warm??new gb({spawn:this.spawn,gpu:this.store.gpu}),this.store.subscribe((t)=>{if(t.type==="models.changed")this.load().catch(()=>{})})}async load(){let e=this.loading.then(()=>this.loadNow(),()=>this.loadNow());return this.loading=e.catch(()=>{}),e}async loadNow(){let t=(await this.store.list()).models.filter((a)=>a.ready).map((a)=>a.id),r=new Set(this.catalog.filter((a)=>t.includes(a.id)).flatMap((a)=>a.variants.map((c)=>c.engine))),n=(await this.store.checkpoints.list().catch(()=>[])).flatMap((a)=>{let c=this.catalog.find((l)=>l.id===u1[a.base]);return c?[d9(a,c)]:[]}).filter((a)=>a.variants.some((c)=>r.has(c.engine))),s=this.warm?this.warm.loaded?.split(":")[0]:null,o=[...t,...n.map((a)=>a.id)];if(this.warm&&s&&!o.includes(s))this.warm.stop();let i=JSON.stringify([this.installed,this.checkpoints]);if(this.installed=t,this.checkpoints=n,JSON.stringify([t,n])!==i)this.onChange?.()}lineOf(e){let t=e.replace(/^local\//,"");return this.spec(t)?.media??"image"}spec(e){return db(e)!=null?this.checkpoints.find((t)=>t.id===e):this.catalog.find((t)=>t.id===e)}listModels(){return[...this.catalog.filter((e)=>this.installed.includes(e.id)),...this.checkpoints].flatMap((e)=>e.media==="text"?[]:[{...e,media:e.media}]).map((e)=>({id:`local/${e.id}`,providerId:this.id,providerModelId:e.id,name:e.name,media:e.media,operations:u9(e),capabilities:{aspectRatios:e.defaults.upscale?[]:e.defaults.aspectRatios,seed:!0,maxCount:1,maxReferenceImages:e.defaults.references?.max??0,..._b(e)&&{strength:qy,mask:Fy},...e.defaults.upscale!=null&&{upscale:e.defaults.upscale},...e.defaults.durations&&{durations:e.defaults.durations},...e.englishPrompts&&{englishPrompts:!0},...e.loraBase&&{loraBase:e.loraBase}},pricing:{usdPerOutput:0},...e.profile&&{profile:e.profile}}))}async submit(e){let t={modelId:e.model.providerModelId,params:e.params},r=this.spec(t.modelId),n=e.params.loras??[];if(r&&n.length>0)t.loras=await this.checkLoras(r,n);let s=r?.defaults.references?.max??0;if(!r||e.references.length===0||s===0)return t;let[o]=e.references,i=(a)=>{let c=new Bun.Image(a);return c.metadata().then((l)=>({picture:c,...l})).catch(()=>{throw new O("The reference picture cannot be read","referenceUnreadable")})};if(r.defaults.upscale!=null&&o){let{picture:a,width:c,height:l}=await i(o.data),d=await(Math.max(c,l)>wb?a.resize(wb,wb,{fit:"inside"}):a).png().bytes();return t.pictures=[{data:d,extension:"png"}],t}if(_b(r)&&o){let{picture:a,width:c,height:l}=await i(o.data),u=b1(r.defaults.size,`${c}:${l}`);if(t.size=u,t.pictures=[{data:await a.resize(u.width,u.height,{fit:"fill"}).png().bytes(),extension:"png"}],e.mask){let d=await i(e.mask.data);t.mask=await d.picture.resize(u.width,u.height,{fit:"fill"}).png().bytes()}return t}return t.pictures=e.references.slice(0,s).map((a)=>({data:a.data,extension:a.mime.split("/")[1]??"png"})),t}async checkLoras(e,t){let r=[],n=null;for(let{id:s,weight:o}of t){let i=await this.store.loras.get(s);if(!e.loraBase||i.base!==e.loraBase){n=i.name;continue}if(!r.some((a)=>a.id===s))r.push({id:s,weight:o,trigger:i.trigger})}if(r.length>_c)throw new O(`At most ${_c} LoRAs can be used at once`,"tooManyLoras",{max:_c});if(r.length===0&&n)throw new O(`${n} is not made for ${e.name}`,"loraWrongBase",{lora:n,model:e.name});return r}async*events(e,t){let r=db(e.modelId),n=r!=null?this.spec(e.modelId):void 0;if(r!=null&&!n)throw new Ee("That model is no longer here","checkpointMissing",{id:r});let s=r!=null&&n?await this.store.checkpointRuntime(r,n):await this.store.runtime(e.modelId),o=s.model.media==="video";await XU(s.scratch,{recursive:!0});let i=bb(s.scratch,`${crypto.randomUUID()}.${o?"webm":"png"}`),a=s.throughWindows?this.windowsPath:async(d)=>d,c=p9(s.executable);if(this.warm&&!o&&!e.loras?.length&&!s.model.defaults.engineArgs?.includes("--clip-skip")&&s.model.defaults.upscale==null&&!s.throughWindows&&c!==s.executable&&await Bun.file(c).exists()){let d=s.model.defaults,p=(e.pictures??[]).map((P)=>Buffer.from(P.data).toString("base64")),{width:f,height:m,redrawing:h,masked:g,strength:w,steps:v}=v1(s,d,e.params,p.length,e.size,e.mask!=null),_=d.references?p.slice(0,d.references.max):[],C=d.references?.as==="init",k=[c];for(let[P,y]of Object.entries(s.files))k.push(vb(P),y);k.push(...Fd(s));try{yield*this.warm.run(`${s.model.id}:${s.variant.id}:${Fd(s).join(" ")}`,k,{video:!1,prompt:w1(e.params.prompt,[]),negativePrompt:d.negativePrompt,width:f,height:m,seed:e.params.seed??Math.floor(Math.random()*2147483648),steps:v,...C&&_[0]!=null&&{initImage:_[0]},...!C&&_.length>0&&{refImages:_},...g&&e.mask&&{maskImage:Buffer.from(e.mask).toString("base64")},...h&&{strength:w},cfgScale:d.cfgScale,sampler:d.sampler,flowShift:d.flowShift,previewInterval:h1(d,p.length)?g1(v)??void 0:void 0},t.signal,s.variant.memoryBytes,(P)=>this.warnIfSlow(s,t.signal,P));return}catch(P){if(t.signal.aborted)throw P}}let l=[],u=async(d,p)=>{let f=bb(s.scratch,`${crypto.randomUUID()}${p}`);return l.push(f),await Bun.write(f,d),f};try{let d=[];for(let m of e.pictures??[])d.push(await u(m.data,`.${m.extension}`));let p=e.mask&&await u(e.mask,"-mask.png"),f=yield*this.store.gpu.acquire(s.variant.memoryBytes,t.signal);try{yield*this.warnIfSlow(s,t.signal,0),yield*this.once(s,e,t,i,a,d,p)}finally{f.release()}}finally{for(let d of l)await yb(d,{force:!0})}}async*warnIfSlow(e,t,r){if(e.fit!=="gpu")return;let n=await a9(this.freeMemory().catch(()=>null),t,i9),s=c9(n,e.variant.memoryBytes,r+this.store.gpu.othersReserved());if(s!=null)yield{type:"progress",message:"Other programs are using graphics memory, so this may be slow",stage:"lowMemory",busyBytes:s}}async*once(e,t,r,n,s,o,i){let a=e.model.media==="video",c=[e.executable,...await s9(e,e.model.defaults,t.params,n,s,o,t.size,i,await this.engineLoras(t))],l=a?null:h1(e.model.defaults,o.length)?g1(e.model.defaults.steps):null,u=n.replace(/\.png$/,""),d=(w)=>`${u}-${String(w).padStart(3,"0")}.png`,p=0;if(l!=null)c.push("--preview","vae","--preview-interval",String(l),"--preview-path",await s(`${u}-%03d.png`));yield{type:"progress",message:"Loading the model",stage:"loading"};let f=this.spawn(c),m=new Promise((w,v)=>{let _=()=>{f.kill(),v(r.signal.reason)};if(r.signal.aborted)_();else r.signal.addEventListener("abort",_,{once:!0})});m.catch(()=>{});let h=f.output[Symbol.asyncIterator](),g=[];try{let w=-1;for(;;){let k=await Promise.race([h.next(),m]);if(k.done)break;let P=k.value;if(P.trim())g.push(P.trim());if(g.length>20)g.shift();let y=o9(P),x=y&&y.step/y.steps;if(y&&x!=null&&Math.floor(x*100)!==w){w=Math.floor(x*100);let T;while(l!=null){let I=await Bun.file(d(p)).bytes().catch(()=>null);if(!I||!l9(I))break;T={data:I,mime:"image/png"},p++}yield{type:"progress",fraction:x,message:"Generating",stage:"generating",step:y.step,steps:y.steps,...T&&{preview:T}}}}let v=await Promise.race([f.exited,m]);if(v!==0){let P=g.filter((x)=>/error|fail/i.test(x)).at(-1)?.replace(/^\[\w\]\s*/,""),y={attempts:2};yield P?{type:"failed",error:`The engine stopped: ${P}`,code:"engineStopped",params:{reason:P},retry:y}:{type:"failed",error:`The engine stopped with code ${v}`,code:"engineExitCode",params:{code:v},retry:y};return}let _=await Bun.file(n).bytes().catch(()=>null),C=_&&Yn(_);if(!_||!C){yield{type:"failed",error:"The engine produced no result",code:"engineNoResult"};return}yield{type:"completed",outputs:[{data:_,mime:C}],costUsd:0}}finally{f.kill(),await yb(n,{force:!0});for(let w=0;w<=p+_1;w++)await yb(d(w),{force:!0})}}async engineLoras(e){let t=[];for(let r of e.loras??[])await this.store.loras.get(r.id),t.push({...r,path:this.store.loras.path(r.id)});return t}async cancel(){}async unloadIdle(){if(this.warm===!1)return;if(this.warm.unused)await this.warm.stopAndWait()}close(){if(this.warm)this.warm.stop();this.store.gpu.close()}}var xb=(e)=>{let t=Bun.spawn(e,{stdin:"ignore",stdout:"pipe",stderr:"pipe"});async function*r(){let n=[],s={wake:null},o=()=>{s.wake?.(),s.wake=null},i=[t.stdout,t.stderr].map(async(c)=>{let l="";for await(let u of c.pipeThrough(new TextDecoderStream)){let d=(l+u).split(/[\r\n]/);l=d.pop()??"",n.push(...d),o()}if(l)n.push(l)}),a=!0;Promise.all(i).finally(()=>{a=!1,o()});while(a||n.length>0){let c=n.shift();if(c!=null){yield c;continue}await new Promise((l)=>{s.wake=l})}}return{output:r(),exited:t.exited,kill:()=>t.kill()}},Kc=async(e)=>{let t=Bun.spawn(["wslpath","-w",e],{stdout:"pipe"}),r=(await new Response(t.stdout).text()).trim();if(await t.exited!==0||!r)throw Error(`Could not translate ${e} for Windows`);return r},t9,wb=1536,i9=1500,_1=4;var Vd=b(()=>{Ar();Br();Ud();Gc();t9={model:"-m",diffusion_model:"--diffusion-model","high-noise-diffusion-model":"--high-noise-diffusion-model",vae:"--vae",taesd:"--taesd",clip_l:"--clip_l",clip_g:"--clip_g",clip_vision:"--clip_vision",t5xxl:"--t5xxl",llm:"--llm",llm_vision:"--llm_vision",tokenizer:"--tokenizer",upscale_model:"--upscale-model","embeddings-connectors":"--embeddings-connectors"}});import{mkdir as f9,rm as m9}from"fs/promises";import{basename as h9,dirname as g9,join as x1}from"path";async function S9(){let e=Bun.serve({hostname:"127.0.0.1",port:0,fetch:()=>new Response}),t=e.port;return e.stop(!0),t}function $9(e,t){return[`<|im_start|>system
|
|
76
|
+
${e}<|im_end|>`,`<|im_start|>user
|
|
77
|
+
${t}<|im_end|>`,`<|im_start|>assistant
|
|
78
|
+
`].join(`
|
|
79
|
+
`)}class kb{vision=!1;contextChars=12000;store;model;spawn;run;fetch;freePort;windowsPath;idleMs;server=null;idle;serverKey=null;inFlight=0;generation=0;constructor(e){this.store=e.store,this.model=e.model,this.spawn=e.spawn??xb,this.run=e.run??$b,this.fetch=e.fetch??((t,r)=>fetch(t,r)),this.freePort=e.freePort??S9,this.windowsPath=e.windowsPath??Kc,this.idleMs=e.idleMs??y9}async ready(){return(await this.store.list().catch(()=>null))?.models.find((t)=>t.id===this.model)?.ready??!1}toEnglish(e,t){return this.reply(Md,e,t,{temperature:0})}async reply(e,t,r,n={}){let s=await this.store.runtime(this.model),o={instructions:e,text:t,temperature:n.temperature??0};return s.throughWindows?this.once(s,o,r):this.served(s,o,r)}async chat(e,t,r,n){let s=await this.store.runtime(this.model);if(s.throughWindows)throw new le("The assistant on this computer runs only in the Windows app, not under WSL","localAssistantUnavailable");return ad(await this.completion(s,{messages:od(e,t,!1),...r.length>0&&{tools:id(r)},temperature:0.3,max_tokens:x9},n))}async served(e,t,r){let s=(await this.completion(e,{messages:[{role:"system",content:t.instructions},{role:"user",content:t.text}],temperature:t.temperature,max_tokens:S1},r)).choices?.[0]?.message?.content;if(typeof s!=="string")throw Error("No answer came back");return s}async completion(e,t,r){clearTimeout(this.idle),this.inFlight++;try{let n=await this.started(e);r.throwIfAborted();let s=await this.fetch(`${n.url}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:r});if(!s.ok)throw Error(`The language model refused (HTTP ${s.status})`);return await s.json()}finally{if(this.inFlight--,this.inFlight===0)clearTimeout(this.idle),this.idle=setTimeout(()=>this.stop(),this.idleMs),this.idle.unref?.()}}started(e){let t=`${e.executable}:${e.files.model}`;if(this.server&&this.serverKey!==t)this.stop();if(!this.server){let r=this.generation,n=this.start(t,e,r);this.server=n,this.serverKey=t,n.catch(()=>{if(this.server===n)this.forget()})}return this.server}forget(){this.server=null,this.serverKey=null}async start(e,t,r){let n=t.files.model;if(!n)throw Error("The translator has no model file");let s=await this.freePort(),o=this.spawn([t.executable,"-m",n,"--host","127.0.0.1","--port",String(s),"-c",String(_9),"-np","1"]);(async()=>{for await(let u of o.output);})().catch(()=>{});let i=!1,a=`http://127.0.0.1:${s}`,c={key:e,url:a,stop:()=>o.kill(),exited:o.exited};o.exited.then(()=>{i=!0,this.server?.then((u)=>{if(u===c)this.forget()})});let l=Date.now();for(;;){if(i)throw Error("The translator would not start");if(this.generation!==r)throw o.kill(),Error("The translator was stopped");if(Date.now()-l>w9)throw o.kill(),Error("The translator took too long to start");if((await this.fetch(`${a}/health`).catch(()=>null))?.ok)break;await Bun.sleep(b9)}return c}async once(e,t,r){let n=e.files.model;if(!n)throw Error("The translator has no model file");let s=x1(g9(e.executable),h9(e.executable).replace("llama-server","llama-completion"));await f9(e.scratch,{recursive:!0});let o=x1(e.scratch,`${crypto.randomUUID()}.prompt.txt`);await Bun.write(o,$9(t.instructions,t.text));try{let{code:i,stdout:a,stderr:c}=await this.run([s,"-m",await this.windowsPath(n),"-f",await this.windowsPath(o),"-no-cnv","--no-display-prompt","--temp",String(t.temperature),"-n",String(S1),"-c",String(v9),"--no-perf"],r);if(i!==0){let l=c.trim().split(/\r?\n/).at(-1);throw Error(`The translator stopped: ${l??`code ${i}`}`)}return a.replace(/\s*\[end of text\]\s*$/,"").trim()}finally{await m9(o,{force:!0})}}stop(){this.stopAndWait()}async stopAndWait(){clearTimeout(this.idle),this.generation++;let e=this.server;this.forget();let t=await e?.catch(()=>null);t?.stop(),await t?.exited}}var y9=300000,w9=120000,b9=250,S1=512,v9=2048,_9=8192,x9=1024,$b=async(e,t)=>{t.throwIfAborted();let r=Bun.spawn(e,{stdin:"ignore",stdout:"pipe",stderr:"pipe"}),n=()=>r.kill();t.addEventListener("abort",n,{once:!0});try{let[s,o,i]=await Promise.all([new Response(r.stdout).text(),new Response(r.stderr).text(),r.exited]);return t.throwIfAborted(),{code:i,stdout:s,stderr:o}}finally{t.removeEventListener("abort",n)}};var Tb=b(()=>{Ar();Fc();Vd()});import{mkdir as k9,rm as T9}from"fs/promises";import{basename as P9,dirname as E9,join as $1}from"path";function z9(e){let t=e.replace(/^\s*(caption|description)\s*:\s*/i,"").replace(/["\u201C\u201D]/g,"").replace(/\s+/g," ").trim().replace(/\.$/,"");if(t.length<=k1)return t;let r=t.slice(0,k1),n=r.lastIndexOf(",");return(n>0?r.slice(0,n):r).trim()}function M9(e){let t=e.trim().slice(0,R9);return[t?`The person asked for: "${t}".`:"The person asked for a picture.","In two or three sentences, in English: say what the picture shows, then say plainly whether it matches what was asked and what, if anything, is off (something missing, cut off, the wrong number of things, misspelled text)."].join(" ")}class Pb{store;model;run;windowsPath;constructor(e){this.store=e.store,this.model=e.model,this.run=e.run??$b,this.windowsPath=e.windowsPath??Kc}async ready(){return(await this.store.list().catch(()=>null))?.models.find((t)=>t.id===this.model)?.ready??!1}async look(e,t,r){let n=[];for(let s of e.slice(0,I9)){let o=await this.ask(s,M9(t),A9,r);n.push(s.label?`${s.label}: ${o}`:o)}return n.join(`
|
|
80
|
+
`)}async caption(e,t){return z9(await this.ask(e,O9,C9,t))}async ask(e,t,r,n){let s=await this.store.runtime(this.model),o=s.files.model,i=s.files.llm_vision;if(!o||!i)throw Error("The model that looks at pictures is incomplete");let a=s.throughWindows?this.windowsPath:async(d)=>d,c=$1(E9(s.executable),P9(s.executable).replace("llama-server","llama-mtmd-cli"));await k9(s.scratch,{recursive:!0});let l=e.mimeType.split("/")[1]??"jpeg",u=$1(s.scratch,`${crypto.randomUUID()}.look.${l}`);await Bun.write(u,Buffer.from(e.data,"base64"));try{let{code:d,stdout:p,stderr:f}=await this.run([c,"-m",await a(o),"--mmproj",await a(i),"--image",await a(u),"-p",t,"-n",String(r),"--temp","0.2","--no-perf"],n);if(d!==0){let m=f.trim().split(/\r?\n/).at(-1);throw Error(`Looking at the picture failed: ${m??`code ${d}`}`)}return p.replace(/\s+/g," ").trim()}finally{await T9(u,{force:!0})}}}var I9=2,A9=200,R9=500,C9=120,k1=400,O9="Write a caption for this picture, to train an image model with: one line in English of phrases of a few words each, separated by commas, such as: sitting on a wooden table, soft window light, close-up, plain gray background. Say where it is, what the subject does or how it is posed, what it wears or holds, the light, the framing and the background. Do not say who or what the main subject is, nor its colors or art style. No full sentences, no quotes.";var T1=b(()=>{Vd();Tb()});import{linkSync as N9,readFileSync as P1,renameSync as L9,rmSync as Zd,statSync as E1,writeFileSync as Hd}from"fs";import{dirname as D9,join as j9}from"path";function B9(e){let t=j9(e,`.clock-${crypto.randomUUID()}`);try{return Hd(t,""),E1(t).mtimeMs}finally{Zd(t,{force:!0})}}function Eb(e,t){try{let{mtimeMs:r}=E1(e);return B9(D9(e))-r<=t}catch{return!1}}function zi(e,t=Ib){return Eb(e,t)}function A1(e,t,r){try{return Hd(e,t,{flag:"wx"}),!0}catch(s){if(s.code!=="EEXIST")throw s}if(Eb(e,r))return!1;let n=`${e}.${crypto.randomUUID()}.stale`;try{L9(e,n)}catch{return!1}if(Eb(n,r)){try{N9(n,e)}catch{}return Zd(n,{force:!0}),!1}Zd(n,{force:!0});try{return Hd(e,t,{flag:"wx"}),!0}catch{return!1}}function R1(e,t,r){let n=setInterval(()=>{try{if(P1(e,"utf8")===t)Hd(e,t)}catch{}},r);return n.unref?.(),()=>{clearInterval(n);try{if(P1(e,"utf8")===t)Zd(e)}catch{}}}function Mi(e,t={}){let r=t.owner??crypto.randomUUID();if(!A1(e,r,t.staleMs??Ib))return null;return R1(e,r,t.heartbeatMs??I1)}async function Ab(e,t,r,n={}){let s=crypto.randomUUID(),o=n.staleMs??Ib;for(;;){if(t.throwIfAborted(),A1(e,s,o))break;await n.onWait?.(),await Bun.sleep(n.pollMs??U9)}let i=R1(e,s,n.heartbeatMs??I1);try{return await r()}finally{i()}}var Ib=30000,I1=5000,U9=1000;var Rb=()=>{};import{existsSync as M1}from"fs";import{homedir as q9}from"os";import{join as Wc,posix as Ni,win32 as ns}from"path";function C1(e,t,r,n){let s=t.join(e,Ds),o=t.join(e,es),i=(a)=>n.some((c)=>r(t.join(a,c)));return!i(s)&&i(o)?o:s}function Cb(e,t,r){let n=t.join(e,Ds),s=t.join(e,es);if(r(t.join(n,`${Ds}.sqlite`)))return n;if(r(t.join(s,`${es}.sqlite`)))return s;return r(s)?s:n}function Qt(e=process.platform,t=process.env,r=q9(),n=M1){let s=lt(t,"DATA_DIR");if(s)return s;if(e==="win32")return Cb(t.APPDATA??ns.join(r,"AppData","Roaming"),ns,n);if(e==="darwin")return Cb(Wc(r,"Library","Application Support"),Ni,n);return Cb(t.XDG_DATA_HOME??Wc(r,".local","share"),Ni,n)}function Jc(e){return/^\\\\\?\\[A-Za-z]:\\/.test(e)?e.slice(4):e}async function z1(e){try{let t=Bun.spawn(e,{stdout:"pipe",stderr:"ignore"}),[r,n]=await Promise.all([new Response(t.stdout).text(),t.exited]);return n===0?r.replaceAll("\r","").trim():null}catch{return null}}async function N1(e,t=process.platform,r=process.env,n=M1){let s=lt(r,"MODELS_DIR");if(s)return s;if(t==="win32")return r.LOCALAPPDATA?ns.join(C1(r.LOCALAPPDATA,ns,n,O1),"models"):ns.join(e,"models");if(t==="linux"&&(await qd({run:async()=>null})).wsl){let o=await z1(["cmd.exe","/c","echo","%LOCALAPPDATA%"]),i=o&&!o.includes("%")?await z1(["wslpath","-u",o]):null;if(i)return Wc(C1(i,Ni,n,O1),"models")}return Wc(e,"models")}function L1(e,t=process.platform,r=process.env){let n=lt(r,"TRAINER_DIR");if(n)return n;if(t==="win32"&&r.LOCALAPPDATA)return ns.join(r.LOCALAPPDATA,Ds,"trainer");return Wc(e,"trainer")}function Ob(e){let t=/^[A-Za-z]:\\/.test(e)?ns:Ni;return t.join(t.dirname(e),"models-location.json")}function Gd(e,t=process.platform){let r=e.match(/^([A-Za-z]):[\\/](.*)$/),n=e.match(/^\/mnt\/([a-z])(?:\/(.*))?$/);if(t==="win32"){if(r)return e;if(n)return ns.join(`${n[1]?.toUpperCase()}:\\`,...(n[2]??"").split("/").filter(Boolean));return null}if(r)return t==="linux"?Ni.join(`/mnt/${r[1]?.toLowerCase()}`,...(r[2]??"").split(/[\\/]/).filter(Boolean)):null;return Ni.isAbsolute(e)?e:null}function D1(e){let t=e.match(/^\/mnt\/([a-z])(?:\/(.*))?$/);if(!t)return e;return ns.join(`${t[1]?.toUpperCase()}:\\`,...(t[2]??"").split("/").filter(Boolean))}async function j1(e,t=process.platform){return await Bun.file(Ob(e)).json().then((s)=>typeof s.path==="string"?Gd(s.path,t):null).catch(()=>null)??e}var O1;var zb=b(()=>{Gc();O1=["models","models-location.json"]});import{mkdirSync as Mb,readdirSync as F9,readFileSync as V9,rmSync as Li,statSync as Nb,writeFileSync as Kd}from"fs";import{join as Lb}from"path";class Db{dir;owner=crypto.randomUUID();holds=new Set;heartbeat;capacity;known=null;staleMs;heartbeatMs;pollMs;constructor(e){this.dir=Lb(e.root,"gpu"),this.capacity=e.capacity,this.staleMs=e.staleMs??Z9,this.heartbeatMs=e.heartbeatMs??K9,this.pollMs=e.pollMs??W9}moveTo(e){if(this.dir=Lb(e,"gpu"),this.holds.size>0)try{this.publish()}catch{}}inUse(){if(this.holds.size>0)return!0;try{Mb(this.dir,{recursive:!0});let e=this.look(this.now(),!1);return e.others>0||e.waiters.length>0}catch{return!1}}othersReserved(){try{Mb(this.dir,{recursive:!0});let{others:e}=this.look(this.now(),!1);return Number.isFinite(e)?e:0}catch{return 0}}get reserved(){let e=0;for(let t of this.holds)e+=t.bytes;return e}file(e){return Lb(this.dir,e)}now(){let e=this.file(`clock-${this.owner}`);return Kd(e,""),Nb(e).mtimeMs}fits(e,t){return e<=0||e+t<=(this.known??0)}exclusive(e){let t=this.file("mutex");try{Kd(t,"",{flag:"wx"})}catch(r){if(r.code!=="EEXIST")throw r;try{if(this.now()-Nb(t).mtimeMs>G9)Li(t,{force:!0})}catch{}return null}try{return e(this.now())}finally{Li(t,{force:!0})}}look(e,t){let r=0,n=[];for(let s of F9(this.dir)){if(s==="mutex")continue;let o=this.file(s);try{let i=e-Nb(o).mtimeMs,a=s.startsWith("wait-");if(i>(a?H9:this.staleMs)){if(t)Li(o,{force:!0});continue}if(s.startsWith("clock-"))continue;let c=V9(o,"utf8");if(a){let[l,u]=c.split(":").map(Number);if(l&&Number.isFinite(u))n.push({id:s.slice(5),since:l,bytes:u??0})}else if(s!==this.owner){let l=Number(c);r+=c&&Number.isFinite(l)?l:1/0}}catch{}}return{others:r,waiters:n}}publish(){if(this.holds.size===0){Li(this.file(this.owner),{force:!0}),clearInterval(this.heartbeat),this.heartbeat=void 0;return}if(Kd(this.file(this.owner),String(this.reserved)),!this.heartbeat)this.heartbeat=setInterval(()=>this.beat(),this.heartbeatMs),this.heartbeat.unref?.()}beat(){try{this.publish(),this.letGoFor(this.look(this.now(),!1))}catch{}}letGoFor(e){let t=this.reserved+e.others;for(let r of[...this.holds]){if(!r.onWanted)continue;if(e.waiters.some((n)=>this.fits(t-r.bytes,n.bytes)))r.onWanted()}}wanted(e){try{let t=this.look(this.now(),!1),r=this.reserved+t.others-e;return t.waiters.some((n)=>this.fits(r,n.bytes))}catch{return!1}}async*acquire(e,t,r={}){Mb(this.dir,{recursive:!0}),this.known=await this.capacity().catch(()=>null);let n={bytes:e,onWanted:r.onWanted},s=crypto.randomUUID(),o=this.file(`wait-${s}`),i=null,a=0;try{for(;;){t.throwIfAborted();let l,u={others:0,waiters:[]};try{l=this.exclusive((d)=>{u=this.look(d,!0);let p=this.reserved+u.others;if(!this.fits(p,e))return!1;if(u.waiters.some((m)=>m.id!==s&&(i==null||m.since<i)&&this.fits(p,m.bytes)))return!1;this.holds.add(n);try{this.publish()}catch(m){throw this.holds.delete(n),m}return!0}),a=0}catch(d){if(++a>=U1)throw d;l=null}if(l)break;if(l===null){await Bun.sleep(J9);continue}try{if(i==null)i=this.now(),yield{type:"progress",message:"Waiting for the GPU",stage:"waitingGpu"};Kd(o,`${i}:${e}`),this.letGoFor({others:u.others,waiters:[{id:s,since:i,bytes:e}]})}catch(d){if(++a>=U1)throw d}await Bun.sleep(this.pollMs)}}finally{try{Li(o,{force:!0})}catch{}}let c=!1;return{release:()=>{if(c)return;c=!0,this.holds.delete(n);try{this.publish()}catch{}}}}close(){this.holds.clear();try{this.publish(),Li(this.file(`clock-${this.owner}`),{force:!0})}catch{}}}var Z9=30000,H9=5000,G9=5000,K9=5000,W9=1000,J9=20,U1=10;var B1=()=>{};import{copyFile as Q9,link as X9,mkdir as jb,readdir as Wd,rename as Ub,rm as Qc,rmdir as Y9,stat as Di}from"fs/promises";import{dirname as Bb,join as Lo}from"path";async function Qd(e){let t=await Di(e).catch(()=>null);if(!t)return 0;if(!t.isDirectory())return t.size;let r=0;for(let n of await Wd(e))r+=await Qd(Lo(e,n));return r}function qb(e){return e.endsWith(".lock")||e.endsWith(".stale")||e.endsWith(".moving")||e.endsWith(".tmp")||e.startsWith(".clock-")}async function Jd(e,t,r,n){n.signal?.throwIfAborted();let s=await Di(e,{bigint:!0}).catch(()=>null);if(!s)return;let o=await Di(t,{bigint:!0}).catch(()=>null);if(o&&o.dev===s.dev&&o.ino===s.ino){if(s.isDirectory())throw Error(`${t} is ${e} itself`);r.old.push(e),n.report(Number(s.size));return}if(s.isDirectory()){if(o&&!o.isDirectory())throw Error(`${t} is in the way`);if(o&&n.whole?.(e)){if(await q1(e,t)){r.old.push(e),n.report(await Qd(e));return}await Qc(t,{recursive:!0,force:!0}),o=null}if(!o&&n.whole?.(e)){let c=`${t}.${crypto.randomUUID()}.moving`,l={made:[],old:[]};try{await jb(c,{recursive:!0});for(let u of await Wd(e)){if(qb(u))continue;await Jd(Lo(e,u),Lo(c,u),l,n)}await Ub(c,t)}catch(u){throw await Qc(c,{recursive:!0,force:!0}),u}r.made.push(t),r.old.push(e);return}await jb(t,{recursive:!0});for(let c of await Wd(e)){if(qb(c))continue;await Jd(Lo(e,c),Lo(t,c),r,n)}return}let i=e.endsWith(".part")&&o&&s.size>o.size;if(o&&n.keep(e)&&!i){r.old.push(e),n.report(Number(s.size));return}let a=`${t}.${crypto.randomUUID()}.moving`;await jb(Bb(t),{recursive:!0});try{try{await X9(e,a)}catch{await Q9(e,a)}if(o)await Ub(a,t);else await Ub(a,t),r.made.push(t)}catch(c){throw await Qc(a,{force:!0}),c}r.old.push(e),n.report(Number(s.size))}async function q1(e,t){let[r,n]=await Promise.all([Di(e),Di(t)]);if(r.isDirectory()!==n.isDirectory())return!1;if(!r.isDirectory())return r.size===n.size;let s=(a)=>Wd(a).then((c)=>c.filter((l)=>!qb(l)).sort()),[o,i]=await Promise.all([s(e),s(t)]);if(o.join("/")!==i.join("/"))return!1;for(let a of o)if(!await q1(Lo(e,a),Lo(t,a)))return!1;return!0}async function F1(e){let t=[];for(let r of[...e.made].reverse())await Qc(r,{recursive:!0,force:!0}).catch(()=>{t.push(r)});return t}async function V1(e,t){let r=new Set;for(let n of e.old){let s=await Di(n).catch(()=>null);if(!s)continue;await Qc(n,{recursive:s.isDirectory(),force:!0}).catch(()=>{});for(let o=Bb(n);o.startsWith(t)&&o!==t;)r.add(o),o=Bb(o)}for(let n of[...r].sort((s,o)=>o.length-s.length))await Y9(n).catch(()=>{})}var Z1=()=>{};import{createReadStream as G1,createWriteStream as K1}from"fs";import{chmod as e5,mkdir as Xd,rename as W1,rm as Fb,stat as t5,symlink as r5}from"fs/promises";import{dirname as H1,join as n5,resolve as s5,sep as J1}from"path";import{Readable as Q1}from"stream";import{pipeline as Vb}from"stream/promises";import{createGunzip as o5,createGzip as i5}from"zlib";class X1{chunks;rest=Buffer.alloc(0);constructor(e){this.chunks=e[Symbol.asyncIterator]()}async next(e){while(this.rest.length===0){let{value:r,done:n}=await this.chunks.next();if(n)return null;this.rest=r}let t=this.rest.subarray(0,e);return this.rest=this.rest.subarray(t.length),t}async*take(e){for(let t=e;t>0;){let r=await this.next(t);if(!r)throw Error("The archive is truncated");t-=r.length,yield r}}async read(e){let t=[];for await(let r of this.take(e))t.push(r);return Buffer.concat(t,e)}async block(){let e=await this.next(Vr);if(!e)return null;if(e.length===Vr)return e;return Buffer.concat([e,await this.read(Vr-e.length)])}async skip(e){for await(let t of this.take(e));}async drain(){this.rest=Buffer.alloc(0);while(!(await this.chunks.next()).done);}}function Us(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return n.toString("utf8",0,s===-1?r:s)}function Yd(e,t,r){let n=e.subarray(t,t+r),s=n[0]??0;if(s&128){let i=s&127;for(let a of n.subarray(1))i=i*256+a;return i}let o=Us(e,t,r).trim();if(o==="")return 0;if(!/^[0-7]+$/.test(o))throw Error("The archive is damaged");return Number.parseInt(o,8)}function c5(e){let t=0;for(let r=0;r<Vr;r++)t+=r>=148&&r<156?32:e[r]??0;return t===Yd(e,148,8)}function l5(e){let t=new Map,r=0;while(r<e.length){let n=e.indexOf(32,r),s=Number(e.toString("utf8",r,n));if(n===-1||!Number.isInteger(s)||s<=0)break;let o=e.toString("utf8",n+1,r+s-1),i=o.indexOf("=");if(i>0)t.set(o.slice(0,i),o.slice(i+1));r+=s}return t}function u5(e,t){let r=t.split("/");if(t.startsWith("/")||t.includes("\\")||r.some((s)=>s===".."))throw Error(`The archive holds an unsafe path: ${t}`);let n=n5(e,...r.filter((s)=>s!==""&&s!=="."));if(n!==e&&!n.startsWith(e+J1))throw Error(`The archive holds an unsafe path: ${t}`);return n}async function ep(e,t){await Xd(t,{recursive:!0}),await eI(e,t)}async function Y1(e){return eI(e,null)}async function eI(e,t){let r=[];return await Vb(G1(e),o5(),async(n)=>{let s=new X1(n);await p5(s,t,r),await s.drain()}),r}async function p5(e,t,r){let n={};for(;;){let s=await e.block();if(!s||s.every((g)=>g===0))break;if(!c5(s))throw Error("The archive is damaged");let o=String.fromCharCode(s[156]??0),i=o==="x"||o==="g"||o==="L"||o==="K",a=i?Yd(s,124,12):n.size??Yd(s,124,12);if(!Number.isSafeInteger(a)||a<0)throw Error("The archive is damaged");let c=(Vr-a%Vr)%Vr;if(i){if(a>a5)throw Error("The archive holds an extended header too large");let g=await e.read(a);if(await e.skip(c),o==="x"){let w=l5(g),v=w.get("path"),_=w.get("linkpath"),C=w.get("size");n={...n,...v!=null&&{path:v},..._!=null&&{linkpath:_},...C!=null&&{size:Number(C)}}}else if(o==="L")n={...n,path:Us(g,0,g.length)};else if(o==="K")n={...n,linkpath:Us(g,0,g.length)};continue}let l=Us(s,257,5)==="ustar"?Us(s,345,155):"",u=n.path??(l?`${l}/${Us(s,0,100)}`:Us(s,0,100)),d=n.linkpath??Us(s,157,100);n={};let p=t??d5,f=u5(p,u);if(f===p&&o!=="5")throw Error(`The archive holds an unsafe path: ${u}`);let m=!d||d.includes("/")||d.includes("\\")||d==="."||d==="..",h=o==="0"||o==="\x00"||o==="7";if(o==="2"&&m)throw Error(`The archive holds an unsafe link: ${u}`);if(o!=="5"&&o!=="2"&&!h)throw Error(`${u} is a kind of file that is not supported`);if(f!==p)r.push({name:f.slice(p.length+1).split(J1).join("/"),type:o==="5"?"directory":o==="2"?"link":"file",size:h?a:0});if(t===null){await e.skip(a+c);continue}if(o==="5")await Xd(f,{recursive:!0}),await e.skip(a+c);else if(h){await Xd(H1(f),{recursive:!0});let g=`${f}.${crypto.randomUUID()}.tmp`;try{await Vb(Q1.from(e.take(a)),K1(g))}catch(w){throw await Fb(g,{force:!0}),w}await e.skip(c),await e5(g,Yd(s,100,8)&493),await W1(g,f)}else await Xd(H1(f),{recursive:!0}),await Fb(f,{force:!0}),await r5(d,f),await e.skip(a+c)}}function tI(e,t,r,n="0"){let s=Buffer.alloc(Vr),o=(c,l,u)=>{s.write(c,l,u,"utf8")},i=(c,l,u)=>o(`${c.toString(8).padStart(u-1,"0")}\x00`,l,u);o(e,0,100),i(r,100,8),i(0,108,8),i(0,116,8),i(t,124,12),i(Math.floor(Date.now()/1000),136,12),o(n,156,1),o("ustar\x00",257,6),o("00",263,2),s.fill(32,148,156);let a=0;for(let c of s)a+=c;return i(a,148,7),s}function f5(e){let t=` path=${e}
|
|
81
|
+
`,r=Buffer.byteLength(t)+1;while(Buffer.byteLength(`${r}${t}`)!==r)r++;let n=Buffer.from(`${r}${t}`);return[tI("PaxHeader",n.length,420,"x"),n,rI(n.length)]}async function nI(e,t,r={}){async function*n(){for(let o of t){let i=await t5(o.source),a=o.name.replaceAll("\\","/");if(Buffer.byteLength(a)>100)yield*f5(a);yield tI(Buffer.byteLength(a)>100?a.slice(-100):a,i.size,i.mode&493);let c=0;if(i.size>0)for await(let l of G1(o.source,{start:0,end:i.size-1}))c+=l.length,yield l;if(c!==i.size)throw Error(`${o.source} changed while it was being saved`);yield rI(i.size)}yield Buffer.alloc(Vr*2)}let s=`${e}.${crypto.randomUUID()}.tmp`;try{await Vb(Q1.from(n()),i5(),K1(s,{mode:r.mode??420})),await W1(s,e)}catch(o){throw await Fb(s,{force:!0}),o}}var Vr=512,a5=1048576,d5,rI=(e)=>Buffer.alloc((Vr-e%Vr)%Vr);var Zb=b(()=>{d5=s5("/nowhere")});import{mkdir as Hb,open as sI,rename as m5,rm as h5}from"fs/promises";import{dirname as g5,join as y5,sep as w5}from"path";import{Readable as b5,Transform as v5}from"stream";import{pipeline as _5}from"stream/promises";import{crc32 as x5,createInflateRaw as S5}from"zlib";async function Xc(e,t,r){let n=Buffer.alloc(r),{bytesRead:s}=await e.read(n,0,r,t);if(s!==r)throw Error("The archive is truncated");return n}async function I5(e,t){let r=Math.min(t,65557),n=await Xc(e,t-r,r),s=-1;for(let p=n.length-22;p>=0;p--)if(n.readUInt32LE(p)===$5){s=p;break}if(s===-1)throw Error("Not a zip archive");let o=n.readUInt16LE(s+10),i=n.readUInt32LE(s+12),a=n.readUInt32LE(s+16),c=s-20;if(c>=0&&n.readUInt32LE(c)===k5){let p=Number(n.readBigUInt64LE(c+8)),f=await Xc(e,p,56);if(f.readUInt32LE(0)!==T5)throw Error("The archive's zip64 record is damaged");o=Number(f.readBigUInt64LE(32)),i=Number(f.readBigUInt64LE(40)),a=Number(f.readBigUInt64LE(48))}if(a+i>t)throw Error("The archive is truncated");let l=await Xc(e,a,i),u=[],d=0;for(let p=0;p<o;p++){if(l.readUInt32LE(d)!==P5)throw Error("The archive's file list is damaged");let f=l.readUInt16LE(d+28),m=l.readUInt16LE(d+30),h=l.readUInt16LE(d+32),g=l.readUInt32LE(d+20),w=l.readUInt32LE(d+24),v=l.readUInt32LE(d+42),_=d+46+f,C=_+m;while(_+4<=C){let k=l.readUInt16LE(_),P=l.readUInt16LE(_+2);if(k===1){let y=_+4,x=()=>{let T=Number(l.readBigUInt64LE(y));return y+=8,T};if(w===Gb)w=x();if(g===Gb)g=x();if(v===Gb)v=x()}_+=4+P}u.push({name:l.toString("utf8",d+46,d+46+f),method:l.readUInt16LE(d+10),crc:l.readUInt32LE(d+16),compressedSize:g,size:w,headerOffset:v}),d+=46+f+m+h}return u}function A5(e,t){let r=t.replaceAll("\\","/").split("/");if(t.startsWith("/")||/^[a-zA-Z]:/.test(t)||r.some((s)=>s===".."))throw Error(`The archive holds an unsafe path: ${t}`);let n=y5(e,...r.filter((s)=>s!==""&&s!=="."));if(n!==e&&!n.startsWith(e+w5))throw Error(`The archive holds an unsafe path: ${t}`);return n}function oI(e){let t=0,r=0;return new v5({transform(n,s,o){if(t=x5(n,t),r+=n.length,r>e.size){o(Error(`${e.name} is larger than the archive says`));return}o(null,n)},flush(n){if(r!==e.size||t!==e.crc){n(Error(`${e.name} is damaged in the archive`));return}n()}})}async function Yc(e,t){let r=await sI(e,"r");try{let{size:n}=await r.stat(),s=await I5(r,n);await Hb(t,{recursive:!0});for(let o of s){let i=A5(t,o.name);if(o.name.endsWith("/")){await Hb(i,{recursive:!0});continue}if(o.method!==0&&o.method!==8)throw Error(`${o.name} uses a compression method that is not supported`);let a=await Xc(r,o.headerOffset,30);if(a.readUInt32LE(0)!==E5)throw Error("The archive is damaged");let c=o.headerOffset+30+a.readUInt16LE(26)+a.readUInt16LE(28);if(c+o.compressedSize>n)throw Error("The archive is truncated");await Hb(g5(i),{recursive:!0});let l=`${i}.${crypto.randomUUID()}.tmp`,u=await sI(l,"w");try{let d=b5.from(async function*(){for(let m=0;m<o.compressedSize;m+=1048576){let h=Math.min(1048576,o.compressedSize-m);yield await Xc(r,c+m,h)}}()),p=o.method===8?[S5(),oI(o)]:[oI(o)];await _5(d,...p,u.createWriteStream())}catch(d){throw await h5(l,{force:!0}),d}finally{await u.close().catch(()=>{})}await m5(l,i)}}finally{await r.close()}}var $5=101010256,k5=117853008,T5=101075792,P5=33639248,E5=67324752,Gb=4294967295;var Kb=()=>{};import{chmod as R5,mkdir as Bs,open as C5,readdir as ji,rename as el,rm as Sr,stat as tl,statfs as iI}from"fs/promises";import{dirname as tp,join as Ae,resolve as Xb}from"path";function O5(e,t){let r=(n)=>{let s=Xb(n);return process.platform==="win32"||s.startsWith("/mnt/")?s.toLowerCase():s};return r(e)===r(t)}async function cI(e,t){for(let r=tp(Xb(e));;r=tp(r)){let n=await tl(r,{bigint:!0}).catch(()=>null);if(n&&n.dev===t.dev&&n.ino===t.ino)return!0;if(r===tp(r))return!1}}function Wb(){return new O("Models are moving to another folder; try again once they are there","modelsMoving")}async function M5(e){try{let t=Bun.spawn([e,"--help"],{stdin:"ignore",stdout:"ignore",stderr:"pipe"}),r=setTimeout(()=>t.kill(),z5),[n,s]=await Promise.all([t.exited,new Response(t.stderr).text()]);if(clearTimeout(r),n===0)return null;return s.trim().split(/\r?\n/).at(-1)||`it stopped with code ${n}`}catch(t){return t instanceof Error?t.message:String(t)}}function Do(e){if(e<1000)return`${e} B`;if(e<1e6)return`${Math.round(e/1000)} kB`;if(e<1e9)return`${Math.round(e/1e6)} MB`;return`${(e/1e9).toFixed(e<10000000000?2:1)} GB`}function dI(e,t){if(e.length===0)throw Error(`${t} has no files`);if(new Set(e.map((r)=>r.name)).size!==e.length)throw Error(`Repeated file name in ${t}`);for(let r of e){if(!r.url.startsWith("https://"))throw Error(`Not an HTTPS URL: ${r.url}`);if(!/^[a-f0-9]{64}$/.test(r.sha256))throw Error(`Invalid hash for ${r.name} of ${t}`);if(!Number.isInteger(r.size)||r.size<=0)throw Error(`Invalid size for ${r.name} of ${t}`)}}function N5(e,t){let r=new Map,n=(i,a)=>{for(let c of i){if((r.get(c.sha256)??c.size)!==c.size)throw Error(`One hash, two sizes: ${c.name} of ${a}`);r.set(c.sha256,c.size)}},s=new Set;for(let i of t)for(let a of i.builds){if(!Jb.test(a.id)||s.has(a.id))throw Error(`Invalid or repeated engine build id: ${a.id}`);if(s.add(a.id),a.engine!==i.id)throw Error(`Build ${a.id} belongs to another engine`);let c=a.executable.split(/[\\/]/);if(a.executable.startsWith("/")||c.includes(".."))throw Error(`Unsafe executable path in build ${a.id}`);dI(a.files,`build ${a.id}`),n(a.files,`build ${a.id}`)}let o=new Set;for(let i of e){if(!Jb.test(i.id)||o.has(i.id))throw Error(`Invalid or repeated local model id: ${i.id}`);if(o.add(i.id),i.variants.length===0)throw Error(`Local model without variants: ${i.id}`);let a=new Set;for(let c of i.variants){let l=`${i.id} (${c.id})`;if(!Jb.test(c.id)||a.has(c.id))throw Error(`Invalid or repeated variant id: ${l}`);if(a.add(c.id),!t.some((u)=>u.id===c.engine))throw Error(`Unknown engine ${c.engine} for ${l}`);dI(c.files,l),n(c.files,l)}for(let c of i.demos)if(!c.url.startsWith("https://"))throw Error(`Not an HTTPS URL: ${c.url}`)}}async function L5(e,t,r){let n=await new Bun.Image(Bun.file(e)).resize(r,r,{fit:"inside",withoutEnlargement:!0}).webp({quality:82}).bytes(),s=`${t}.${crypto.randomUUID()}.tmp`;try{await Bun.write(s,n),await el(s,t)}catch(o){throw await Sr(s,{force:!0}),o}return!0}async function mI(e){let t=0;for(let r of await ji(e,{withFileTypes:!0}).catch(()=>[])){let n=Ae(e,r.name);t+=r.isDirectory()?await mI(n):await Ui(n)}return t}class Yb{root;catalog;engines;fetch;detect;gpuMemory;memoryRead=null;hardware=null;checkEngine;broken=new Set;providedBroken=new Set;lastReady=null;listeners=new Set;installs=new Map;errors=new Map;demos=new Map;unshrinkable=new Set;queue=Promise.resolve();gpu;loras;checkpoints;locationFile;enginesDir;moving=null;moveTask=Promise.resolve();relocating=!1;holders=new Set;moveError=null;constructor(e){N5(e.catalog,e.engines),this.root=e.root,this.locationFile=e.locationFile??null,this.enginesDir=e.enginesDir?Xb(e.enginesDir):null,this.catalog=e.catalog,this.engines=e.engines,this.fetch=e.fetch??globalThis.fetch,this.detect=e.hardware??(()=>qd()),this.gpuMemory=e.gpuMemory??(e.hardware?async()=>null:()=>Bd()),this.checkEngine=e.checkEngine??M5,this.loras=new lb({root:()=>this.root,check:()=>this.notMoving(),changed:()=>this.emit({type:"loras.changed"})}),this.checkpoints=new pb({root:()=>this.root,check:()=>this.notMoving(),changed:()=>this.emit({type:"models.changed"}),release:()=>this.letGo()}),this.gpu=new Db({root:this.root,capacity:async()=>{let{gpus:t}=await this.machine();return t.length>0?Math.max(...t.map((r)=>r.memoryBytes))*D5:null}})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){console.error("A local model listener failed",r)}}machine(){return this.hardware??=Promise.all([this.detect(),this.loadBroken(),this.checkProvided()]).then(([e])=>e),this.hardware}freeMemory(){let e=Date.now();if(!this.memoryRead||e-this.memoryRead.at>j5)this.memoryRead={at:e,memory:this.gpuMemory().catch(()=>null)};return this.memoryRead.memory}async listWithMemory(){let e=await this.list(),t=e.hardware.gpus[0];if(t?.vendor!=="nvidia")return e;let r=await this.freeMemory();if(!r)return e;return{...e,hardware:{...e.hardware,gpus:[{...t,freeBytes:r.freeBytes},...e.hardware.gpus.slice(1)]}}}async checkProvided(){for(let e of this.engines.flatMap((t)=>t.builds)){let t=await this.providedEngineDir(e);if(!t)continue;let r=await this.checkEngine(Ae(t,...e.executable.split(/[\\/]/)));if(r)console.warn(`${e.id} from ${this.enginesDir} does not run: ${r}`),this.providedBroken.add(e.id)}}brokenFile(){return Ae(this.root,"broken-engines.json")}async loadBroken(){let e=await Bun.file(this.brokenFile()).json().catch(()=>[]);if(Array.isArray(e)){for(let t of e)if(typeof t==="string")this.broken.add(t)}}async markBroken(e){this.broken.add(e),await Bs(this.root,{recursive:!0}),await Bun.write(this.brokenFile(),JSON.stringify([...this.broken]))}spec(e){let t=this.catalog.find((r)=>r.id===e);if(!t)throw new Ee(`Unknown local model: ${e}`,"unknownLocalModel",{model:e});return t}blob(e){return Ae(this.root,"blobs",e)}marker(e){return Ae(this.root,"installed",e)}engineDir(e){return Ae(this.root,"engines",e)}async providedEngineDir(e){if(!this.enginesDir||this.providedBroken.has(e.id))return null;let t=Ae(this.enginesDir,e.id);return(await tl(Ae(t,...e.executable.split(/[\\/]/))).catch(()=>null))?.isFile()?t:null}async installedEngineDir(e){return await this.providedEngineDir(e)??this.engineDir(e.id)}chooser(e){let t=new Map;return(r)=>{if(!t.has(r)){let n=(this.engines.find((s)=>s.id===r)?.builds??[]).filter((s)=>!this.broken.has(s.id)&&!this.providedBroken.has(s.id));t.set(r,p1(r,n,e))}return t.get(r)??null}}async onDisk(){let e=new Set,t=new Map,r=Ae(this.root,"blobs");for(let n of await ji(r).catch(()=>[]))if(/^[a-f0-9]{64}$/.test(n))e.add(n);else if(/^[a-f0-9]{64}\.part$/.test(n))t.set(n.slice(0,64),await Ui(Ae(r,n)));return{complete:e,partial:t}}async installedVariants(e){let t=new Map;for(let r of await ji(Ae(this.root,"installed")).catch(()=>[])){let n=this.catalog.find((a)=>a.id===r);if(!n)continue;let s=await Bun.file(this.marker(r)).text().catch(()=>""),o;try{o=JSON.parse(s).variant}catch{}let i=n.variants.find((a)=>a.id===o)??n.variants.find((a)=>a.files.every((c)=>e.has(c.sha256)));if(i)t.set(r,i)}return t}async installedBuilds(){let e=this.engines.flatMap((s)=>s.builds),t=new Set(e.map((s)=>s.id)),r=await ji(Ae(this.root,"engines")).catch(()=>[]),n=new Set(r.filter((s)=>t.has(s)));for(let s of e)if(await this.providedEngineDir(s))n.add(s.id);return n}async neededHashes(){let e=await this.onDisk(),t=new Set,r=[...(await this.installedVariants(e.complete)).values(),...[...this.installs.values()].map((s)=>s.variant)],n=Ae(this.root,"installed");for(let s of await ji(n).catch(()=>[])){if(!s.endsWith(".lock")||!zi(Ae(n,s)))continue;let o=this.catalog.find((i)=>`${i.id}.lock`===s);if(o)r.push(...o.variants)}for(let s of r)for(let o of s.files)t.add(o.sha256);return t}async list(){await this.follow();let e=await this.machine(),t=await this.onDisk(),[r,n]=await Promise.all([this.installedVariants(t.complete),this.installedBuilds()]),s=this.chooser(e),o=(m)=>{if(t.complete.has(m.sha256))return m.size;for(let h of this.installs.values())if(h.current?.sha256===m.sha256)return h.current.bytes;return Math.min(t.partial.get(m.sha256)??0,m.size)},i=new Map;for(let m of n)i.set(m,await mI(this.engineDir(m)));let a=(m,h)=>[...r,...[...this.installs].map(([g,w])=>[g,w.variant])].filter(([g,w])=>g!==h&&w.engine===m).map(([g])=>g),c=(m)=>{let h=fb(m,e,s),g=fb(m.filter((w)=>w.files.every((v)=>t.complete.has(v.sha256))),e,s);return(g&&g.fit===h?.fit?g:h)?.variant},l=this.catalog.map((m)=>{let{variants:h,demos:g,defaults:w,...v}=m,_=this.installs.get(m.id),C=_?.variant??r.get(m.id),k=C??c(h)??null,P=k?s(k.engine)?.build:void 0,y=P!=null&&!n.has(P.id),x=k?ss(k.files):[],T=y&&P?ss(P.files):[],I=new Set;for(let[de,qe]of r)if(de!==m.id)for(let Ye of qe.files)I.add(Ye.sha256);for(let[de,qe]of this.installs)if(de!==m.id)for(let Ye of qe.variant.files)I.add(Ye.sha256);let j=ss(h.flatMap((de)=>de.files)).filter((de)=>!I.has(de.sha256)),se=C!=null&&P!=null&&n.has(P.id)&&a(C.engine,m.id).length===0,we=this.errors.get(m.id);return{...v,state:_?.state??(r.has(m.id)?"installed":"available"),variants:h.map(({files:de,...qe})=>({...qe,fit:Oi(qe,e,s(qe.engine)),size:En(ss(de).map((Ye)=>Ye.size)),files:de.map((Ye)=>({name:Ye.name,size:Ye.size,present:t.complete.has(Ye.sha256)}))})),variant:k?.id??null,installed:r.has(m.id),ready:r.has(m.id)&&P!=null&&!y,demos:g.map(({url:de,...qe})=>qe),size:En([...x,...T].map((de)=>de.size)),receivedBytes:En([...x,...T].map(o)),reclaimableBytes:En(j.map(o))+(se&&P?i.get(P.id)??0:0),...we&&{error:we.message,...we.code&&{errorCode:we.code},...we.params&&{errorParams:we.params}}}}),u=this.engines.flatMap((m)=>{let h=s(m.id);if(!h)return[];let{build:g,throughWindows:w}=h,v=n.has(g.id);return[{engine:m.id,name:m.name,build:g.id,version:g.version,backend:g.backend,throughWindows:w,installed:v,size:v?i.get(g.id)??0:En(ss(g.files).map((_)=>_.size)),usedBy:a(m.id)}]}),d=new Map([...this.catalog.flatMap((m)=>m.variants.flatMap((h)=>h.files)),...this.engines.flatMap((m)=>m.builds.flatMap((h)=>h.files))].map((m)=>[m.sha256,m.size])),p=En([...i.values()]);for(let m of t.complete)p+=d.get(m)??await Ui(this.blob(m));for(let m of t.partial.values())p+=m;let f=l.filter((m)=>m.ready).map((m)=>m.id).join();if(this.lastReady!=null&&f!==this.lastReady)this.lastReady=f,this.emit({type:"models.changed"});return this.lastReady=f,{hardware:e,engines:u,models:l,disk:{path:this.root,freeBytes:await this.freeBytes(),usedBytes:p,changeable:this.locationFile!=null,moving:this.moving,moveError:this.moveError}}}async freeBytes(){await Bs(this.root,{recursive:!0});let e=await iI(this.root);return e.bavail*e.bsize}async relocate(e){if(this.moving||this.relocating)throw Wb();this.relocating=!0;try{await this.startMove(e)}finally{this.relocating=!1}}async startMove(e){let t=this.locationFile;if(!t)throw new O("The models folder is set from outside Hatchlight","modelsFolderFixed");let r=Gd(e.trim());if(!r)throw new O(`Not a full path: ${e}`,"folderNotAbsolute",{path:e});if(process.platform==="linux"&&t.startsWith("/mnt/")&&!/^\/mnt\/[a-z](\/|$)/.test(r))throw new O(`Windows cannot reach ${r}`,"folderNotShared",{path:r});try{await Bs(r,{recursive:!0});let c=Ae(r,`.hatchlight-${crypto.randomUUID()}`);await Bun.write(c,""),await Sr(c)}catch{throw new O(`Cannot write to ${r}`,"folderNotWritable",{path:r})}await Bs(this.root,{recursive:!0});let[n,s]=await Promise.all([tl(this.root,{bigint:!0}),tl(r,{bigint:!0})]);if(n.dev===s.dev&&n.ino===s.ino)return;if(await cI(r,n)||await cI(this.root,s))throw new O("The new folder cannot hold the current one, nor sit inside it","folderInside",{path:r});let o=Mi(Ae(this.root,"moving.lock")),i=o&&Mi(Ae(r,"moving.lock")),a=()=>{o?.(),i?.()};if(!o||!i)throw a(),Wb();await this.letGo();try{let c=async(p)=>(await ji(Ae(this.root,p)).catch(()=>[])).some((f)=>f.endsWith(".lock")&&zi(Ae(this.root,p,f)));if(this.installs.size>0||this.gpu.inUse()||this.loras.busy||this.checkpoints.busy||await c("blobs")||await c("engines")||await c("installed"))throw new O("Models are in use; try again once nothing is installing or generating","modelsBusy");let u=0;for(let p of aI)u+=await Qd(Ae(this.root,p));if(n.dev!==s.dev){let p=await iI(r),f=p.bavail*p.bsize;if(u>f)throw new O(`Not enough disk space: ${Do(u)} needed, ${Do(f)} free`,"notEnoughDisk",{neededBytes:u,freeBytes:f})}let d={to:r,movedBytes:0,totalBytes:u};this.moving=d,this.moveError=null,this.emit({type:"models.moving",...d}),this.moveTask=this.move(r,t,d,a)}catch(c){throw a(),c}}async move(e,t,r,n){let s=this.root,o=0,i=(c)=>{r.movedBytes+=c;let l=Date.now();if(l-o<uI)return;o=l,this.emit({type:"models.moving",...r})},a={made:[],old:[]};try{for(let l of aI)await Jd(Ae(s,l),Ae(e,l),a,{report:i,keep:(u)=>!u.startsWith(Ae(s,"installed"))&&!u.endsWith("broken-engines.json"),whole:(u)=>tp(u)===Ae(s,"engines")});let c=`${t}.${crypto.randomUUID()}.tmp`;await Bun.write(c,JSON.stringify({path:D1(e)})),await el(c,t)}catch(c){let l=await F1(a),u=c instanceof Error?c.message:String(c);this.moveError=$s(new le(`Could not move the models: ${u}`,l.length>0?"modelsMoveLeftCopies":"modelsMoveFailed",{reason:u,path:e})),this.moving=null,n(),this.emit({type:"models.changed"});return}this.switchTo(e),await V1(a,s),this.moving=null,n(),this.emit({type:"models.changed"})}notMoving(){if(this.moving||this.relocating||zi(Ae(this.root,"moving.lock")))throw Wb()}async follow(){if(!this.locationFile||this.moving||this.relocating||this.installs.size>0||this.gpu.reserved>0)return;let e=await Bun.file(this.locationFile).json().then((t)=>typeof t.path==="string"?Gd(t.path):null).catch(()=>null);if(e&&!O5(e,this.root))this.switchTo(e)}switchTo(e){this.root=e,this.gpu.moveTo(e),this.emit({type:"models.changed"})}async runtime(e){let t=this.spec(e);await this.follow(),this.notMoving();let r=await this.onDisk(),n=(await this.installedVariants(r.complete)).get(e);if(!n)throw new O(`${t.name} is not installed`,"notInstalled",{model:t.name});let s=await this.machine(),o=this.chooser(s)(n.engine);if(!o||!(await this.installedBuilds()).has(o.build.id))throw new O(`The engine for ${t.name} is not installed. Install the model again.`,"engineMissing",{model:t.name});let i=await this.installedEngineDir(o.build);return{model:t,variant:n,build:o.build,executable:Ae(i,...o.build.executable.split(/[\\/]/)),throughWindows:o.throughWindows,fit:Oi(n,s,o),...o.gpu&&{gpuMemoryBytes:o.gpu.memoryBytes},scratch:Ae(this.root,"tmp"),files:Object.fromEntries(n.files.map((a)=>[a.role??a.name,this.blob(a.sha256)]))}}async checkpointRuntime(e,t){await this.follow(),this.notMoving();let[r]=t.variants;if(await this.checkpoints.get(e),!r)throw Error(`${t.name} has no variant`);let n=await this.machine(),s=this.chooser(n)(r.engine);if(!s||!(await this.installedBuilds()).has(s.build.id))throw new O(`${t.name} needs the engine of the Stable Diffusion models. Install one of them first.`,"checkpointNeedsEngine",{model:t.name});let o=await this.installedEngineDir(s.build);return{model:t,variant:r,build:s.build,executable:Ae(o,...s.build.executable.split(/[\\/]/)),throughWindows:s.throughWindows,fit:Oi(r,n,s),...s.gpu&&{gpuMemoryBytes:s.gpu.memoryBytes},scratch:Ae(this.root,"tmp"),files:{model:this.checkpoints.path(e)}}}async install(e,t){let r=this.spec(e);if(this.installs.has(e))return;this.notMoving();let n=await this.list(),s=n.models.find((w)=>w.id===e);if(s.ready)return;let o=await this.machine(),i=this.chooser(o),a;if(s.installed){if(a=r.variants.find((w)=>w.id===s.variant),!a)throw Error(`${r.name} has no variant installed`)}else if(t){if(a=r.variants.find((w)=>w.id===t),!a)throw new Ee(`Unknown variant: ${t}`,"unknownVariant",{variant:t});if(Oi(a,o,i(a.engine))==="none")throw new O(`${r.name} (${a.label}) does not run on this machine`,"variantDoesNotRun",{model:r.name,variant:a.label})}else if(a=r.variants.find((w)=>w.id===s.variant),!a)throw new O(`${r.name} does not run on this machine`,"modelDoesNotRun",{model:r.name});let c=i(a.engine)?.build,l=await this.installedBuilds(),u=await this.onDisk(),d=new Set([...this.installs.values()].map((w)=>i(w.variant.engine)?.build.id)),p=(w)=>w.size-Math.min(u.partial.get(w.sha256)??0,w.size),m=(l.has(c.id)||d.has(c.id)?0:En(ss(c.files).map(p))+En(ss(c.files).map((w)=>w.size))*2)+En(ss(a.files).filter((w)=>!u.complete.has(w.sha256)).map(p))+En(n.models.filter((w)=>this.installs.has(w.id)).map((w)=>w.size-w.receivedBytes));if(m>n.disk.freeBytes)throw new O(`Not enough disk space: ${Do(m)} needed, ${Do(n.disk.freeBytes)} free`,"notEnoughDisk",{neededBytes:m,freeBytes:n.disk.freeBytes});let h={state:"queued",controller:new AbortController,variant:a,current:null,startedAt:0,transferred:0,lastProgress:0};this.installs.set(e,h),this.errors.delete(e),this.emit({type:"models.changed"});let g=async()=>{if(this.installs.get(e)!==h)return;let w=null;try{await Bs(Ae(this.root,"installed"),{recursive:!0}),w=Mi(Ae(this.root,"installed",`${e}.lock`)),h.state="downloading",h.startedAt=Date.now(),this.emit({type:"models.changed"});let v=c;while(!(await this.installedBuilds()).has(v.id))try{await this.installEngine(r,v,h)}catch(_){if(!(_ instanceof Qb))throw _;await this.markBroken(v.id);let C=this.chooser(await this.machine())(a.engine);if(!C)throw new le(`The engine does not run on this computer: ${_.message}`,"engineDoesNotRun",{reason:_.message});v=C.build}for(let _ of a.files)await this.download(r,_,h);await Bun.write(this.marker(e),JSON.stringify({variant:a.id}))}catch(v){if(!h.controller.signal.aborted)this.errors.set(e,$s(v))}finally{w?.(),this.installs.delete(e),this.emit({type:"models.changed"})}};this.queue=this.queue.then(g)}async installEngine(e,t,r){await Bs(Ae(this.root,"engines"),{recursive:!0}),await Ab(`${this.engineDir(t.id)}.lock`,r.controller.signal,async()=>{if((await this.installedBuilds()).has(t.id))return;await this.unpackEngine(e,t,r)})}async unpackEngine(e,t,r){for(let i of t.files)await this.download(e,i,r);r.state="verifying",this.progress(e,r,!0);let n=this.engineDir(t.id),s=`${n}.${crypto.randomUUID()}.tmp`;try{for(let i of t.files)r.controller.signal.throwIfAborted(),await(/\.(tar\.gz|tgz)$/.test(i.name)?ep:Yc)(this.blob(i.sha256),s).catch((c)=>{throw new le(c instanceof Error?c.message:String(c),"engineUnpackFailed")});await R5(Ae(s,...t.executable.split(/[\\/]/)),493),await el(s,n)}finally{await Sr(s,{recursive:!0,force:!0})}let o=await this.checkEngine(Ae(n,...t.executable.split(/[\\/]/)));if(o){await Sr(n,{recursive:!0,force:!0});for(let i of t.files)await Sr(this.blob(i.sha256),{force:!0});throw new Qb(o)}for(let i of t.files)await Sr(this.blob(i.sha256),{force:!0})}progress(e,t,r=!1){let n=Date.now();if(!r&&n-t.lastProgress<uI)return;t.lastProgress=n,this.list().catch(()=>null).then((s)=>{if(!s)return;let o=s.models.find((a)=>a.id===e.id);if(!o||this.installs.get(e.id)!==t)return;let i=Math.max((n-t.startedAt)/1000,0.001);this.emit({type:"model.progress",id:e.id,state:t.state,receivedBytes:o.receivedBytes,size:o.size,bytesPerSecond:Math.round(t.transferred/i)})})}async download(e,t,r){let n=this.blob(t.sha256);if(await Bun.file(n).exists())return;this.notMoving(),await Bs(Ae(this.root,"blobs"),{recursive:!0}),await Ab(`${n}.lock`,r.controller.signal,async()=>{if(await Bun.file(n).exists())return;await this.fetchFile(e,t,r)},{onWait:async()=>{r.state="downloading",r.current={sha256:t.sha256,bytes:await Ui(`${n}.part`)},this.progress(e,r,!0)}})}async fetchFile(e,t,r){let{signal:n}=r.controller,s=this.blob(t.sha256),o=`${s}.part`,i=await Ui(o);if(i>t.size)await Sr(o,{force:!0}),i=0;if(r.state="downloading",r.current={sha256:t.sha256,bytes:i},i<t.size){let c=await this.fetch(t.url,{headers:i>0?{range:`bytes=${i}-`}:{},signal:n});if(!c.ok||!c.body)throw new le(`Could not download ${t.name} (HTTP ${c.status})`,"downloadFailed",{file:t.name,status:c.status});let l=c.status===206;if(!l)r.current.bytes=0;let u=await C5(o,l?"r+":"w");try{for await(let d of c.body){if(r.current.bytes+d.byteLength>t.size)throw new le(`${t.name} is larger than expected`,"downloadTooLarge",{file:t.name});await u.write(d,0,d.byteLength,r.current.bytes),r.current.bytes+=d.byteLength,r.transferred+=d.byteLength,this.progress(e,r)}}finally{await u.close()}if(n.throwIfAborted(),r.current.bytes!==t.size||await Ui(o)!==t.size)throw new le(`The download of ${t.name} was cut short`,"downloadCutShort",{file:t.name})}r.state="verifying",this.progress(e,r,!0);let a=new Bun.CryptoHasher("sha256");for await(let c of Bun.file(o).stream())n.throwIfAborted(),a.update(c);if(a.digest("hex")!==t.sha256)throw await Sr(o,{force:!0}),new le(`${t.name} did not match its expected hash`,"hashMismatch",{file:t.name});await el(o,s),r.current=null,r.state="downloading"}async cancel(e){this.spec(e);let t=this.installs.get(e);if(!t)return;if(t.controller.abort(),t.state==="queued"){this.installs.delete(e),this.emit({type:"models.changed"});return}await this.settled(e)}async settled(e){while(this.installs.has(e))await new Promise((t)=>{let r=this.subscribe((n)=>{if(n.type!=="models.changed")return;r(),t()})})}onLetGo(e){this.holders.add(e)}async letGo(){for(let e of this.holders)await e().catch(()=>{})}async remove(e){let t=this.spec(e);this.notMoving(),await this.cancel(e),await this.letGo(),this.errors.delete(e),await Sr(this.marker(e),{force:!0});let r=await this.neededHashes();for(let n of ss(t.variants.flatMap((s)=>s.files))){if(r.has(n.sha256))continue;if(zi(`${this.blob(n.sha256)}.lock`))continue;await Sr(this.blob(n.sha256),{force:!0}),await Sr(`${this.blob(n.sha256)}.part`,{force:!0})}await this.removeUnusedEngines(),this.emit({type:"models.changed"})}async removeUnusedEngines(){let e=await this.onDisk(),t=new Set([...(await this.installedVariants(e.complete)).values(),...[...this.installs.values()].map((r)=>r.variant)].map((r)=>r.engine));for(let r of this.engines){if(t.has(r.id))continue;for(let n of r.builds){if(zi(`${this.engineDir(n.id)}.lock`))continue;await Sr(this.engineDir(n.id),{recursive:!0,force:!0});for(let s of n.files)await Sr(this.blob(s.sha256),{force:!0}),await Sr(`${this.blob(s.sha256)}.part`,{force:!0})}}}async demo(e,t,r="original"){let n=this.spec(e).demos[t];if(!n)throw new Ee("Demo not found");let s=new Bun.CryptoHasher("sha256").update(n.url).digest("hex"),o=Ae(this.root,"demos",s);if(!await Bun.file(o).exists())await this.once(s,()=>this.fetchDemo(n.url,o));let i=Bun.file(o),a=Yn(await i.slice(0,32).bytes());if(!a)throw Error("The stored demo is not an image or a video");let c=`${s}.${r}`;if(r==="original"||!a.startsWith("image/")||a==="image/gif"||this.unshrinkable.has(c))return{blob:i,mime:a};let l=`${o}.${r}.webp`;if(!await Bun.file(l).exists()){if(!await this.once(c,()=>L5(o,l,pI[r])).catch(()=>!1))return this.unshrinkable.add(c),{blob:i,mime:a}}return{blob:Bun.file(l),mime:"image/webp"}}once(e,t){let r=this.demos.get(e);if(!r)r=t().finally(()=>this.demos.delete(e)),this.demos.set(e,r);return r}async fetchDemo(e,t){let r=await this.fetch(e,{signal:AbortSignal.timeout(120000)});if(!r.ok)throw Error(`Could not download the demo (HTTP ${r.status})`);if(Number(r.headers.get("content-length"))>lI)throw Error("The demo is too large");let n=await r.bytes();if(n.byteLength>lI||!Yn(n))throw Error("The demo is not an image or a video");await Bs(Ae(this.root,"demos"),{recursive:!0});let s=`${t}.${crypto.randomUUID()}.tmp`;return await Bun.write(s,n),await el(s,t),t}async idle(){await this.moveTask;while(this.installs.size>0)await this.queue}async close(){for(let e of this.installs.values())e.controller.abort();await this.idle()}}var aI,lI=67108864,uI=250,Jb,Qb,z5=30000,pI,fI=(e)=>e==="original"||Object.hasOwn(pI,e),Ui=(e)=>tl(e).then((t)=>t.size,()=>0),ss=(e)=>[...new Map(e.map((t)=>[t.sha256,t])).values()],En=(e)=>e.reduce((t,r)=>t+r,0),D5=0.9,j5=3000;var hI=b(()=>{Ar();zb();Ud();mb();Rb();B1();Gc();jd();Z1();Zb();Kb();aI=["blobs","installed","engines","demos","loras","checkpoints","broken-engines.json"];Jb=/^[a-z0-9][a-z0-9.-]*$/;Qb=class Qb extends Error{};pI={card:960,large:2560}});import{copyFile as U5,link as B5,mkdir as gI,readdir as ev,readFile as q5,rename as tv,rm as Xt,stat as rv}from"fs/promises";import{freemem as F5}from"os";import{dirname as V5,join as Ot}from"path";function nB(e){return Math.max(100,Math.round(e/4/50)*50)}function sB(e,t,r=eB){let n=(t.find((o)=>o.trim())??"").trim();return[(n?`${e}, ${n}`:e).replace(/-{2,}/g,"-").replace(/\s+/g," "),`--w ${r} --h ${r} --s ${tB} --l 6 --d ${rB}`,"--n blurry, low quality"].join(" ")}function oB(e,t){if(t.step>0||!(e instanceof le))return!1;if(e.code!=="trainingFailed")return!1;return/out of memory|OUT_OF_MEMORY|Cannot allocate memory/i.test(String(e.params?.reason??""))}async function aB(){if(process.platform==="linux"){let t=(await q5("/proc/meminfo","utf8").catch(()=>"")).match(/MemAvailable:\s+(\d+)/)?.[1];if(t)return Number(t)*1024}return F5()}function lB(e){let t=e.split(":").map(Number);if(t.some((r)=>Number.isNaN(r)))return null;return t.reduce((r,n)=>r*60+n,0)}function Bi(e,t,r){let n=t;while(n<e.length&&r.includes(e[n]??""))n++;return n}function uB(e,t){let r=Bi(e,t," \t"),n=Bi(e,r,rp);if(n===r||e[n]!=="/")return null;let s=e.slice(r,n);r=n+1;let o=Bi(e,r,rp);if(o===r)return null;let i=e.slice(r,o);if(r=Bi(e,o," \t"),e[r]!=="[")return null;let a=Bi(e,r+1,`${rp}:`);if(a===r+1||e[a]!=="<")return null;let c=Bi(e,a+1,`${rp}:?`);if(c===a+1)return null;return[s,i,e.slice(a+1,c)]}function dB(e){let t=e.indexOf("steps:");if(t<0)return null;for(let r=e.indexOf("|",t);r>=0;r=e.indexOf("|",r+1)){let n=uB(e,r+1);if(n)return n}return null}function pB(e){let t=dB(e);if(!t)return null;let[r,n,s]=t,o=Number(n);if(!(o>0))return null;return{step:Math.min(Number(r),o),steps:o,secondsLeft:s.includes("?")?null:lB(s)}}function fB(e){if(/caching (latents|text encoder)/i.test(e))return"caching";if(/saving (model|checkpoint)|model saved/i.test(e))return"saving";if(/loading|load (state dict|vae|unet|text encoder)|building/i.test(e))return"loading";return null}class nv{options;listeners=new Set;installing=null;installError=null;ready=null;training=null;trainingController=null;starting=!1;lastEmit=0;pending=null;finishing=null;leftovers;constructor(e){this.options={platform:process.platform,fetch:globalThis.fetch,run:iB,freeMemory:aB,memoryCheckMs:Y5,...e,letGo:e.letGo??(async()=>{})},this.leftovers=Promise.all(["runs","samples"].map((t)=>Xt(this.path(t),{recursive:!0,force:!0}).catch(()=>{}))).then(()=>{})}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get windows(){return this.options.platform==="win32"}path(...e){return Ot(this.options.dir,...e)}get python(){return this.windows?this.path("venv","Scripts","python.exe"):this.path("venv","bin","python")}get scripts(){return this.path("sd-scripts")}get uvEnv(){return{UV_PYTHON_INSTALL_DIR:this.path("python"),UV_CACHE_DIR:this.path("cache"),UV_NO_CONFIG:"1",UV_PYTHON_PREFERENCE:"only-managed",PYTHONUNBUFFERED:"1",PYTHONIOENCODING:"utf-8"}}async isReady(){if(this.ready==null){let e=await Bun.file(this.path("ready.json")).json().catch(()=>null);this.ready=e?.version===yI}return this.ready}async status(){return{state:this.installing?"installing":await this.isReady()?"ready":"missing",install:this.installing&&{step:this.installing.step,receivedBytes:this.installing.receivedBytes,totalBytes:this.installing.totalBytes},error:this.installError,downloadBytes:J5,training:this.training&&{...this.training}}}changed(e=!1){let t=()=>{this.pending=null,this.lastEmit=Date.now(),this.status().then((r)=>{for(let n of this.listeners)try{n({type:"trainer.changed",trainer:r})}catch(s){console.error("A trainer listener failed",s)}})};if(e||Date.now()-this.lastEmit>=wI){if(this.pending)clearTimeout(this.pending);t()}else if(!this.pending)this.pending=setTimeout(t,wI)}async download(e,t,r){let n=e.url.split("/").at(-1)??e.url,s=await this.options.fetch(e.url,{signal:r}).catch((l)=>{if(r.aborted)throw l;throw new le(`Could not download ${n}: ${l instanceof Error?l.message:l}`,"noConnection")});if(!s.ok||!s.body)throw new le(`Could not download the trainer (HTTP ${s.status})`,"downloadFailed",{file:e.url.split("/").at(-1)??e.url,status:s.status});let o=`${t}.part`,i=Bun.file(o).writer(),a=new Bun.CryptoHasher("sha256"),c=0;try{for await(let l of s.body){if(c+=l.byteLength,c>e.size)throw new le("The download is larger than expected","downloadTooLarge",{file:e.url.split("/").at(-1)??e.url});if(a.update(l),i.write(l),this.installing)this.installing.receivedBytes=c,this.installing.totalBytes=e.size;this.changed()}}finally{await i.end()}if(a.digest("hex")!==e.sha256)throw await Xt(o,{force:!0}),new le("The trainer did not match its expected hash","hashMismatch",{file:e.url.split("/").at(-1)??e.url});await tv(o,t)}async step(e,t,r){t.throwIfAborted();let n=this.options.run(e,{cwd:r,env:this.uvEnv}),s=()=>n.kill();t.addEventListener("abort",s,{once:!0});let o=[];try{for await(let a of n.output){if(a.trim())o.push(a.trim());if(o.length>20)o.shift()}let i=await n.exited;if(t.throwIfAborted(),i!==0){let a=o.filter((c)=>/error|fail|not found|no matching/i.test(c)).at(-1)??o.at(-1)??`it stopped with code ${i}`;throw new le(`Installing the trainer failed: ${a}`,"trainerInstallFailed",{reason:a,exitCode:i})}}finally{t.removeEventListener("abort",s)}}async find(e,t){for(let r of await ev(e,{recursive:!0}).catch(()=>[]))if(r.split(/[\\/]/).at(-1)===t)return Ot(e,r);return null}async install(){if(this.installing||this.starting||this.training?.state==="running")throw new O("The trainer is busy","trainerBusy");if(process.arch!=="x64")throw new O("The trainer runs on 64-bit Intel and AMD processors only","trainerNoCuda");let e=this.windows?"win32":this.options.platform==="linux"?"linux":null;if(!e)throw new O("The trainer runs on Windows and Linux only","trainerNoCuda");let t=new AbortController;this.installing={step:"uv",receivedBytes:null,totalBytes:null,controller:t},this.installError=null,this.ready=!1,this.changed(!0),this.installNow(e,t.signal).then(()=>{this.ready=!0}).catch(async(r)=>{if(!t.signal.aborted)this.installError=$s(r);for(let n of["cache","downloads"])await Xt(this.path(n),{recursive:!0,force:!0}).catch(()=>{})}).finally(()=>{this.installing=null,this.changed(!0)})}setStep(e){if(!this.installing)return;this.installing.step=e,this.installing.receivedBytes=null,this.installing.totalBytes=null,this.changed(!0)}async installNow(e,t){let r=this.options.dir;await Xt(this.path("ready.json"),{force:!0}),await Bun.write(this.path("downloads",".keep"),"");let n=this.path("downloads",e==="win32"?"uv.zip":"uv.tar.gz");if(await this.download(H5[e],n,t),await Xt(this.path("uv"),{recursive:!0,force:!0}),e==="win32")await Yc(n,this.path("uv"));else await Bun.write(this.path("uv",".keep"),""),await this.step(["tar","-xzf",n,"-C",this.path("uv")],t);let s=await this.find(this.path("uv"),e==="win32"?"uv.exe":"uv");if(!s)throw new le("uv was not in its archive","trainerInstallFailed",{reason:"uv was not in its archive"});this.setStep("scripts");let o=this.path("downloads","sd-scripts.zip");await this.download(Z5,o,t);let i=this.path("sd-scripts.tmp");await Xt(i,{recursive:!0,force:!0}),await Yc(o,i);let[a]=await ev(i);if(!a)throw new le("The training scripts' archive was empty","trainerInstallFailed",{reason:"empty archive"});await Xt(this.scripts,{recursive:!0,force:!0}),await tv(Ot(i,a),this.scripts),await Xt(i,{recursive:!0,force:!0}),this.setStep("python"),await Xt(this.path("venv"),{recursive:!0,force:!0}),await this.step([s,"venv","--python",G5,this.path("venv")],t,r),this.setStep("packages"),await this.step([s,"pip","install","--python",this.python,"-r","requirements.txt",...K5,"--extra-index-url",W5,"--index-strategy","unsafe-best-match"],t,this.scripts),await Xt(this.path("cache"),{recursive:!0,force:!0}),await Xt(this.path("downloads"),{recursive:!0,force:!0}),this.setStep("checking");try{await this.step([this.python,"-c","import sys, torch; sys.exit(0 if torch.cuda.is_available() else 3)"],t)}catch(c){if(t.aborted||!(c instanceof le)||c.params.exitCode!==3)throw c;throw new le("PyTorch cannot use a graphics card here","trainerNoCuda")}await Bun.write(this.path("ready.json"),JSON.stringify({version:yI,installedAt:Date.now()}))}cancelInstall(){this.installing?.controller.abort()}async remove(){if(this.installing||this.training?.state==="running")throw new O("The trainer is busy","trainerBusy");await Xt(this.options.dir,{recursive:!0,force:!0}),this.ready=!1,this.installError=null,this.changed(!0)}async assertCanTrain(){if(!await this.isReady())throw new O("Install the trainer first","trainerMissing");if(this.starting||this.training?.state==="running"||this.installing)throw new O("The trainer is busy","trainerBusy")}async train(e){await this.assertCanTrain(),this.starting=!0;try{return await this.start(e)}finally{this.starting=!1}}async start(e){let t=e.name.trim(),r=e.trigger.trim();if(!t||t.length>80)throw new O("Give the LoRA a name of at most 80 characters","trainingBadName",{max:80});if(!cB.test(r))throw new O("The trigger must be one word of 2 to 40 letters or digits","trainingBadTrigger",{min:2,max:40});if(e.pictures.length<jo||e.pictures.length>Uo)throw new O(`Training needs ${jo} to ${Uo} pictures`,"trainingNeedsPictures",{min:jo,max:Uo});let n=Math.round(e.steps);if(!(n>=qi&&n<=Fi))throw new O(`Steps must be between ${qi} and ${Fi}`,"trainingBadSteps",{min:qi,max:Fi});let s=await this.options.baseModel(),o=crypto.randomUUID(),i=new AbortController;this.trainingController=i,this.training={id:o,name:t,trigger:r,startedBy:e.startedBy??null,state:"running",stage:"waitingGpu",step:0,steps:n,secondsLeft:null,startedAt:Date.now(),finishedAt:null,freeMemoryBytes:null,loraId:null,samples:[],savedStep:null,keptStep:null,error:null},this.changed(!0);let a=this.training;return this.trainNow(a,{...e,name:t,trigger:r,steps:n},s,i.signal).then((c)=>{a.state="done",a.loraId=c}).catch((c)=>{if(i.signal.aborted)a.state="canceled";else a.state="failed",a.error=$s(c)}).finally(()=>{if(a.finishedAt=Date.now(),a.secondsLeft=null,this.trainingController===i)this.trainingController=null;this.changed(!0)}),{...a}}cancelTraining(){this.trainingController?.abort()}finishTraining(){let e=this.training;if(e?.state!=="running"||e.savedStep==null)throw new O("Nothing is saved to keep yet","trainingNothingSaved");if(e.step>=e.steps)return;this.finishing?.()}sampleFile(e,t){let r=this.training;if(!r||r.id!==e||!r.samples.includes(t))return null;return this.path("samples",e,`${t}.png`)}async trainNow(e,t,r,n){let s=this.path("runs",e.id);await this.leftovers;try{let o=Ot(s,"dataset","10_subject");await Xt(this.path("samples"),{recursive:!0,force:!0});for(let[l,u]of t.pictures.entries()){let d=Ot(o,String(l).padStart(3,"0"));await Bun.write(`${d}.${u.extension}`,u.data);let p=u.caption.replace(/\s+/g," ").trim();await Bun.write(`${d}.txt`,p?`${t.trigger}, ${p}`:t.trigger)}await Bun.write(Ot(s,"dataset.toml"),["[general]",'caption_extension = ".txt"',"shuffle_caption = false","keep_tokens = 1","","[[datasets]]","resolution = 1024","batch_size = 1","enable_bucket = true",""," [[datasets.subsets]]",` image_dir = ${mB(o)}`," num_repeats = 10",""].join(`
|
|
82
|
+
`)),await Bun.write(Ot(s,"samples.txt"),sB(t.trigger,t.pictures.map((l)=>l.caption)));let i=this.options.gpu.acquire(Q5,n),a=await i.next();while(!a.done)a=await i.next();let c=a.value;try{await this.options.letGo().catch(()=>{});let l=await this.named(await this.options.baseModel().catch(()=>r),e.id,s);try{try{return await this.runTraining(e,t,l.file,s,n)}catch(u){if(n.aborted||!oB(u,e))throw u;return await Xt(Ot(s,"out"),{recursive:!0,force:!0}),e.stage="loading",this.changed(!0),await this.runTraining(e,t,l.file,s,n)}}finally{if(l.made)await Xt(l.file,{force:!0}).catch(()=>{})}}finally{c.release()}}finally{await Xt(s,{recursive:!0,force:!0}).catch(()=>{})}}async named(e,t,r){if(e.file.toLowerCase().endsWith(".safetensors"))return{file:e.file,made:!1};let n=Ot(e.scratch,`train-${t}.safetensors`);try{return await gI(e.scratch,{recursive:!0}),await B5(e.file,n),{file:n,made:!0}}catch{let s=Ot(r,"base.safetensors");return await U5(e.file,s),{file:s,made:!1}}}async collectSamples(e,t,r=!1){try{await this.moveSamples(e,t,r)}catch{}}async moveSamples(e,t,r){let n=Ot(t,"sample"),s=await ev(n).catch(()=>[]);for(let o of s){let i=Number(o.match(/^lora_(\d{6})_/)?.[1]);if(!i||e.samples.includes(i))continue;if(!r&&i>=e.step)continue;let a=this.path("samples",e.id,`${i}.png`);if(await gI(V5(a),{recursive:!0}),await tv(Ot(n,o),a).then(()=>!0,()=>!1))e.samples=[...e.samples,i].sort((c,l)=>c-l)}}async runTraining(e,t,r,n,s){e.stage="loading",this.changed(!0);let o=Ot(n,"out"),i=nB(t.steps),a=this.options.run([this.python,"sdxl_train_network.py","--pretrained_model_name_or_path",r,"--dataset_config",Ot(n,"dataset.toml"),"--output_dir",o,"--output_name","lora","--save_model_as","safetensors","--metadata_title",t.name,"--network_module","networks.lora","--network_dim","16","--network_alpha","8","--network_train_unet_only","--learning_rate","1e-4","--optimizer_type","AdamW8bit","--lr_scheduler","constant","--max_train_steps",String(t.steps),"--mixed_precision","bf16","--full_bf16","--lowram","--save_precision","fp16","--no_half_vae","--cache_latents","--cache_text_encoder_outputs","--gradient_checkpointing","--sdpa","--seed","42","--max_data_loader_n_workers","0","--save_every_n_steps",String(i),"--sample_every_n_steps",String(i),"--sample_prompts",Ot(n,"samples.txt"),"--sample_sampler","euler_a"],{cwd:this.scripts,env:this.uvEnv}),c=!1,l=!1,u=()=>a.kill();s.addEventListener("abort",u,{once:!0}),this.finishing=()=>{l=!0,a.kill()};let d=!0,p=!1,f=setInterval(async()=>{if(p)return;p=!0;try{await m()}finally{p=!1}},this.options.memoryCheckMs),m=async()=>{let v=await this.options.freeMemory().catch(()=>null);if(!d)return;if(e.freeMemoryBytes=v,v!=null&&v<X5&&!c)c=!0,a.kill();if(await this.collectSamples(e,o),d)this.changed()},h=[];try{for await(let C of a.output){if(C.trim())h.push(C.trim());if(h.length>30)h.shift();let k=pB(C);if(k){e.stage=k.step>=k.steps?"saving":"training",e.step=k.step,e.secondsLeft=k.secondsLeft;let y=Math.floor((k.step-1)/i)*i;if(y>(e.savedStep??0)&&await rv(Ot(o,bI(y))).catch(()=>null))e.savedStep=y;this.changed();continue}let P=fB(C);if(P&&e.stage!=="training")e.stage=P,this.changed()}let v=await a.exited;s.throwIfAborted(),d=!1,await this.collectSamples(e,o,!0);let _=v===0&&!c&&await rv(Ot(o,"lora.safetensors")).catch(()=>null)!=null;if(l&&!_&&e.savedStep!=null){e.stage="saving",this.changed(!0);let C=await this.options.loras.add(Bun.file(Ot(o,bI(e.savedStep))),`${t.name}.safetensors`);return e.keptStep=e.savedStep,C.id}if(c)throw new le("Training stopped before the computer ran out of memory","trainingOutOfMemory");if(v!==0){let C=h.filter((k)=>/error|exception|out of memory/i.test(k)).at(-1)??h.at(-1)??`it stopped with code ${v}`;throw new le(`Training failed: ${C}`,"trainingFailed",{reason:C})}}finally{d=!1,clearInterval(f),s.removeEventListener("abort",u),this.finishing=null,a.kill()}e.stage="saving",this.changed(!0);let g=Ot(o,"lora.safetensors");if(!await rv(g).catch(()=>null))throw new le("Training made no LoRA","trainingFailed",{reason:"no file was written"});return(await this.options.loras.add(Bun.file(g),`${t.name}.safetensors`)).id}}var yI="sd-scripts-cb70b96+torch-2.14.1-cu130+py3.11",Z5,H5,G5="3.11",K5,W5="https://download.pytorch.org/whl/cu130",J5=6442450944,Q5,X5=1610612736,Y5=5000,wI=1000,jo=3,Uo=200,qi=100,Fi=4000,eB=768,tB=20,rB=42,bI=(e)=>`lora-step${String(e).padStart(8,"0")}.safetensors`,iB=(e,t)=>{let r=Bun.spawn(e,{cwd:t.cwd,env:{...process.env,...t.env},stdin:"ignore",stdout:"pipe",stderr:"pipe"});async function*n(){let s=[],o={wake:null},i=2;for(let a of[r.stdout,r.stderr])(async()=>{let c="";try{for await(let l of a.pipeThrough(new TextDecoderStream)){let u=(c+l).split(/[\r\n]/);c=u.pop()??"",s.push(...u),o.wake?.()}}catch{}if(c)s.push(c);i--,o.wake?.()})();while(i>0||s.length>0){let a=s.shift();if(a!=null){yield a;continue}await new Promise((c)=>{o.wake=c}),o.wake=null}}return{output:n(),exited:r.exited,kill:()=>{if(r.exitCode!=null||r.signalCode!=null)return;if(process.platform==="win32")Bun.spawn(["taskkill","/T","/F","/PID",String(r.pid)],{stdout:"ignore",stderr:"ignore"});else r.kill()}}},cB,rp="0123456789",mB=(e)=>JSON.stringify(e);var vI=b(()=>{Ar();Kb();Z5={url:"https://github.com/kohya-ss/sd-scripts/archive/cb70b96858477e716a2096292ab8aab433277f38.zip",sha256:"13587ab358c5ecb878a991a391ca924cb37ff1d427805b1476f41bbf23fcc493",size:6689584},H5={linux:{url:"https://github.com/astral-sh/uv/releases/download/0.9.30/uv-x86_64-unknown-linux-gnu.tar.gz",sha256:"8b3762374972daa7a74bbc6896cc73229ca69a07403dd9f9ea3805a51ffd7582",size:22237571},win32:{url:"https://github.com/astral-sh/uv/releases/download/0.9.30/uv-x86_64-pc-windows-msvc.zip",sha256:"875981be7908295937dee09532bb66d576986d4f223259e171b0c767c885897a",size:21763186}},K5=["torch==2.14.1+cu130","torchvision==0.29.1+cu130"],Q5=Number.MAX_SAFE_INTEGER;cB=/^[\p{L}\p{N}_-]{2,40}$/u});class sv{adapters=new Map;models=new Map;register(e){if(this.adapters.has(e.id))throw Error(`Provider already registered: ${e.id}`);this.adapters.set(e.id,e);for(let t of e.listModels())this.models.set(t.id,t);return this}refresh(e){let t=this.adapters.get(e);if(!t)return;for(let[r,n]of this.models)if(n.providerId===e)this.models.delete(r);for(let r of t.listModels())this.models.set(r.id,r)}adapter(e){return this.adapters.get(e)}listAdapters(){return[...this.adapters.values()]}model(e){return this.models.get(e)}listModels(){return[...this.models.values()]}}import{readFile as hB,rename as gB,rm as yB,writeFile as wB}from"fs/promises";import{basename as bB,join as _I}from"path";async function xI(e,t){for(let r of[np(e),iv(e)]){let n=`${r}.${process.pid}.tmp`;await wB(n,JSON.stringify(t)),await gB(n,r)}}async function SI(e){for(let t of[np(e),iv(e)])if((await ov(t,()=>!0))?.pid===process.pid)await yB(t,{force:!0})}async function $I(e,t=vB){return await ov(np(e),t)??await ov(iv(e),t)}async function ov(e,t){try{let r=JSON.parse(await hB(e,"utf8"));if(typeof r.pid!=="number"||typeof r.url!=="string"||!/^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(r.url))return null;return t(r.pid)?{pid:r.pid,url:r.url}:null}catch{return null}}var np=(e)=>_I(e,"hatchlight.server.json"),iv=(e)=>_I(e,Vc(bB(np(e)))),vB=(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}};var kI=()=>{};function xB(e,t){let r=e.capabilities;if(t.referenceAssetIds.length>r.maxReferenceImages)throw r.maxReferenceImages===0?new O(`${e.name} does not accept reference images`,"noReferences",{model:e.name}):new O(`${e.name} accepts at most ${r.maxReferenceImages} reference images`,"tooManyReferences",{model:e.name,count:r.maxReferenceImages});if(r.upscale!=null&&t.referenceAssetIds.length===0)throw new O(`${e.name} needs a picture to work on`,"needsPicture",{model:e.name});if(t.maskAssetId!=null){if(t.referenceAssetIds.length!==1)throw new O("A mask needs exactly one reference image to redraw","maskWithoutReference");if(r.mask==null)throw new O(`${e.name} cannot redraw only part of a picture`,"noMask",{model:e.name})}let n=r.durations??[],s=t.durationSeconds??n[0];return{...t,count:Math.min(t.count,r.maxCount),durationSeconds:s==null||n.length===0?void 0:n.reduce((o,i)=>Math.abs(i-s)<Math.abs(o-s)?i:o),aspectRatio:t.aspectRatio&&r.aspectRatios.includes(t.aspectRatio)&&!(r.strength!=null&&t.referenceAssetIds.length>0)?t.aspectRatio:void 0,seed:r.seed?t.seed:void 0,strength:r.strength!=null&&t.referenceAssetIds.length>0?t.strength??(t.maskAssetId!=null?r.mask:void 0)??r.strength:void 0,loras:r.loraBase&&t.loras?.length?t.loras:void 0}}class av{deps;constructor(e){this.deps=e}listModels(){return this.deps.registry.listModels()}async listProviders(e){let t=await this.deps.keys.list(e),r=await this.deps.keys.sources?.(e)??null;return this.deps.registry.listAdapters().map((n)=>({id:n.id,name:n.name,requiresKey:n.requiresKey,hasKey:t.includes(n.id)||Boolean(n.keyEnv&&process.env[n.keyEnv]),...r&&{keys:{personal:r.personal.includes(n.id),server:r.server.includes(n.id)||Boolean(n.keyEnv&&process.env[n.keyEnv])}}}))}async setProviderKey(e,t,r){if(this.requireProvider(t),!r.trim())throw new O("The key is empty","emptyKey");await this.deps.keys.set(e,t,r.trim())}async deleteProviderKey(e,t){this.requireProvider(t),await this.deps.keys.delete(e,t)}requireProvider(e){if(!this.deps.registry.adapter(e))throw new Ee(`Unknown provider: ${e}`,"unknownProvider",{provider:e})}listSessions(e){return this.deps.repo.listSessions(e)}async getSession(e,t){let r=await this.deps.repo.getSession(e,t);if(!r)throw new Ee("Session not found","sessionNotFound");return{...r,turns:await this.deps.repo.listTurns(e,t)}}async startSession(e,t){let r=Date.now(),n={id:Ft("ses"),userId:e.userId,title:t.slice(0,80),createdAt:r,updatedAt:r};return await this.deps.repo.createSession(n),n}async deleteSession(e,t){let r=await this.getSession(e,t);for(let n of r.turns.flatMap((s)=>s.jobs))await this.deps.engine.cancel(n.id);await this.deps.repo.deleteSession(e,t)}assertRoom(e){let t=this.deps.storageRefusal?.(e.userId);if(t)throw t}async createTurn(e,t){this.assertRoom(e);let{sessionId:r,modelIds:n,...s}=t,o=RT.safeParse(s);if(!o.success)throw new O(o.error.issues[0]?.message??"Invalid input");let i=o.data;if(n.length===0)throw new O("Choose at least one model","noModel");let a=[...new Set(n)].map((h)=>{let g=this.deps.registry.model(h);if(!g)throw new O(`Unknown model: ${h}`,"unknownModel",{model:h});return g}),c=[...i.referenceAssetIds,...i.maskAssetId!=null?[i.maskAssetId]:[]],l=await this.deps.repo.getAssets(e,c);if(l.length!==new Set(c).size)throw new O("A reference image was not found","referenceNotFound");if(l.some((h)=>!h.mime.startsWith("image/")))throw new O("Only images can be used as references","referenceNotImage");let u=a.map((h)=>xB(h,i)),d=Date.now(),p;if(r){let h=await this.deps.repo.getSession(e,r);if(!h)throw new Ee("Session not found","sessionNotFound");p={...h,updatedAt:d}}else p={id:Ft("ses"),userId:e.userId,title:i.prompt.slice(0,80),createdAt:d,updatedAt:d},await this.deps.repo.createSession(p);let f={id:Ft("trn"),sessionId:p.id,userId:e.userId,prompt:i.prompt,referenceAssetIds:i.referenceAssetIds,createdAt:d},m=a.map((h,g)=>({id:Ft("job"),turnId:f.id,position:g,userId:e.userId,providerId:h.providerId,modelId:h.id,params:u[g],status:"queued",handle:null,error:null,errorCode:null,errorParams:null,costUsd:null,createdAt:d,startedAt:null,finishedAt:null,tokenId:e.tokenId??null}));await this.deps.repo.createTurn(f,m);for(let h of m)this.deps.engine.enqueue(h);return{session:p,turn:{...f,jobs:m.map((h)=>({...h,assets:[]}))}}}async cancelJob(e,t){let r=await this.deps.repo.findJob(t);if(!r||r.userId!==e.userId)throw new Ee("Job not found","jobNotFound");await this.deps.engine.cancel(t)}async retryJob(e,t){this.assertRoom(e);let r=await this.deps.repo.findJob(t);if(!r||r.userId!==e.userId)throw new Ee("Job not found","jobNotFound");await this.deps.engine.retry(r,e.tokenId??null)}jobPreview(e,t){let r=this.deps.engine.preview(e.userId,t);if(!r)throw new Ee("No preview","jobNotFound");return r}async deleteAsset(e,t){let[r]=await this.deps.repo.getAssets(e,[t]);if(!r)throw new Ee("Asset not found","assetNotFound");let{sharing:n}=await this.deps.repo.deleteAsset(e,t);if(n===0)await this.deps.assets.remove(e,r.hash)}async uploadAsset(e,t){this.assertRoom(e);let r=Yn(t);if(!r||!_B.includes(r))throw new O("Only PNG, JPEG and WebP images can be uploaded","uploadType");let n=await this.deps.assets.put(e,t),s={id:Ft("ast"),userId:e.userId,kind:"upload",jobId:null,hash:n.hash,mime:r,size:n.size,prompt:null,modelId:null,params:null,createdAt:Date.now()};return await this.deps.repo.createAsset(s),s}async getAssetFile(e,t){let[r]=await this.deps.repo.getAssets(e,[t]),n=r&&await this.deps.assets.get(e,r.hash);if(!r||!n)throw new Ee("Asset not found","assetNotFound");return{asset:r,blob:n}}listGallery(e,t){return this.deps.repo.listGallery(e,t)}}var _B;var TI=b(()=>{Ar();Br();_B=["image/png","image/jpeg","image/webp"]});import{mkdir as PI,rename as EI,writeFile as II}from"fs/promises";import{dirname as AI}from"path";class lv{path;pending=Promise.resolve();constructor(e){this.path=e}async read(){let e=Bun.file(this.path);if(!await e.exists())return{};return await e.json().catch(()=>({}))}async get(e){let t=(await this.read())[e.userId]??{};return{translateWith:xc(t.translateWith)?t.translateWith:cv.translateWith,improveWith:Rs(t.improveWith)?t.improveWith:cv.improveWith,assistantWith:Rs(t.assistantWith)?t.assistantWith:cv.assistantWith}}set(e,t){let r=this.pending.then(async()=>{let n=await this.read();n[e.userId]={...n[e.userId],...t},await PI(AI(this.path),{recursive:!0});let s=`${this.path}.${crypto.randomUUID()}.tmp`;return await II(s,JSON.stringify(n,null,2)),await EI(s,this.path),this.get(e)});return this.pending=r.catch(()=>{}),r}moveUser(e,t){let r=this.pending.then(async()=>{let n=await this.read();if(!Object.hasOwn(n,e)||Object.hasOwn(n,t))return;n[t]=n[e],delete n[e],await PI(AI(this.path),{recursive:!0});let s=`${this.path}.${crypto.randomUUID()}.tmp`;await II(s,JSON.stringify(n,null,2)),await EI(s,this.path)});return this.pending=r.catch(()=>{}),r}}var cv;var RI=b(()=>{Br();cv={translateWith:"local",improveWith:"auto",assistantWith:"auto"}});function CI(e,t="1:1"){let[r=1,n=1]=t.split(":").map(Number),s=96/Math.max(r,n),o=Math.max(1,Math.round(r*s)),i=Math.max(1,Math.round(n*s)),a=new Bun.CryptoHasher("sha256").update(e).digest(),c=Math.ceil(o*3/4)*4,l=new Uint8Array(54+c*i),u=new DataView(l.buffer);l.set([66,77]),u.setUint32(2,l.length,!0),u.setUint32(10,54,!0),u.setUint32(14,40,!0),u.setInt32(18,o,!0),u.setInt32(22,i,!0),u.setUint16(26,1,!0),u.setUint16(28,24,!0);for(let d=0;d<i;d++){let p=d/Math.max(1,i-1);for(let f=0;f<o;f++)for(let m=0;m<3;m++){let h=a[m]??0,g=a[m+3]??0;l[54+d*c+f*3+m]=h+(g-h)*p}}return l}class sp{id;modelNames;name;requiresKey=!1;resumable=!1;maxConcurrency;gate=null;failWith=null;failures=[];delayMs=0;outputUrl=null;submitted=[];canceled=[];constructor(e="fake",t=["alpha","beta"]){this.id=e;this.modelNames=t;this.name=`Fake (${e})`}listModels(){return this.modelNames.map((e)=>({id:`${this.id}/${e}`,providerId:this.id,providerModelId:e,name:`Fake ${e}`,media:"image",operations:["generate","edit"],capabilities:{aspectRatios:["1:1","16:9"],seed:!0,maxCount:2,maxReferenceImages:e==="alpha"?2:0,...e==="alpha"&&{mask:0.85},...e==="beta"&&{englishPrompts:!0}},pricing:{usdPerOutput:0.01}}))}keysUsed=[];async submit(e,t){this.keysUsed.push(t?.apiKey);let r={model:e.model.id,prompt:e.params.prompt,count:e.params.count,aspectRatio:e.params.aspectRatio,...e.mask&&{mask:e.mask.data}};return this.submitted.push(r),r}async*events(e,t){yield{type:"progress",fraction:0.5,preview:{data:CI(`${e.model} ${e.prompt} 0`,e.aspectRatio),mime:"image/bmp"}};let r=[];if(this.gate)r.push(this.gate);if(this.delayMs>0)r.push(Bun.sleep(this.delayMs));await Promise.race([Promise.all(r),new Promise((s,o)=>{if(t.signal.aborted)o(t.signal.reason);t.signal.addEventListener("abort",()=>o(t.signal.reason))})]);let n=this.failures.shift();if(n){yield n;return}if(this.failWith){yield{type:"failed",error:this.failWith};return}if(this.outputUrl){yield{type:"completed",outputs:[{url:this.outputUrl}]};return}yield{type:"completed",outputs:Array.from({length:e.count},(s,o)=>({data:CI(`${e.model} ${e.prompt} ${o}`,e.aspectRatio),mime:"image/bmp"}))}}async cancel(e){this.canceled.push(e)}}var zI;var OI=b(()=>{zI={name:"@hatchlight/desktop",version:"0.4.1",private:!0,type:"module",scripts:{"prepare-bundle":"bun run --cwd ../web build && bun scripts/sidecar.ts",dev:"tauri dev",build:"tauri build",icons:"tauri icon icon.svg",typecheck:"tsc -p ."},devDependencies:{"@tauri-apps/cli":"2.12.5"}}});var MI;var NI=b(()=>{OI();MI=zI.version});var Pt=b(()=>{jT();qT();Xw();BE();KE();Ar();t1();i1();Ud();mb();T1();Rb();Gc();jd();Vd();Dd();hI();Zb();vI();Tb();zb();rb();kI();TI();RI();Gm();Fc();Br();NI()});var LI=b(()=>{Xu()});var DI=b(()=>{LI()});function YI(e){if(e.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function eA(e){if(e.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var uv="2025-11-25",jI="2025-03-26",Zi,qs="io.modelcontextprotocol/related-task",ip="2.0",zt,UI,BI,Nue,kB,TB,dv,Mr,rl,qI=(e)=>rl.safeParse(e).success,Ht,Zr,Hr,Gt,ap,FI,os=(e)=>FI.safeParse(e).success,VI,ZI=(e)=>VI.safeParse(e).success,pv,is=(e)=>pv.safeParse(e).success,ne,fv,Hi=(e)=>fv.safeParse(e).success,nl,Lue,cp,PB,lp,EB,sl,Vi,HI,IB,AB,RB,CB,OB,zB,up,mv=(e)=>up.safeParse(e).success,MB,NB,hv,dp,LB,DB,pp,jB,ol,il,UB,al,Gi,BB,cl,fp,mp,hp,Due,gp,yp,wp,GI,KI,WI,gv,JI,ll,Ki,QI,qB,bp,FB,vp,VB,yv,ZB,_p,HB,GB,KB,WB,JB,QB,XB,YB,eq,tq,xp,rq,nq,Sp,wv,bv,vv,sq,oq,iq,_v,aq,cq,lq,uq,dq,XI,$p,pq,kp,jue,fq,Wi,mq,Uue,ul,hq,xv,gq,yq,wq,bq,vq,_q,xq,op,Sq,$q,kq,dl,Sv,Tq,Pq,Eq,Iq,Aq,Rq,Cq,Oq,zq,Mq,Nq,Lq,Dq,jq,Uq,Bq,qq,Fq,Ji,Vq,Zq,Hq,Tp,Gq,Kq,Wq,$v,Jq,Bue,que,Fue,Vue,Zue,Hue,te,tA;var Bo=b(()=>{DI();Zi=[uv,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],zt=ST((e)=>e!==null&&(typeof e==="object"||typeof e==="function")),UI=Xe([E(),xe().int()]),BI=E(),Nue=sr({ttl:xe().optional(),pollInterval:xe().optional()}),kB=Z({ttl:xe().optional()}),TB=Z({taskId:E()}),dv=sr({progressToken:UI.optional(),[qs]:TB.optional()}),Mr=Z({_meta:dv.optional()}),rl=Mr.extend({task:kB.optional()}),Ht=Z({method:E(),params:Mr.loose().optional()}),Zr=Z({_meta:dv.optional()}),Hr=Z({method:E(),params:Zr.loose().optional()}),Gt=sr({_meta:dv.optional()}),ap=Xe([E(),xe().int()]),FI=Z({jsonrpc:oe(ip),id:ap,...Ht.shape}).strict(),VI=Z({jsonrpc:oe(ip),...Hr.shape}).strict(),pv=Z({jsonrpc:oe(ip),id:ap,result:Gt}).strict();(function(e){e[e.ConnectionClosed=-32000]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ne||(ne={}));fv=Z({jsonrpc:oe(ip),id:ap.optional(),error:Z({code:xe().int(),message:E(),data:Qe().optional()})}).strict(),nl=Xe([FI,VI,pv,fv]),Lue=Xe([pv,fv]),cp=Gt.strict(),PB=Zr.extend({requestId:ap.optional(),reason:E().optional()}),lp=Hr.extend({method:oe("notifications/cancelled"),params:PB}),EB=Z({src:E(),mimeType:E().optional(),sizes:$e(E()).optional(),theme:or(["light","dark"]).optional()}),sl=Z({icons:$e(EB).optional()}),Vi=Z({name:E(),title:E().optional()}),HI=Vi.extend({...Vi.shape,...sl.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),IB=Wu(Z({applyDefaults:St().optional()}),Ke(E(),Qe())),AB=Dy((e)=>{if(e&&typeof e==="object"&&!Array.isArray(e)){if(Object.keys(e).length===0)return{form:{}}}return e},Wu(Z({form:IB.optional(),url:zt.optional()}),Ke(E(),Qe()).optional())),RB=sr({list:zt.optional(),cancel:zt.optional(),requests:sr({sampling:sr({createMessage:zt.optional()}).optional(),elicitation:sr({create:zt.optional()}).optional()}).optional()}),CB=sr({list:zt.optional(),cancel:zt.optional(),requests:sr({tools:sr({call:zt.optional()}).optional()}).optional()}),OB=Z({experimental:Ke(E(),zt).optional(),sampling:Z({context:zt.optional(),tools:zt.optional()}).optional(),elicitation:AB.optional(),roots:Z({listChanged:St().optional()}).optional(),tasks:RB.optional(),extensions:Ke(E(),zt).optional()}),zB=Mr.extend({protocolVersion:E(),capabilities:OB,clientInfo:HI}),up=Ht.extend({method:oe("initialize"),params:zB}),MB=Z({experimental:Ke(E(),zt).optional(),logging:zt.optional(),completions:zt.optional(),prompts:Z({listChanged:St().optional()}).optional(),resources:Z({subscribe:St().optional(),listChanged:St().optional()}).optional(),tools:Z({listChanged:St().optional()}).optional(),tasks:CB.optional(),extensions:Ke(E(),zt).optional()}),NB=Gt.extend({protocolVersion:E(),capabilities:MB,serverInfo:HI,instructions:E().optional()}),hv=Hr.extend({method:oe("notifications/initialized"),params:Zr.optional()}),dp=Ht.extend({method:oe("ping"),params:Mr.optional()}),LB=Z({progress:xe(),total:et(xe()),message:et(E())}),DB=Z({...Zr.shape,...LB.shape,progressToken:UI}),pp=Hr.extend({method:oe("notifications/progress"),params:DB}),jB=Mr.extend({cursor:BI.optional()}),ol=Ht.extend({params:jB.optional()}),il=Gt.extend({nextCursor:BI.optional()}),UB=or(["working","input_required","completed","failed","cancelled"]),al=Z({taskId:E(),status:UB,ttl:Xe([xe(),hT()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:et(xe()),statusMessage:et(E())}),Gi=Gt.extend({task:al}),BB=Zr.merge(al),cl=Hr.extend({method:oe("notifications/tasks/status"),params:BB}),fp=Ht.extend({method:oe("tasks/get"),params:Mr.extend({taskId:E()})}),mp=Gt.merge(al),hp=Ht.extend({method:oe("tasks/result"),params:Mr.extend({taskId:E()})}),Due=Gt.loose(),gp=ol.extend({method:oe("tasks/list")}),yp=il.extend({tasks:$e(al)}),wp=Ht.extend({method:oe("tasks/cancel"),params:Mr.extend({taskId:E()})}),GI=Gt.merge(al),KI=Z({uri:E(),mimeType:et(E()),_meta:Ke(E(),Qe()).optional()}),WI=KI.extend({text:E()}),gv=E().refine((e)=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),JI=KI.extend({blob:gv}),ll=or(["user","assistant"]),Ki=Z({audience:$e(ll).optional(),priority:xe().min(0).max(1).optional(),lastModified:$j({offset:!0}).optional()}),QI=Z({...Vi.shape,...sl.shape,uri:E(),description:et(E()),mimeType:et(E()),size:et(xe()),annotations:Ki.optional(),_meta:et(sr({}))}),qB=Z({...Vi.shape,...sl.shape,uriTemplate:E(),description:et(E()),mimeType:et(E()),annotations:Ki.optional(),_meta:et(sr({}))}),bp=ol.extend({method:oe("resources/list")}),FB=il.extend({resources:$e(QI)}),vp=ol.extend({method:oe("resources/templates/list")}),VB=il.extend({resourceTemplates:$e(qB)}),yv=Mr.extend({uri:E()}),ZB=yv,_p=Ht.extend({method:oe("resources/read"),params:ZB}),HB=Gt.extend({contents:$e(Xe([WI,JI]))}),GB=Hr.extend({method:oe("notifications/resources/list_changed"),params:Zr.optional()}),KB=yv,WB=Ht.extend({method:oe("resources/subscribe"),params:KB}),JB=yv,QB=Ht.extend({method:oe("resources/unsubscribe"),params:JB}),XB=Zr.extend({uri:E()}),YB=Hr.extend({method:oe("notifications/resources/updated"),params:XB}),eq=Z({name:E(),description:et(E()),required:et(St())}),tq=Z({...Vi.shape,...sl.shape,description:et(E()),arguments:et($e(eq)),_meta:et(sr({}))}),xp=ol.extend({method:oe("prompts/list")}),rq=il.extend({prompts:$e(tq)}),nq=Mr.extend({name:E(),arguments:Ke(E(),E()).optional()}),Sp=Ht.extend({method:oe("prompts/get"),params:nq}),wv=Z({type:oe("text"),text:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),bv=Z({type:oe("image"),data:gv,mimeType:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),vv=Z({type:oe("audio"),data:gv,mimeType:E(),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),sq=Z({type:oe("tool_use"),name:E(),id:E(),input:Ke(E(),Qe()),_meta:Ke(E(),Qe()).optional()}),oq=Z({type:oe("resource"),resource:Xe([WI,JI]),annotations:Ki.optional(),_meta:Ke(E(),Qe()).optional()}),iq=QI.extend({type:oe("resource_link")}),_v=Xe([wv,bv,vv,iq,oq]),aq=Z({role:ll,content:_v}),cq=Gt.extend({description:E().optional(),messages:$e(aq)}),lq=Hr.extend({method:oe("notifications/prompts/list_changed"),params:Zr.optional()}),uq=Z({title:E().optional(),readOnlyHint:St().optional(),destructiveHint:St().optional(),idempotentHint:St().optional(),openWorldHint:St().optional()}),dq=Z({taskSupport:or(["required","optional","forbidden"]).optional()}),XI=Z({...Vi.shape,...sl.shape,description:E().optional(),inputSchema:Z({type:oe("object"),properties:Ke(E(),zt).optional(),required:$e(E()).optional()}).catchall(Qe()),outputSchema:Z({type:oe("object"),properties:Ke(E(),zt).optional(),required:$e(E()).optional()}).catchall(Qe()).optional(),annotations:uq.optional(),execution:dq.optional(),_meta:Ke(E(),Qe()).optional()}),$p=ol.extend({method:oe("tools/list")}),pq=il.extend({tools:$e(XI)}),kp=Gt.extend({content:$e(_v).default([]),structuredContent:Ke(E(),Qe()).optional(),isError:St().optional()}),jue=kp.or(Gt.extend({toolResult:Qe()})),fq=rl.extend({name:E(),arguments:Ke(E(),Qe()).optional()}),Wi=Ht.extend({method:oe("tools/call"),params:fq}),mq=Hr.extend({method:oe("notifications/tools/list_changed"),params:Zr.optional()}),Uue=Z({autoRefresh:St().default(!0),debounceMs:xe().int().nonnegative().default(300)}),ul=or(["debug","info","notice","warning","error","critical","alert","emergency"]),hq=Mr.extend({level:ul}),xv=Ht.extend({method:oe("logging/setLevel"),params:hq}),gq=Zr.extend({level:ul,logger:E().optional(),data:Qe()}),yq=Hr.extend({method:oe("notifications/message"),params:gq}),wq=Z({name:E().optional()}),bq=Z({hints:$e(wq).optional(),costPriority:xe().min(0).max(1).optional(),speedPriority:xe().min(0).max(1).optional(),intelligencePriority:xe().min(0).max(1).optional()}),vq=Z({mode:or(["auto","required","none"]).optional()}),_q=Z({type:oe("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:$e(_v).default([]),structuredContent:Z({}).loose().optional(),isError:St().optional(),_meta:Ke(E(),Qe()).optional()}),xq=Ly("type",[wv,bv,vv]),op=Ly("type",[wv,bv,vv,sq,_q]),Sq=Z({role:ll,content:Xe([op,$e(op)]),_meta:Ke(E(),Qe()).optional()}),$q=rl.extend({messages:$e(Sq),modelPreferences:bq.optional(),systemPrompt:E().optional(),includeContext:or(["none","thisServer","allServers"]).optional(),temperature:xe().optional(),maxTokens:xe().int(),stopSequences:$e(E()).optional(),metadata:zt.optional(),tools:$e(XI).optional(),toolChoice:vq.optional()}),kq=Ht.extend({method:oe("sampling/createMessage"),params:$q}),dl=Gt.extend({model:E(),stopReason:et(or(["endTurn","stopSequence","maxTokens"]).or(E())),role:ll,content:xq}),Sv=Gt.extend({model:E(),stopReason:et(or(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:ll,content:Xe([op,$e(op)])}),Tq=Z({type:oe("boolean"),title:E().optional(),description:E().optional(),default:St().optional()}),Pq=Z({type:oe("string"),title:E().optional(),description:E().optional(),minLength:xe().optional(),maxLength:xe().optional(),format:or(["email","uri","date","date-time"]).optional(),default:E().optional()}),Eq=Z({type:or(["number","integer"]),title:E().optional(),description:E().optional(),minimum:xe().optional(),maximum:xe().optional(),default:xe().optional()}),Iq=Z({type:oe("string"),title:E().optional(),description:E().optional(),enum:$e(E()),default:E().optional()}),Aq=Z({type:oe("string"),title:E().optional(),description:E().optional(),oneOf:$e(Z({const:E(),title:E()})),default:E().optional()}),Rq=Z({type:oe("string"),title:E().optional(),description:E().optional(),enum:$e(E()),enumNames:$e(E()).optional(),default:E().optional()}),Cq=Xe([Iq,Aq]),Oq=Z({type:oe("array"),title:E().optional(),description:E().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:Z({type:oe("string"),enum:$e(E())}),default:$e(E()).optional()}),zq=Z({type:oe("array"),title:E().optional(),description:E().optional(),minItems:xe().optional(),maxItems:xe().optional(),items:Z({anyOf:$e(Z({const:E(),title:E()}))}),default:$e(E()).optional()}),Mq=Xe([Oq,zq]),Nq=Xe([Rq,Cq,Mq]),Lq=Xe([Nq,Tq,Pq,Eq]),Dq=rl.extend({mode:oe("form").optional(),message:E(),requestedSchema:Z({type:oe("object"),properties:Ke(E(),Lq),required:$e(E()).optional()})}),jq=rl.extend({mode:oe("url"),message:E(),elicitationId:E(),url:E().url()}),Uq=Xe([Dq,jq]),Bq=Ht.extend({method:oe("elicitation/create"),params:Uq}),qq=Zr.extend({elicitationId:E()}),Fq=Hr.extend({method:oe("notifications/elicitation/complete"),params:qq}),Ji=Gt.extend({action:or(["accept","decline","cancel"]),content:Dy((e)=>e===null?void 0:e,Ke(E(),Xe([E(),xe(),St(),$e(E())])).optional())}),Vq=Z({type:oe("ref/resource"),uri:E()}),Zq=Z({type:oe("ref/prompt"),name:E()}),Hq=Mr.extend({ref:Xe([Zq,Vq]),argument:Z({name:E(),value:E()}),context:Z({arguments:Ke(E(),E()).optional()}).optional()}),Tp=Ht.extend({method:oe("completion/complete"),params:Hq});Gq=Gt.extend({completion:sr({values:$e(E()).max(100),total:et(xe().int()),hasMore:et(St())})}),Kq=Z({uri:E().startsWith("file://"),name:E().optional(),_meta:Ke(E(),Qe()).optional()}),Wq=Ht.extend({method:oe("roots/list"),params:Mr.optional()}),$v=Gt.extend({roots:$e(Kq)}),Jq=Hr.extend({method:oe("notifications/roots/list_changed"),params:Zr.optional()}),Bue=Xe([dp,up,Tp,xv,Sp,xp,bp,vp,_p,WB,QB,Wi,$p,fp,hp,gp,wp]),que=Xe([lp,pp,hv,Jq,cl]),Fue=Xe([cp,dl,Sv,Ji,$v,mp,yp,Gi]),Vue=Xe([dp,kq,Bq,Wq,fp,hp,gp,wp]),Zue=Xe([lp,pp,yq,YB,GB,mq,lq,cl,Fq]),Hue=Xe([cp,NB,Gq,cq,rq,FB,VB,HB,kp,pq,mp,yp,Gi]);te=class te extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`);this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){if(e===ne.UrlElicitationRequired&&r){let n=r;if(n.elicitations)return new tA(n.elicitations,t)}return new te(e,t,r)}};tA=class tA extends te{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(ne.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});class kv{constructor(e){this._maxBufferSize=e?.maxBufferSize??Qq}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
83
|
+
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Xq(t)}clear(){this._buffer=void 0}}function Xq(e){return nl.parse(JSON.parse(e))}function rA(e){return JSON.stringify(e)+`
|
|
84
|
+
`}var Qq=10485760;var nA=b(()=>{Bo()});import sA from"process";class Tv{constructor(e=sA.stdin,t=sA.stdout,r){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=(n)=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=(n)=>{this.onerror?.(n)},this._readBuffer=new kv({maxBufferSize:r?.maxBufferSize})}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise((t)=>{let r=rA(e);if(this._stdout.write(r))t();else this._stdout.once("drain",t)})}}var oA=b(()=>{nA()});class cs{baseUrl;fetch;constructor(e,t=(r,n)=>globalThis.fetch(r,n)){this.baseUrl=e;this.fetch=t}async request(e,t){let r=await this.fetch(`${this.baseUrl}${e}`,t);if(!r.ok){let s=await r.json().catch(()=>null);throw new as(s?.error??`Hatchlight answered ${r.status}`,r.status,s?.code??null)}let n=await r.text();return n?JSON.parse(n):void 0}post=(e)=>this.request(e,{method:"POST"});models=()=>this.request("/api/models");providers=()=>this.request("/api/providers");session=(e)=>this.request(`/api/sessions/${encodeURIComponent(e)}`);createTurn=(e)=>this.request("/api/turns",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)});upload=(e)=>this.request("/api/assets",{method:"POST",body:e});gallery=(e)=>{let t=new URLSearchParams;if(e.query)t.set("query",e.query);return t.set("limit",String(e.limit??20)),this.request(`/api/gallery?${t}`)};async asset(e){let t=await this.fetch(`${this.baseUrl}/api/assets/${encodeURIComponent(e)}`);if(!t.ok)throw new as(`No picture or video with id ${e}`,t.status,"assetNotFound");return{data:new Uint8Array(await t.arrayBuffer()),mime:t.headers.get("content-type")??"application/octet-stream"}}cancelJob=(e)=>this.post(`/api/jobs/${encodeURIComponent(e)}/cancel`);retryJob=(e)=>this.post(`/api/jobs/${encodeURIComponent(e)}/retry`);async*events(e){let t=await this.fetch(`${this.baseUrl}/api/events`,{signal:e});if(!t.ok||!t.body)return;let r="";try{for await(let n of t.body.pipeThrough(new TextDecoderStream)){r=(r+n).replaceAll(`\r
|
|
85
|
+
`,`
|
|
86
|
+
`);for(;;){let s=r.indexOf(`
|
|
87
|
+
|
|
88
|
+
`);if(s<0)break;let o=r.slice(0,s);r=r.slice(s+2);let i=o.split(`
|
|
89
|
+
`).filter((c)=>c.startsWith("data:")).map((c)=>c.slice(5).trimStart()).join(`
|
|
90
|
+
`);if(!i)continue;let a=JSON.parse(i);if(typeof a.type==="string")yield a}}}catch(n){if(!e.aborted)throw n}}sessionUrl=(e)=>`${this.baseUrl}/#/s/${encodeURIComponent(e)}`}var as;var Pp=b(()=>{as=class as extends Error{status;code;constructor(e,t,r){super(e);this.status=t;this.code=r}}});async function t8(e){try{let t=await fetch(`${e}/api/models`,{signal:AbortSignal.timeout(3000)});return t.ok&&Array.isArray(await t.json())}catch{return!1}}async function pl(e){let t=await $I(e);return t&&await t8(t.url)?t.url:null}async function r8(e,t){let r=Bun.spawn([...e,...t,"--port","0","--no-open","--parent-pid",String(process.pid)],{stdin:"pipe",stdout:"pipe",stderr:"pipe",detached:!0}),n=new Response(r.stderr).text(),s=r.stdout.pipeThrough(new TextDecoderStream).getReader(),o="",i=setTimeout(()=>r.kill(),Yq);try{for(;;){let{value:c,done:l}=await s.read();if(l)break;o+=c;let u=o.match(/Hatchlight is running at (http:\/\/\S+)\r?\n/);if(u?.[1])return(async()=>{while(!(await s.read()).done);})(),u[1].replace("localhost","127.0.0.1")}}finally{clearTimeout(i)}let a=(await n).trim();if(/already running/.test(a))return"in use";throw Error(`Hatchlight did not start: ${a||o.trim()}`)}async function fl(e,t,r){let n=await pl(e);if(n)return{url:n,started:!1};let s=await r8(t,r);if(s!=="in use")return{url:s,started:!0};let o=Date.now()+e8;while(Date.now()<o){await Bun.sleep(250);let i=await pl(e);if(i)return{url:i,started:!1}}throw Error("Hatchlight is running on this data directory but does not answer")}var Yq=60000,e8=20000;var Pv=b(()=>{Pt()});function ml(e,t,r){if(Gr(e))return 0;let n=e.pricing;if(n?.usdPerOutput!=null)return n.usdPerOutput*t;if(n?.usdPerSecond!=null){let s=r??e.capabilities.durations?.[0]??5;return n.usdPerSecond*s*t}return null}class hl{limitUsd;spentUsd;held=new Map;constructor(e,t=0){this.limitUsd=e;this.spentUsd=t}committed(){return this.spentUsd+[...this.held.values()].reduce((e,t)=>e+t.usd,0)}left(){return this.limitUsd==null?null:Math.max(0,this.limitUsd-this.committed())}hold(e,t,r,n){let s=new Map;for(let a of t){let c=ml(a,r,n);if(c==null){if(this.limitUsd!=null)return{ok:!1,reason:`${a.name} does not say what it costs, so it cannot be kept within the spending limit.`}}else s.set(a.id,c)}let o=[...s.values()].reduce((a,c)=>a+c,0),i=this.limitUsd;if(i!=null&&o>0&&this.committed()+o>i)return{ok:!1,reason:`This would cost about ${Nr(o)}, over what is left of the ${Nr(i)} limit (${Nr(Math.max(0,i-this.committed()))}).`};return this.held.set(e,{usd:o,perJob:s}),{ok:!0,usd:o}}heldKeys(){return[...this.held.keys()]}release(e){this.held.delete(e)}rename(e,t){let r=this.held.get(e);if(!r)return;this.held.delete(e),this.held.set(t,r)}settle(e){let t=this.held.get(e.id);if(!t||!dn(e.jobs))return;this.held.delete(e.id);for(let r of e.jobs){if(r.providerId==="local")continue;this.spentUsd+=r.costUsd??(r.status==="succeeded"?t.perJob.get(r.modelId)??0:0)}}}var Ev,Gr=(e)=>e.providerId==="local",dn=(e)=>e.every((t)=>Ev.includes(t.status)),Nr=(e)=>`$${e.toFixed(2)}`;var Ep=b(()=>{Ev=["succeeded","failed","canceled"]});import{mkdir as n8,readFile as s8,writeFile as o8}from"fs/promises";import{dirname as i8,isAbsolute as a8,resolve as c8}from"path";async function Ip(e){try{let t=await new Bun.Image(e).metadata(),r=await new Bun.Image(e).resize(aA,aA,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:85}).bytes();return{size:t,image:{data:Buffer.from(r).toString("base64"),mimeType:"image/jpeg"}}}catch{return null}}function iA(e){let t=e.flatMap((r)=>r.label?[r.label]:[]);return t.length>0?[`Previews below, in order: ${t.join("; ")}.`]:[]}function u8(e){let t=e.capabilities,r=[e.operations.includes("generate")&&"makes from words",t.maxReferenceImages>0&&t.upscale==null&&(t.strength!=null?"redraws a given picture (strength)":`follows up to ${t.maxReferenceImages} given picture(s)`),t.mask!=null&&"redraws only a masked part",t.upscale!=null&&`upscales a picture ${t.upscale}x`].filter(Boolean),n=Gr(e)?"free, runs on this computer":e.pricing?.usdPerOutput!=null?`about $${e.pricing.usdPerOutput} per ${e.media}`:e.pricing?.usdPerSecond!=null?`about $${e.pricing.usdPerSecond} per second`:"paid, price unknown",s=t.aspectRatios.length?`; ratios ${t.aspectRatios.join(", ")}`:"",o=t.durations?.length?`; lengths ${t.durations.join(", ")} s`:"";return`- ${e.id} \u2014 ${e.name} (${e.media}): ${r.join(", ")}; ${n}${s}${o}`}function Rp(e,t){return e.filter((r)=>Gr(r)&&r.media==="image"&&r.capabilities.upscale==null&&(t>0?r.capabilities.maxReferenceImages>=t:r.operations.includes("generate"))).toSorted((r,n)=>(n.profile?.quality??0)-(r.profile?.quality??0)||(n.profile?.speed??0)-(r.profile?.speed??0))[0]}async function Qi(e,t){let[r,n]=await Promise.all([e.models(),e.providers()]),s=new Set(n.filter((o)=>o.hasKey||!o.requiresKey).map((o)=>o.id));return r.filter((o)=>s.has(o.providerId)&&(t||Gr(o)))}function Cp(e,t){let r=t.waitMs??900000,n=t.pollMs??1000,{spend:s}=t,o=t.files?"Picture ids (ast_\u2026) or image file paths":"Picture ids (ast_\u2026)",i=()=>Qi(e,t.allowPaid);function a(p){if(t.files)return null;let f=p.filter((m)=>!In.test(m));return f.length>0?ls(`Pictures are given by id (ast_\u2026), not ${f.join(", ")}.`):null}async function c(p){let f=[];for(let m of p){if(In.test(m)){f.push(m);continue}if(!t.files)throw Error(`Not a picture id: ${m}`);let h=new Uint8Array(await s8(c8(m)));f.push((await e.upload(h)).id)}return f}async function l(p,f,m){let h=[];for(let g of p){let w=f.find((k)=>k.id===g.modelId)?.name??g.modelId,v=g.startedAt&&g.finishedAt?` in ${((g.finishedAt-g.startedAt)/1000).toFixed(1)} s`:"",_=g.costUsd?`, $${g.costUsd.toFixed(3)}`:"";if(g.status!=="succeeded"){h.push(`- ${w}: ${g.status}${g.error?`: ${g.error}`:""}`);continue}let C=[];for(let k of g.assets){let P=k.mime.startsWith("image/")&&m.length<l8?await Ip((await e.asset(k.id)).data):null;if(P)m.push({...P.image,label:`${k.id} by ${w}`}),C.push(`${k.id} (${P.size.width}x${P.size.height})`);else C.push(`${k.id} (${k.mime})`)}h.push(`- ${w}: done${v}${_}. ${C.join(", ")}`)}return h}async function u(p,f,m){let h=a(p.references);if(h)return h;let g=p.modelIds.map((j)=>f.find((se)=>se.id===j)),w=`pending-${crypto.randomUUID()}`,v=s.hold(w,g,p.count??1,p.durationSeconds);if(!v.ok)return ls(v.reason);if(m.signal.aborted)return s.release(w),ls("Stopped before it started; nothing was made.");let _,C;try{let j=await c(p.references);({session:_,turn:C}=await e.createTurn({prompt:p.prompt,modelIds:p.modelIds,referenceAssetIds:j,...p.sessionId&&{sessionId:p.sessionId},...p.aspectRatio&&{aspectRatio:p.aspectRatio},...p.count!=null&&{count:p.count},...p.seed!=null&&{seed:p.seed},...p.durationSeconds!=null&&{durationSeconds:p.durationSeconds},...p.strength!=null&&{strength:p.strength}}))}catch(j){throw s.release(w),j}s.rename(w,C.id),m.started?.(C.id);let k=C.jobs,P=Date.now(),y=!1;try{while(p.wait&&!dn(k)){if(Date.now()-P>r||m.signal.aborted){y=!0;break}await Bun.sleep(n);let se=(await e.session(_.id)).turns.find((de)=>de.id===C.id);if(se)k=se.jobs,s.settle(se);let we=k.filter((de)=>Ev.includes(de.status));await m.progress(`${we.length} of ${k.length} done`)}}catch(j){if(!m.signal.aborted)throw j;y=!0}s.settle({...C,jobs:k});let x=[],T=[`Session ${_.id}, turn ${C.id} (the user can open it at ${e.sessionUrl(_.id)}).`,...await l(k,f,x)];if(T.push(...iA(x)),!dn(k))T.push(y?`Stopped waiting; it goes on. Call job_status with session ${_.id} later.`:`Started. Call job_status with session ${_.id} for the results.`);let I=s.limitUsd;if(I!=null&&s.committed()>0)T.push(`Spent or held so far: ${Nr(s.committed())} of ${Nr(I)}.`);return{text:T.join(`
|
|
91
|
+
`),images:x,turnId:C.id}}let d=[qo({name:"list_models",title:"List models",description:"Lists the models that can be used now, with what each can do (make from words, redraw or follow given pictures, redraw a masked part, upscale), its cost, and the ratios and video lengths it accepts. Local models are free and run on the user's computer. Only installed models are listed; the user installs more in the Hatchlight app.",input:{media:or(["image","video"]).optional().describe("Only models that make this.")},readOnly:!0,async run({media:p}){let f=(await i()).filter((g)=>p==null||g.media===p);if(f.length===0)return Fs(t.allowPaid?"No model can be used now. The user can install local models, or add an API key, in the Hatchlight app.":"No local model is installed. The user can install one from Local models in the Hatchlight app. (Paid models are off for this connection.)");let m=s.limitUsd,h=t.allowPaid?m!=null?`Paid models are allowed, up to ${Nr(m)} in all (${Nr(s.left()??0)} left).`:"Paid models are allowed, without a limit.":"Only local models are allowed for this connection.";return Fs([...f.map(u8),"",h].join(`
|
|
92
|
+
`))}}),qo({name:"generate",title:"Make pictures or videos",description:`Makes pictures or videos from a prompt, waits for them, and returns small previews with their ids. Give several models to compare them on the same prompt. Give reference_images to redraw, edit or animate a picture: ${t.files?"ids from earlier results (ast_\u2026) or paths of image files":"ids from earlier results (ast_\u2026)"}. Pass session_id to keep iterating in the same session. Without models, the best free local model that fits is used.`,input:{prompt:E().min(1).describe("What to make, or what to change."),models:$e(E()).optional().describe("Model ids from list_models; several compare them."),reference_images:$e(E()).optional().describe(`${o} to start from.`),strength:xe().min(0.05).max(1).optional().describe("For models that redraw a picture: how much it changes, 0.05 to 1."),aspect_ratio:E().optional().describe('Such as "16:9".'),count:xe().int().min(1).max(8).optional(),seed:xe().int().nonnegative().optional(),duration_seconds:xe().int().optional().describe("Video length, for video models."),session_id:E().regex(Kr).optional(),wait:St().optional().describe("Wait for the results (default). False returns at once; use job_status later.")},async run(p,f){let m=await i(),h=p.reference_images??[],g=a(h);if(g)return g;let w=p.models??[];if(w.length===0){let _=Rp(m,h.length);if(!_)return ls(h.length>0?"No installed local model can start from a picture. Name one with models, or the user can install one in the Hatchlight app.":"No local model is installed. The user can install one from Local models in the Hatchlight app.");w=[_.id]}let v=w.filter((_)=>!m.some((C)=>C.id===_));if(v.length>0)return ls(`Cannot use ${v.join(", ")}: not installed, without a key, or paid while paid models are off. Call list_models for what can be used.`);return u({prompt:p.prompt,modelIds:w,references:h,sessionId:p.session_id,aspectRatio:p.aspect_ratio,count:p.count,seed:p.seed,durationSeconds:p.duration_seconds,strength:p.strength,wait:p.wait??!0},m,f)}}),qo({name:"upscale",title:"Upscale a picture",description:`Makes a picture larger and sharper with an installed upscaler, free and local when one is. Give a ${t.files?"picture id (ast_\u2026) or an image file path":"picture id (ast_\u2026)"}.`,input:{image:E().describe(t.files?"A picture id (ast_\u2026) or an image file path.":"A picture id (ast_\u2026)."),session_id:E().regex(Kr).optional()},async run(p,f){let m=await i(),h=m.filter((w)=>w.capabilities.upscale!=null),g=h.find(Gr)??h[0];if(!g)return ls("No upscaler is installed. The user can install Real-ESRGAN from Local models in the Hatchlight app.");return u({prompt:`Upscale \xD7${g.capabilities.upscale}`,modelIds:[g.id],references:[p.image],sessionId:p.session_id,wait:!0},m,f)}}),qo({name:"job_status",title:"Check a session",description:"Says how a session's latest turn, and any turn still running, stand, with previews of what is done. For generations started with wait set to false, or that took too long.",input:{session_id:E().regex(Kr)},readOnly:!0,async run({session_id:p}){let[f,m]=await Promise.all([e.session(p),e.models()]),h=f.turns.at(-1);if(!h)return Fs("The session has nothing in it yet.");let g=f.turns.filter((_)=>_===h||!dn(_.jobs)),w=[],v=[];for(let _ of g)s.settle(_),v.push(`Turn ${_.id}: "${_.prompt}"`),v.push(...await l(_.jobs,m,w));return v.push(...iA(w)),{text:v.join(`
|
|
93
|
+
`),images:w}}}),qo({name:"search_gallery",title:"Search the gallery",description:`Finds pictures and videos made before, newest first, by words in their prompts. Returns ids to use with get_image${t.files?", save_image,":""} or as reference_images.`,input:{query:E().optional(),limit:xe().int().min(1).max(50).optional()},readOnly:!0,async run({query:p,limit:f}){let m=await e.gallery({query:p,limit:f??20});if(m.length===0)return Fs("Nothing found.");return Fs(m.map((h)=>`- ${h.id} \u2014 ${h.mime} \u2014 ${h.modelId??"uploaded"} \u2014 ${new Date(h.createdAt).toISOString()} \u2014 "${h.prompt??""}"`).join(`
|
|
94
|
+
`))}}),qo({name:"get_image",title:"Look at a picture",description:"Shows a picture by its id, made small enough to look at.",input:{asset_id:E().regex(In)},readOnly:!0,async run({asset_id:p}){let{data:f,mime:m}=await e.asset(p),h=m.startsWith("image/")?await Ip(f):null;if(!h)return Fs(`${p} is a ${m} that cannot be shown${t.files?"; save_image saves it":""}.`);return{text:`${p}: ${h.size.width}x${h.size.height} ${m}`,images:[h.image]}}})];if(t.files)d.push(qo({name:"save_image",title:"Save a picture or video",description:"Writes a picture or video, at full size, to a file. The path must be absolute; an existing file is kept unless overwrite is true.",input:{asset_id:E().regex(In),path:E().describe("Absolute path of the file to write."),overwrite:St().optional()},async run({asset_id:p,path:f,overwrite:m}){if(!a8(f))return ls("The path must be absolute.");let{data:h,mime:g}=await e.asset(p);await n8(i8(f),{recursive:!0});try{await o8(f,h,{flag:m?"w":"wx"})}catch(w){if(w.code!=="EEXIST")throw w;return ls(`${f} exists; pass overwrite true to replace it.`)}return Fs(`Saved ${p} (${g}, ${h.byteLength} bytes) to ${f}`)}}));return d}var Ap="Hatchlight makes pictures and videos with the models its user installed (local, free) and, when allowed, with paid cloud models on the user's own keys. Call list_models first to see what can be used. Pass returned picture ids (ast_\u2026) back as reference_images to iterate on a result. Models can only be installed by the user, in the Hatchlight app.",aA=1024,l8=8,Kr,In,Fs=(e)=>({text:e,images:[]}),ls=(e)=>({...Fs(e),isError:!0}),qo=(e)=>{let t=Z(e.input);return{...e,async run(r,n){let s=t.safeParse(r??{});if(!s.success)return ls(`The arguments do not fit ${e.name}: ${CS(s.error)}`);return e.run(s.data,n)}}};var Iv=b(()=>{vc();Ep();Kr=/^[a-z]+_[A-Za-z0-9]+$/,In=/^ast_[A-Za-z0-9]+$/});function m8(e){let t="the language the person writes in";if(e)try{t=new Intl.DisplayNames(["en"],{type:"language"}).of(e)??e}catch{t=e}return["You are the assistant inside Hatchlight, an app that makes pictures and videos. The person talks with you to make pictures and change them; you do it with the tools.",`- Always write to the person in ${t}. Keep it short: a sentence or two. Do not describe a picture you have not seen.`,"- Write each prompt for generate in English, as a full description of the picture: subject, setting, light, style. To change a picture, describe the whole new picture, not only the change.","- To change a picture made before, give its id (ast_\u2026) in reference_images when the model can redraw pictures; otherwise make it again with a new prompt.","- Leave models out unless the person names one: the best free model on this computer is used. Use paid models only when the person asks; they are asked to approve the cost.","- Call list_models when the person asks what can be used, or names a model you do not know.","- The pictures you make appear to the person on their own: do not repeat their ids or links.","- When you can see the results, look before you answer: say in one sentence whether they match what was asked, and if something is clearly off (cut off, wrong count, misspelled text, wrong colors) offer one concrete fix as a question. Do not make it again unasked.","- To change a picture you made, start from it: give its id in reference_images, with a model that edits or redraws pictures, rather than making a new one from words.","- When several models made the same prompt, say which result fits the request best and why, in a sentence.",Ap].join(`
|
|
95
|
+
`)}function h8(e){let t=bc(Z(e.input));if(t.properties)delete t.properties.session_id;if(t.required)t.required=t.required.filter((r)=>r!=="session_id");return delete t.$schema,{name:e.name,description:e.description,parameters:t}}function g8(e){let t=[],r=[],n=()=>{for(let s of r)t.push({role:"tool",callId:s.id,name:s.name,content:[{type:"text",text:"Stopped by the person before it ran."}]});r=[]};for(let s of e){if(s.error||s.note)continue;let{message:o}=s;if(o.role==="tool"){r=r.filter((i)=>i.id!==o.callId),t.push(o);continue}if(n(),o.role==="assistant"){if(!o.text&&o.toolCalls.length===0)continue;r=[...o.toolCalls]}t.push(o)}return n(),t}function y8(e,t){if(t==null)return e;let r=(o)=>JSON.stringify(o).length,n=e.reduce((o,i)=>o+r(i),0),s=0;while(n>t&&s<e.length-1){n-=r(e[s]),s++;while(s<e.length-1&&e[s]?.role!=="user")n-=r(e[s]),s++}return e.slice(s)}function Op(e,t,r){let n=[{type:"text",text:t.isError?`Error: ${t.text}`:t.text}];if(r)n.push(...uA(t.images));return{role:"tool",callId:e.id,name:e.name,content:n}}function uA(e){return e.flatMap(({label:t,data:r,mimeType:n})=>[...t?[{type:"text",text:t}]:[],{type:"image",data:r,mimeType:n}])}function _8(e,t){let r=e.toLowerCase(),n=t.name.toLowerCase(),s=t.id.slice(t.id.indexOf("/")+1).toLowerCase(),o=(c)=>c.length>=3;if(o(n)&&r.includes(n)||o(s)&&r.includes(s))return!0;let i=`${n} ${s} ${t.providerId}`.split(/[^\p{L}\p{N}]+/u).filter((c)=>(o(c)||c===n||c===s)&&!v8.has(c)),a=new Set(r.split(/[^\p{L}\p{N}]+/u));return i.some((c)=>a.has(c))}function x8(e,t,r){let n=e.arguments.models;if(e.name!=="generate"||!Array.isArray(n))return e;if(/compar/i.test(t))return e;let s=n.filter((a)=>{let c=r.find((l)=>l.id===a);return c?_8(t,c):t.includes(String(a))}),{models:o,...i}=e.arguments;return{...e,arguments:s.length>0?{...i,models:s}:i}}function zp(e){let{id:t,sessionId:r,createdAt:n,...s}=e;return s}class Av{options;working=new Map;guards=new Map;listeners=new Set;limitUsd;maxSteps;closed=!1;constructor(e){this.options=e;this.limitUsd=e.limitUsd??d8,this.maxSteps=e.maxSteps??p8}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async view(e,t){let r=await this.store.list(e,t),n=await this.guard(e,t,r),s=n.heldKeys();if(s.length>0){let i=await this.options.reel(e).session(t);for(let a of i.turns)if(s.includes(a.id))n.settle(a)}let o=this.working.get(this.key(e,t));return{entries:r,busy:o!=null,turnId:o?.turnId??null,spentUsd:n.committed(),limitUsd:this.limitUsd}}async send(e,t){let r=t.text.trim();if(!r)throw new O("Write something first");let n=await this.needBrain(e),s=t.sessionId??(await this.options.startSession(e,r)).id;if(t.sessionId)await this.options.reel(e).session(s);let o=this.claim(e,s);try{let i=await this.store.list(e,s);for(let a of i)if(a.confirm?.state==="asked")await this.decide(e,a,"The person wrote again instead of approving; nothing was made.");await this.add(e,s,{message:{role:"user",content:[{type:"text",text:r}]}})}catch(i){throw this.release(e,s),i}return this.run(e,s,o,n,t.language),{sessionId:s}}async answer(e,t,r,n,s){let o=this.claim(e,t),i,a,c;try{let u=await this.store.list(e,t),d=u.find((p)=>p.id===r);if(d?.confirm?.state!=="asked")throw new Ee("Nothing is waiting for an answer there","confirmNotWaiting");if(i=d,c=u.some((p)=>p.id!==r&&p.confirm?.state==="asked"),a=c?null:n?await this.needBrain(e):await this.options.brain(e),!n)await this.decide(e,i,"The person said no to the cost; nothing was made. Do not use paid models again unless they ask.")}catch(u){throw this.release(e,t),u}let l=c?null:a;if(!n&&!l){this.release(e,t);return}this.run(e,t,o,l,s,n?(u,d)=>this.approved(e,o,u,d,i):void 0)}async approved(e,t,r,n,s){let{confirm:o,message:i}=s;if(!o||i.role!=="tool")return;let a={id:i.callId,name:i.name,arguments:o.arguments};if(t.controller.signal.aborted){await this.decide(e,s,"Stopped before it ran; nothing was made.");return}let c=await this.paidCost(this.options.reel(e),a,n);if(c&&(c.names.join(`
|
|
96
|
+
`)!==o.modelNames.join(`
|
|
97
|
+
`)||c.usd>o.usd+0.000000001)){await this.decide(e,s,"The models or the price changed after the person said yes; nothing was made. Ask again.");return}let l=zp(s),u={...o,state:"approved"};await this.store.update(e,s.id,{...l,confirm:u}),this.changed(e,s.sessionId);let d=await this.call(e,s.sessionId,t,r,a,(p)=>this.store.update(e,s.id,{...l,confirm:u,turnId:p}));await this.store.update(e,s.id,{...l,confirm:u,message:lA(Op(a,d,!1)),...d.turnId&&{turnId:d.turnId}}),this.changed(e,s.sessionId)}forget(e,t){this.stop(e,t),this.guards.delete(this.key(e,t))}close(){this.closed=!0;for(let e of this.working.values())e.controller.abort()}get store(){if(this.closed)throw Error("The assistant is closed");return this.options.store}stop(e,t){this.working.get(this.key(e,t))?.controller.abort()}key(e,t){return`${e.userId}
|
|
98
|
+
${t}`}claim(e,t){let r=this.key(e,t);if(this.working.has(r))throw new O("The assistant is still working on this conversation","assistantBusy");let n={controller:new AbortController,turnId:null};return this.working.set(r,n),this.changed(e,t),n}release(e,t){this.working.delete(this.key(e,t)),this.changed(e,t)}changed(e,t){for(let r of this.listeners)r(e.userId,{type:"assistant.changed",sessionId:t})}async needBrain(e){let t=await this.options.brain(e);if(!t)throw new O("No language model to think with: install the one for this computer or add a key","noLanguageModel");return t}async guard(e,t,r){let n=this.key(e,t),s=this.guards.get(n);if(s)return s;let o=new Set(r.flatMap((c)=>c.turnId?[c.turnId]:[])),i=0;if(o.size>0){let c=await this.options.reel(e).session(t);for(let l of c.turns){if(!o.has(l.id))continue;for(let u of l.jobs)if(u.providerId!=="local")i+=u.costUsd??0}}let a=this.guards.get(n)??new hl(this.limitUsd,i);return this.guards.set(n,a),a}async add(e,t,r){let n={...r,message:lA(r.message),id:Ft("msg"),sessionId:t,createdAt:Date.now()};return await this.store.add(e,n),this.changed(e,t),n}async decide(e,t,r){if(!t.confirm||t.message.role!=="tool")return;await this.store.update(e,t.id,{...zp(t),confirm:{...t.confirm,state:"declined"},message:{...t.message,content:[{type:"text",text:r}]}}),this.changed(e,t.sessionId)}run(e,t,r,n,s,o){this.loop(e,t,r,n,s,o).catch((i)=>{if(!this.closed)console.error(i)}).finally(()=>this.release(e,t))}async loop(e,t,r,n,s,o){let{signal:i}=r.controller,a=this.options.reel(e),c=async(l)=>{await this.add(e,t,{message:{role:"assistant",text:"",toolCalls:[]},...l})};try{let l=await this.store.list(e,t),u=await this.guard(e,t,l),d=Cp(a,{allowPaid:!0,spend:u,files:!1,waitMs:this.options.waitMs,pollMs:this.options.pollMs});if(o)await o(d,u);if(!n||i.aborted){if(i.aborted)await c({note:"stopped"});return}let p=d.map(h8),f=await this.store.list(e,t),m=g8(f);if(n.vision)await this.showAgain(e,t,f,m);let h=m8(s),g=f.flatMap((w)=>w.message.role==="user"?w.message.content:[]).map((w)=>w.type==="text"?w.text:"").join(`
|
|
99
|
+
`);for(let w=0;w<this.maxSteps;w++){let v=await n.chat(h,y8(m,n.contextChars),p,i),_=v.toolCalls.some((P)=>P.name==="generate")?await a.models():[],C={role:"assistant",text:v.text,toolCalls:v.toolCalls.map((P)=>x8(P,g,_))};if(m.push(C),await this.add(e,t,{message:C}),C.toolCalls.length===0)return;let k=!1;for(let P of C.toolCalls){if(i.aborted)break;let y=await this.paidCost(a,P,u);if(i.aborted)break;if(y){k=!0,await this.add(e,t,{message:{role:"tool",callId:P.id,name:P.name,content:[{type:"text",text:"Waiting for the person to approve the cost."}]},confirm:{arguments:P.arguments,modelNames:y.names,usd:y.usd,state:"asked"}});continue}let x=await this.add(e,t,{message:Op(P,{text:"Started, but no result came back.",images:[],isError:!0},!1)}),T=await this.call(e,t,r,d,P,(se)=>this.store.update(e,x.id,{...zp(x),turnId:se})),I=n.vision?T:await this.described(e,T,m,i),j=Op(P,I,n.vision);m.push(j),await this.store.update(e,x.id,{...zp(x),message:Op(P,I,!1),...I.turnId&&{turnId:I.turnId}}),this.changed(e,t)}if(i.aborted){await c({note:"stopped"});return}if(k)return}await c({note:"tooManySteps"})}catch(l){if(i.aborted){await c({note:"stopped"});return}await c({error:{message:cA(l),code:l instanceof le?l.code??null:null}})}}async described(e,t,r,n){if(t.images.length===0||n.aborted)return t;let s=await this.options.eyes?.(e);if(!s)return t;let o=r.findLast((i)=>i.role==="user")?.content.flatMap((i)=>i.type==="text"?[i.text]:[]).join(" ");try{let i=await s.look(t.images,o??"",n);if(!i)return t;return{...t,text:`${t.text}
|
|
100
|
+
What the pictures show, as a model that sees describes them:
|
|
101
|
+
${i}`}}catch(i){if(n.aborted)throw i;return console.error(i),t}}async showAgain(e,t,r,n){let s=r.filter((l)=>l.turnId&&l.message.role==="tool").slice(-w8);if(s.length===0)return;let o=this.options.reel(e),[i,a]=await Promise.all([o.session(t),o.models()]),c=0;for(let l of s){let u=i.turns.find((h)=>h.id===l.turnId),{message:d}=l;if(!u||d.role!=="tool")continue;let p=[];for(let h of u.jobs){let g=a.find((w)=>w.id===h.modelId)?.name??h.modelId;for(let w of h.assets){if(!w.mime.startsWith("image/")||c>=b8)continue;let v=await Ip((await o.asset(w.id)).data).catch(()=>null);if(!v)continue;c++,p.push({...v.image,label:`${w.id} by ${g}`})}}let f=n.indexOf(d),m=n[f];if(f<0||m?.role!=="tool"||p.length===0)continue;n[f]={...m,content:[...m.content,...uA(p)]}}}async call(e,t,r,n,s,o){let i=n.find((l)=>l.name===s.name),a;if(!i)return{text:`There is no tool named ${s.name}.`,images:[],isError:!0};let c={...s.arguments};if(f8.has(i.name))c.session_id=t;try{return await i.run(c,{signal:r.controller.signal,progress:async()=>{},started:(l)=>{r.turnId=l,a=o?.(l).catch((u)=>console.error(u)),this.changed(e,t)}})}catch(l){return{text:cA(l),images:[],isError:!0}}finally{if(await a,r.turnId)r.turnId=null,this.changed(e,t)}}async paidCost(e,t,r){if(t.name!=="generate"&&t.name!=="upscale")return null;let[n,s]=await Promise.all([e.models(),e.providers()]),o=new Set(s.filter((f)=>f.hasKey||!f.requiresKey).map((f)=>f.id)),i=n.filter((f)=>o.has(f.providerId)),a=t.arguments,c,l=1,u;if(t.name==="generate"){let f=Array.isArray(a.models)?a.models:[];if(c=i.filter((m)=>f.includes(m.id)&&!Gr(m)),typeof a.count==="number")l=a.count;if(typeof a.duration_seconds==="number")u=a.duration_seconds}else{let f=i.filter((m)=>m.capabilities.upscale!=null);c=f.some(Gr)?[]:f.slice(0,1)}if(c.length===0)return null;let d=0;for(let f of c){let m=ml(f,l,u);if(m==null)return null;d+=m}let p=r.left();if(p!=null&&d>p)return null;return{names:c.map((f)=>f.name),usd:d}}}var d8=2,p8=12,f8,cA=(e)=>e instanceof Error?e.message:String(e),w8=2,b8=8,lA=(e)=>e.role==="assistant"?e:{...e,content:e.content.filter((t)=>t.type==="text")},v8;var dA=b(()=>{Pt();vc();Ep();Iv();f8=new Set(["generate","upscale","job_status"]);v8=new Set(["base","image","lightning","local","model","turbo","video"])});var Fo=b(()=>{dA();Ep();Iv()});var Ce,pA,K,us=(e)=>{switch(typeof e){case"undefined":return K.undefined;case"string":return K.string;case"number":return Number.isNaN(e)?K.nan:K.number;case"boolean":return K.boolean;case"function":return K.function;case"bigint":return K.bigint;case"symbol":return K.symbol;case"object":if(Array.isArray(e))return K.array;if(e===null)return K.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return K.promise;if(typeof Map<"u"&&e instanceof Map)return K.map;if(typeof Set<"u"&&e instanceof Set)return K.set;if(typeof Date<"u"&&e instanceof Date)return K.date;return K.object;default:return K.unknown}};var gl=b(()=>{(function(e){e.assertEqual=(s)=>{};function t(s){}e.assertIs=t;function r(s){throw Error()}e.assertNever=r,e.arrayToEnum=(s)=>{let o={};for(let i of s)o[i]=i;return o},e.getValidEnumValues=(s)=>{let o=e.objectKeys(s).filter((a)=>typeof s[s[a]]!=="number"),i={};for(let a of o)i[a]=s[a];return e.objectValues(i)},e.objectValues=(s)=>e.objectKeys(s).map(function(o){return s[o]}),e.objectKeys=typeof Object.keys==="function"?(s)=>Object.keys(s):(s)=>{let o=[];for(let i in s)if(Object.prototype.hasOwnProperty.call(s,i))o.push(i);return o},e.find=(s,o)=>{for(let i of s)if(o(i))return i;return},e.isInteger=typeof Number.isInteger==="function"?(s)=>Number.isInteger(s):(s)=>typeof s==="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map((i)=>typeof i==="string"?`'${i}'`:i).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(s,o)=>{if(typeof o==="bigint")return o.toString();return o}})(Ce||(Ce={}));(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(pA||(pA={}));K=Ce.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var L,Lr;var Mp=b(()=>{gl();L=Ce.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);Lr=class Lr extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(s){return s.message},r={_errors:[]},n=(s)=>{for(let o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)r._errors.push(t(o));else{let i=r,a=0;while(a<o.path.length){let c=o.path[a],l=a===o.path.length-1;if(c==="_errors"){if(l)i._errors.push(t(o));a++;continue}if(!Object.prototype.hasOwnProperty.call(i,c))if(c==="__proto__")Object.defineProperty(i,c,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0});else i[c]={_errors:[]};if(i=i[c],l)i._errors.push(t(o));a++}}};return n(this),r}static assert(e){if(!(e instanceof Lr))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ce.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t=Object.create(null),r=[];for(let n of this.issues)if(n.path.length>0){let s=n.path[0];t[s]=t[s]||[],t[s].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Lr.create=(e)=>new Lr(e)});var S8=(e,t)=>{let r;switch(e.code){case L.invalid_type:if(e.received===K.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case L.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ce.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ce.joinValues(e.keys,", ")}`;break;case L.invalid_union:r="Invalid input";break;case L.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ce.joinValues(e.options)}`;break;case L.invalid_enum_value:r=`Invalid enum value. Expected ${Ce.joinValues(e.options)}, received '${e.received}'`;break;case L.invalid_arguments:r="Invalid function arguments";break;case L.invalid_return_type:r="Invalid function return type";break;case L.invalid_date:r="Invalid date";break;case L.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else Ce.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case L.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case L.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case L.custom:r="Invalid input";break;case L.invalid_intersection_types:r="Intersection results could not be merged";break;case L.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case L.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ce.assertNever(e)}return{message:r}},Vs;var Rv=b(()=>{Mp();gl();Vs=S8});function yl(){return $8}var $8;var Np=b(()=>{Rv();$8=Vs});function V(e,t){let r=yl(),n=Lp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Vs?void 0:Vs].filter((s)=>!!s)});e.common.issues.push(n)}class Yt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let r=[];for(let n of t){if(n.status==="aborted")return fe;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let s=await n.key,o=await n.value;r.push({key:s,value:o})}return Yt.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:s,value:o}=n;if(s.status==="aborted")return fe;if(o.status==="aborted")return fe;if(s.status==="dirty")e.dirty();if(o.status==="dirty")e.dirty();if(s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet))r[s.value]=o.value}return{status:e.value,value:r}}}var Lp=(e)=>{let{data:t,path:r,errorMaps:n,issueData:s}=e,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...s,path:o,message:a}},fe,Xi=(e)=>({status:"dirty",value:e}),ar=(e)=>({status:"valid",value:e}),Cv=(e)=>e.status==="aborted",Ov=(e)=>e.status==="dirty",Vo=(e)=>e.status==="valid",wl=(e)=>typeof Promise<"u"&&e instanceof Promise;var zv=b(()=>{Np();Rv();fe=Object.freeze({status:"aborted"})});var fA=()=>{};var re;var mA=b(()=>{(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(re||(re={}))});class pn{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function ve(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:s};return{errorMap:(i,a)=>{let{message:c}=e;if(i.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(i.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:s}}class Ie{get description(){return this._def.description}_getType(e){return us(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:us(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Yt,ctx:{common:e.parent.common,data:e.data,parsedType:us(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(wl(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:us(e)},n=this._parseSync({data:e,path:r.path,parent:r});return hA(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:us(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Vo(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Vo(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:us(e)},n=this._parse({data:e,path:r.path,parent:r}),s=await(wl(n)?n:Promise.resolve(n));return hA(r,s)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,s)=>{let o=e(n),i=()=>s.addIssue({code:L.custom,...r(n)});if(typeof Promise<"u"&&o instanceof Promise)return o.then((a)=>{if(!a)return i(),!1;else return!0});if(!o)return i(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new Cn({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return Rn.create(this,this._def)}nullable(){return Zs.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return An.create(this)}promise(){return na.create(this,this._def)}or(e){return Sl.create([this,e],this._def)}and(e){return $l.create(this,e,this._def)}transform(e){return new Cn({...ve(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new El({...ve(this._def),innerType:this,defaultValue:t,typeName:D.ZodDefault})}brand(){return new Dv({typeName:D.ZodBranded,type:this,...ve(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new Il({...ve(this._def),innerType:this,catchValue:t,typeName:D.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Zp.create(this,e)}readonly(){return Al.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function yA(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function B8(e){return new RegExp(`^${yA(e)}$`)}function q8(e){let t=`${gA}T${yA(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function F8(e,t){if((t==="v4"||!t)&&z8.test(e))return!0;if((t==="v6"||!t)&&N8.test(e))return!0;return!1}function V8(e,t){if(!A8.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));if(typeof s!=="object"||s===null)return!1;if("typ"in s&&s?.typ!=="JWT")return!1;if(!s.alg)return!1;if(t&&s.alg!==t)return!1;return!0}catch{return!1}}function Z8(e,t){if((t==="v4"||!t)&&M8.test(e))return!0;if((t==="v6"||!t)&&L8.test(e))return!0;return!1}function H8(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(e.toFixed(s).replace(".","")),i=Number.parseInt(t.toFixed(s).replace(".",""));return o%i/10**s}function Yi(e){if(e instanceof ft){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Rn.create(Yi(n))}return new ft({...e._def,shape:()=>t})}else if(e instanceof An)return new An({...e._def,type:Yi(e.element)});else if(e instanceof Rn)return Rn.create(Yi(e.unwrap()));else if(e instanceof Zs)return Zs.create(Yi(e.unwrap()));else if(e instanceof ms)return ms.create(e.items.map((t)=>Yi(t)));else return e}function Nv(e,t){let r=us(e),n=us(t);if(e===t)return{valid:!0,data:e};else if(r===K.object&&n===K.object){let s=Ce.objectKeys(t),o=Ce.objectKeys(e).filter((a)=>s.indexOf(a)!==-1),i={...e,...t};if(Object.prototype.hasOwnProperty.call(i,"__proto__"))delete i.__proto__;for(let a of o){if(a==="__proto__")continue;let c=Nv(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===K.array&&n===K.array){if(e.length!==t.length)return{valid:!1};let s=[];for(let o=0;o<e.length;o++){let i=e[o],a=t[o],c=Nv(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else if(r===K.date&&n===K.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}function wA(e,t){return new Ho({values:e,typeName:D.ZodEnum,...ve(t)})}var hA=(e,t)=>{if(Vo(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Lr(e.common.issues);return this._error=r,this._error}}}},k8,T8,P8,E8,I8,A8,R8,C8,O8="^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",Mv,z8,M8,N8,L8,D8,j8,gA="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",U8,ps,ea,ta,Dp,vl,jp,_l,xl,Up,Zo,fs,Bp,An,ft,Sl,ds=(e)=>{if(e instanceof kl)return ds(e.schema);else if(e instanceof Cn)return ds(e.innerType());else if(e instanceof Tl)return[e.value];else if(e instanceof Ho)return e.options;else if(e instanceof Pl)return Ce.objectValues(e.enum);else if(e instanceof El)return ds(e._def.innerType);else if(e instanceof _l)return[void 0];else if(e instanceof xl)return[null];else if(e instanceof Rn)return[void 0,...ds(e.unwrap())];else if(e instanceof Zs)return[null,...ds(e.unwrap())];else if(e instanceof Dv)return ds(e.unwrap());else if(e instanceof Al)return ds(e.unwrap());else if(e instanceof Il)return ds(e._def.innerType);else return[]},Lv,$l,ms,qp,Fp,ra,bl,kl,Tl,Ho,Pl,na,Cn,Rn,Zs,El,Il,Vp,Mde,Dv,Zp,Al,Nde,D,Lde,Dde,jde,Ude,Bde,qde,Fde,Vde,Zde,Hde,Gde,Kde,Wde,Jde,bA,Qde,Xde,Yde,epe,tpe,rpe,npe,spe,ope,ipe,ape,cpe,lpe,upe,dpe,ppe,fpe,mpe,hpe;var vA=b(()=>{Mp();Np();mA();zv();gl();k8=/^c[^\s-]{8,}$/i,T8=/^[0-9a-z]+$/,P8=/^[0-9A-HJKMNP-TV-Z]{26}$/i,E8=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,I8=/^[a-z0-9_-]{21}$/i,A8=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,R8=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,C8=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,z8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,M8=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,N8=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,L8=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,D8=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,j8=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,U8=new RegExp(`^${gA}$`);ps=class ps extends Ie{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==K.string){let s=this._getOrReturnCtx(e);return V(s,{code:L.invalid_type,expected:K.string,received:s.parsedType}),fe}let r=new Yt,n=void 0;for(let s of this._def.checks)if(s.kind==="min"){if(e.data.length<s.value)n=this._getOrReturnCtx(e,n),V(n,{code:L.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="max"){if(e.data.length>s.value)n=this._getOrReturnCtx(e,n),V(n,{code:L.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="length"){let o=e.data.length>s.value,i=e.data.length<s.value;if(o||i){if(n=this._getOrReturnCtx(e,n),o)V(n,{code:L.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});else if(i)V(n,{code:L.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});r.dirty()}}else if(s.kind==="email"){if(!C8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"email",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="emoji"){if(!Mv)Mv=new RegExp(O8,"u");if(!Mv.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"emoji",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="uuid"){if(!E8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"uuid",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="nanoid"){if(!I8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"nanoid",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="cuid"){if(!k8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"cuid",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="cuid2"){if(!T8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"cuid2",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="ulid"){if(!P8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"ulid",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),V(n,{validation:"url",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="regex"){if(s.regex.lastIndex=0,!s.regex.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"regex",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="trim")e.data=e.data.trim();else if(s.kind==="includes"){if(!e.data.includes(s.value,s.position))n=this._getOrReturnCtx(e,n),V(n,{code:L.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()}else if(s.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(s.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(s.kind==="startsWith"){if(!e.data.startsWith(s.value))n=this._getOrReturnCtx(e,n),V(n,{code:L.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()}else if(s.kind==="endsWith"){if(!e.data.endsWith(s.value))n=this._getOrReturnCtx(e,n),V(n,{code:L.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()}else if(s.kind==="datetime"){if(!q8(s).test(e.data))n=this._getOrReturnCtx(e,n),V(n,{code:L.invalid_string,validation:"datetime",message:s.message}),r.dirty()}else if(s.kind==="date"){if(!U8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{code:L.invalid_string,validation:"date",message:s.message}),r.dirty()}else if(s.kind==="time"){if(!B8(s).test(e.data))n=this._getOrReturnCtx(e,n),V(n,{code:L.invalid_string,validation:"time",message:s.message}),r.dirty()}else if(s.kind==="duration"){if(!R8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"duration",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="ip"){if(!F8(e.data,s.version))n=this._getOrReturnCtx(e,n),V(n,{validation:"ip",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="jwt"){if(!V8(e.data,s.alg))n=this._getOrReturnCtx(e,n),V(n,{validation:"jwt",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="cidr"){if(!Z8(e.data,s.version))n=this._getOrReturnCtx(e,n),V(n,{validation:"cidr",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="base64"){if(!D8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"base64",code:L.invalid_string,message:s.message}),r.dirty()}else if(s.kind==="base64url"){if(!j8.test(e.data))n=this._getOrReturnCtx(e,n),V(n,{validation:"base64url",code:L.invalid_string,message:s.message}),r.dirty()}else Ce.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:L.invalid_string,...re.errToObj(r)})}_addCheck(e){return new ps({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...re.errToObj(e)})}url(e){return this._addCheck({kind:"url",...re.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...re.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...re.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...re.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...re.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...re.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...re.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...re.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...re.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...re.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...re.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...re.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...re.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...re.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...re.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...re.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...re.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...re.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...re.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...re.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...re.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...re.errToObj(t)})}nonempty(e){return this.min(1,re.errToObj(e))}trim(){return new ps({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ps({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ps({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}};ps.create=(e)=>new ps({checks:[],typeName:D.ZodString,coerce:e?.coerce??!1,...ve(e)});ea=class ea extends Ie{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==K.number){let s=this._getOrReturnCtx(e);return V(s,{code:L.invalid_type,expected:K.number,received:s.parsedType}),fe}let r=void 0,n=new Yt;for(let s of this._def.checks)if(s.kind==="int"){if(!Ce.isInteger(e.data))r=this._getOrReturnCtx(e,r),V(r,{code:L.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()}else if(s.kind==="min"){if(s.inclusive?e.data<s.value:e.data<=s.value)r=this._getOrReturnCtx(e,r),V(r,{code:L.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()}else if(s.kind==="max"){if(s.inclusive?e.data>s.value:e.data>=s.value)r=this._getOrReturnCtx(e,r),V(r,{code:L.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()}else if(s.kind==="multipleOf"){if(H8(e.data,s.value)!==0)r=this._getOrReturnCtx(e,r),V(r,{code:L.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()}else if(s.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),V(r,{code:L.not_finite,message:s.message}),n.dirty()}else Ce.assertNever(s);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,re.toString(t))}gt(e,t){return this.setLimit("min",e,!1,re.toString(t))}lte(e,t){return this.setLimit("max",e,!0,re.toString(t))}lt(e,t){return this.setLimit("max",e,!1,re.toString(t))}setLimit(e,t,r,n){return new ea({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:re.toString(n)}]})}_addCheck(e){return new ea({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:re.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:re.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:re.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:re.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:re.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:re.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&Ce.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}};ea.create=(e)=>new ea({checks:[],typeName:D.ZodNumber,coerce:e?.coerce||!1,...ve(e)});ta=class ta extends Ie{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==K.bigint)return this._getInvalidInput(e);let r=void 0,n=new Yt;for(let s of this._def.checks)if(s.kind==="min"){if(s.inclusive?e.data<s.value:e.data<=s.value)r=this._getOrReturnCtx(e,r),V(r,{code:L.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()}else if(s.kind==="max"){if(s.inclusive?e.data>s.value:e.data>=s.value)r=this._getOrReturnCtx(e,r),V(r,{code:L.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()}else if(s.kind==="multipleOf"){if(e.data%s.value!==BigInt(0))r=this._getOrReturnCtx(e,r),V(r,{code:L.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()}else Ce.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return V(t,{code:L.invalid_type,expected:K.bigint,received:t.parsedType}),fe}gte(e,t){return this.setLimit("min",e,!0,re.toString(t))}gt(e,t){return this.setLimit("min",e,!1,re.toString(t))}lte(e,t){return this.setLimit("max",e,!0,re.toString(t))}lt(e,t){return this.setLimit("max",e,!1,re.toString(t))}setLimit(e,t,r,n){return new ta({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:re.toString(n)}]})}_addCheck(e){return new ta({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:re.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:re.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:re.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:re.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:re.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}};ta.create=(e)=>new ta({checks:[],typeName:D.ZodBigInt,coerce:e?.coerce??!1,...ve(e)});Dp=class Dp extends Ie{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==K.boolean){let r=this._getOrReturnCtx(e);return V(r,{code:L.invalid_type,expected:K.boolean,received:r.parsedType}),fe}return ar(e.data)}};Dp.create=(e)=>new Dp({typeName:D.ZodBoolean,coerce:e?.coerce||!1,...ve(e)});vl=class vl extends Ie{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==K.date){let s=this._getOrReturnCtx(e);return V(s,{code:L.invalid_type,expected:K.date,received:s.parsedType}),fe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return V(s,{code:L.invalid_date}),fe}let r=new Yt,n=void 0;for(let s of this._def.checks)if(s.kind==="min"){if(e.data.getTime()<s.value)n=this._getOrReturnCtx(e,n),V(n,{code:L.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()}else if(s.kind==="max"){if(e.data.getTime()>s.value)n=this._getOrReturnCtx(e,n),V(n,{code:L.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()}else Ce.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new vl({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:re.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:re.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}};vl.create=(e)=>new vl({checks:[],coerce:e?.coerce||!1,typeName:D.ZodDate,...ve(e)});jp=class jp extends Ie{_parse(e){if(this._getType(e)!==K.symbol){let r=this._getOrReturnCtx(e);return V(r,{code:L.invalid_type,expected:K.symbol,received:r.parsedType}),fe}return ar(e.data)}};jp.create=(e)=>new jp({typeName:D.ZodSymbol,...ve(e)});_l=class _l extends Ie{_parse(e){if(this._getType(e)!==K.undefined){let r=this._getOrReturnCtx(e);return V(r,{code:L.invalid_type,expected:K.undefined,received:r.parsedType}),fe}return ar(e.data)}};_l.create=(e)=>new _l({typeName:D.ZodUndefined,...ve(e)});xl=class xl extends Ie{_parse(e){if(this._getType(e)!==K.null){let r=this._getOrReturnCtx(e);return V(r,{code:L.invalid_type,expected:K.null,received:r.parsedType}),fe}return ar(e.data)}};xl.create=(e)=>new xl({typeName:D.ZodNull,...ve(e)});Up=class Up extends Ie{constructor(){super(...arguments);this._any=!0}_parse(e){return ar(e.data)}};Up.create=(e)=>new Up({typeName:D.ZodAny,...ve(e)});Zo=class Zo extends Ie{constructor(){super(...arguments);this._unknown=!0}_parse(e){return ar(e.data)}};Zo.create=(e)=>new Zo({typeName:D.ZodUnknown,...ve(e)});fs=class fs extends Ie{_parse(e){let t=this._getOrReturnCtx(e);return V(t,{code:L.invalid_type,expected:K.never,received:t.parsedType}),fe}};fs.create=(e)=>new fs({typeName:D.ZodNever,...ve(e)});Bp=class Bp extends Ie{_parse(e){if(this._getType(e)!==K.undefined){let r=this._getOrReturnCtx(e);return V(r,{code:L.invalid_type,expected:K.void,received:r.parsedType}),fe}return ar(e.data)}};Bp.create=(e)=>new Bp({typeName:D.ZodVoid,...ve(e)});An=class An extends Ie{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==K.array)return V(t,{code:L.invalid_type,expected:K.array,received:t.parsedType}),fe;if(n.exactLength!==null){let o=t.data.length>n.exactLength.value,i=t.data.length<n.exactLength.value;if(o||i)V(t,{code:o?L.too_big:L.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)V(t,{code:L.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)V(t,{code:L.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((o,i)=>n.type._parseAsync(new pn(t,o,t.path,i)))).then((o)=>Yt.mergeArray(r,o));let s=[...t.data].map((o,i)=>n.type._parseSync(new pn(t,o,t.path,i)));return Yt.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new An({...this._def,minLength:{value:e,message:re.toString(t)}})}max(e,t){return new An({...this._def,maxLength:{value:e,message:re.toString(t)}})}length(e,t){return new An({...this._def,exactLength:{value:e,message:re.toString(t)}})}nonempty(e){return this.min(1,e)}};An.create=(e,t)=>new An({type:e,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...ve(t)});ft=class ft extends Ie{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Ce.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==K.object){let c=this._getOrReturnCtx(e);return V(c,{code:L.invalid_type,expected:K.object,received:c.parsedType}),fe}let{status:r,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof fs&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!o.includes(c))i.push(c)}let a=[];for(let c of o){let l=s[c],u=n.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new pn(n,u,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof fs){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of i)a.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(c==="strict"){if(i.length>0)V(n,{code:L.unrecognized_keys,keys:i}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of i){let u=n.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new pn(n,u,n.path,l)),alwaysSet:l in n.data})}}if(n.common.async)return Promise.resolve().then(async()=>{let c=[];for(let l of a){let u=await l.key,d=await l.value;c.push({key:u,value:d,alwaysSet:l.alwaysSet})}return c}).then((c)=>Yt.mergeObjectSync(r,c));else return Yt.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return re.errToObj,new ft({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:re.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new ft({...this._def,unknownKeys:"strip"})}passthrough(){return new ft({...this._def,unknownKeys:"passthrough"})}extend(e){return new ft({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ft({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ft({...this._def,catchall:e})}pick(e){let t={};for(let r of Ce.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new ft({...this._def,shape:()=>t})}omit(e){let t={};for(let r of Ce.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new ft({...this._def,shape:()=>t})}deepPartial(){return Yi(this)}partial(e){let t={};for(let r of Ce.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new ft({...this._def,shape:()=>t})}required(e){let t={};for(let r of Ce.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let s=this.shape[r];while(s instanceof Rn)s=s._def.innerType;t[r]=s}return new ft({...this._def,shape:()=>t})}keyof(){return wA(Ce.objectKeys(this.shape))}};ft.create=(e,t)=>new ft({shape:()=>e,unknownKeys:"strip",catchall:fs.create(),typeName:D.ZodObject,...ve(t)});ft.strictCreate=(e,t)=>new ft({shape:()=>e,unknownKeys:"strict",catchall:fs.create(),typeName:D.ZodObject,...ve(t)});ft.lazycreate=(e,t)=>new ft({shape:e,unknownKeys:"strip",catchall:fs.create(),typeName:D.ZodObject,...ve(t)});Sl=class Sl extends Ie{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(s){for(let i of s)if(i.result.status==="valid")return i.result;for(let i of s)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let o=s.map((i)=>new Lr(i.ctx.common.issues));return V(t,{code:L.invalid_union,unionErrors:o}),fe}if(t.common.async)return Promise.all(r.map(async(s)=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(n);else{let s=void 0,o=[];for(let a of r){let c={...t,common:{...t.common,issues:[]},parent:null},l=a._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;else if(l.status==="dirty"&&!s)s={result:l,ctx:c};if(c.common.issues.length)o.push(c.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map((a)=>new Lr(a));return V(t,{code:L.invalid_union,unionErrors:i}),fe}}get options(){return this._def.options}};Sl.create=(e,t)=>new Sl({options:e,typeName:D.ZodUnion,...ve(t)});Lv=class Lv extends Ie{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==K.object)return V(t,{code:L.invalid_type,expected:K.object,received:t.parsedType}),fe;let r=this.discriminator,n=t.data[r],s=this.optionsMap.get(n);if(!s)return V(t,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),fe;if(t.common.async)return s._parseAsync({data:t.data,path:t.path,parent:t});else return s._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let n=new Map;for(let s of t){let o=ds(s.shape[e]);if(!o.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of o){if(n.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new Lv({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...ve(r)})}};$l=class $l extends Ie{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(s,o)=>{if(Cv(s)||Cv(o))return fe;let i=Nv(s.value,o.value);if(!i.valid)return V(r,{code:L.invalid_intersection_types}),fe;if(Ov(s)||Ov(o))t.dirty();return{status:t.value,value:i.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,o])=>n(s,o));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};$l.create=(e,t,r)=>new $l({left:e,right:t,typeName:D.ZodIntersection,...ve(r)});ms=class ms extends Ie{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==K.array)return V(r,{code:L.invalid_type,expected:K.array,received:r.parsedType}),fe;if(r.data.length<this._def.items.length)return V(r,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),fe;if(!this._def.rest&&r.data.length>this._def.items.length)V(r,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let s=[...r.data].map((o,i)=>{let a=this._def.items[i]||this._def.rest;if(!a)return null;return a._parse(new pn(r,o,r.path,i))}).filter((o)=>!!o);if(r.common.async)return Promise.all(s).then((o)=>Yt.mergeArray(t,o));else return Yt.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ms({...this._def,rest:e})}};ms.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ms({items:e,typeName:D.ZodTuple,rest:null,...ve(t)})};qp=class qp extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==K.object)return V(r,{code:L.invalid_type,expected:K.object,received:r.parsedType}),fe;let n=[],s=this._def.keyType,o=this._def.valueType;for(let i in r.data)n.push({key:s._parse(new pn(r,i,r.path,i)),value:o._parse(new pn(r,r.data[i],r.path,i)),alwaysSet:i in r.data});if(r.common.async)return Yt.mergeObjectAsync(t,n);else return Yt.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof Ie)return new qp({keyType:e,valueType:t,typeName:D.ZodRecord,...ve(r)});return new qp({keyType:ps.create(),valueType:e,typeName:D.ZodRecord,...ve(t)})}};Fp=class Fp extends Ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==K.map)return V(r,{code:L.invalid_type,expected:K.map,received:r.parsedType}),fe;let n=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([i,a],c)=>({key:n._parse(new pn(r,i,r.path,[c,"key"])),value:s._parse(new pn(r,a,r.path,[c,"value"]))}));if(r.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let a of o){let c=await a.key,l=await a.value;if(c.status==="aborted"||l.status==="aborted")return fe;if(c.status==="dirty"||l.status==="dirty")t.dirty();i.set(c.value,l.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let a of o){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return fe;if(c.status==="dirty"||l.status==="dirty")t.dirty();i.set(c.value,l.value)}return{status:t.value,value:i}}}};Fp.create=(e,t,r)=>new Fp({valueType:t,keyType:e,typeName:D.ZodMap,...ve(r)});ra=class ra extends Ie{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==K.set)return V(r,{code:L.invalid_type,expected:K.set,received:r.parsedType}),fe;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)V(r,{code:L.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)V(r,{code:L.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let s=this._def.valueType;function o(a){let c=new Set;for(let l of a){if(l.status==="aborted")return fe;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let i=[...r.data.values()].map((a,c)=>s._parse(new pn(r,a,r.path,c)));if(r.common.async)return Promise.all(i).then((a)=>o(a));else return o(i)}min(e,t){return new ra({...this._def,minSize:{value:e,message:re.toString(t)}})}max(e,t){return new ra({...this._def,maxSize:{value:e,message:re.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ra.create=(e,t)=>new ra({valueType:e,minSize:null,maxSize:null,typeName:D.ZodSet,...ve(t)});bl=class bl extends Ie{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==K.function)return V(t,{code:L.invalid_type,expected:K.function,received:t.parsedType}),fe;function r(i,a){return Lp({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,yl(),Vs].filter((c)=>!!c),issueData:{code:L.invalid_arguments,argumentsError:a}})}function n(i,a){return Lp({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,yl(),Vs].filter((c)=>!!c),issueData:{code:L.invalid_return_type,returnTypeError:a}})}let s={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof na){let i=this;return ar(async function(...a){let c=new Lr([]),l=await i._def.args.parseAsync(a,s).catch((p)=>{throw c.addIssue(r(a,p)),c}),u=await Reflect.apply(o,this,l);return await i._def.returns._def.type.parseAsync(u,s).catch((p)=>{throw c.addIssue(n(u,p)),c})})}else{let i=this;return ar(function(...a){let c=i._def.args.safeParse(a,s);if(!c.success)throw new Lr([r(a,c.error)]);let l=Reflect.apply(o,this,c.data),u=i._def.returns.safeParse(l,s);if(!u.success)throw new Lr([n(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new bl({...this._def,args:ms.create(e).rest(Zo.create())})}returns(e){return new bl({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new bl({args:e?e:ms.create([]).rest(Zo.create()),returns:t||Zo.create(),typeName:D.ZodFunction,...ve(r)})}};kl=class kl extends Ie{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};kl.create=(e,t)=>new kl({getter:e,typeName:D.ZodLazy,...ve(t)});Tl=class Tl extends Ie{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return V(t,{received:t.data,code:L.invalid_literal,expected:this._def.value}),fe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Tl.create=(e,t)=>new Tl({value:e,typeName:D.ZodLiteral,...ve(t)});Ho=class Ho extends Ie{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return V(t,{expected:Ce.joinValues(r),received:t.parsedType,code:L.invalid_type}),fe}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return V(t,{received:t.data,code:L.invalid_enum_value,options:r}),fe}return ar(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ho.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ho.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}};Ho.create=wA;Pl=class Pl extends Ie{_parse(e){let t=Ce.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==K.string&&r.parsedType!==K.number){let n=Ce.objectValues(t);return V(r,{expected:Ce.joinValues(n),received:r.parsedType,code:L.invalid_type}),fe}if(!this._cache)this._cache=new Set(Ce.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=Ce.objectValues(t);return V(r,{received:r.data,code:L.invalid_enum_value,options:n}),fe}return ar(e.data)}get enum(){return this._def.values}};Pl.create=(e,t)=>new Pl({values:e,typeName:D.ZodNativeEnum,...ve(t)});na=class na extends Ie{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==K.promise&&t.common.async===!1)return V(t,{code:L.invalid_type,expected:K.promise,received:t.parsedType}),fe;let r=t.parsedType===K.promise?t.data:Promise.resolve(t.data);return ar(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};na.create=(e,t)=>new na({type:e,typeName:D.ZodPromise,...ve(t)});Cn=class Cn extends Ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:(o)=>{if(V(r,o),o.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){let o=n.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async(i)=>{if(t.value==="aborted")return fe;let a=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});if(a.status==="aborted")return fe;if(a.status==="dirty")return Xi(a.value);if(t.value==="dirty")return Xi(a.value);return a});else{if(t.value==="aborted")return fe;let i=this._def.schema._parseSync({data:o,path:r.path,parent:r});if(i.status==="aborted")return fe;if(i.status==="dirty")return Xi(i.value);if(t.value==="dirty")return Xi(i.value);return i}}if(n.type==="refinement"){let o=(i)=>{let a=n.refinement(i,s);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(i.status==="aborted")return fe;if(i.status==="dirty")t.dirty();return o(i.value),{status:t.value,value:i.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((i)=>{if(i.status==="aborted")return fe;if(i.status==="dirty")t.dirty();return o(i.value).then(()=>({status:t.value,value:i.value}))})}if(n.type==="transform")if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Vo(o))return fe;let i=n.transform(o.value,s);if(i instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((o)=>{if(!Vo(o))return fe;return Promise.resolve(n.transform(o.value,s)).then((i)=>({status:t.value,value:i}))});Ce.assertNever(n)}};Cn.create=(e,t,r)=>new Cn({schema:e,typeName:D.ZodEffects,effect:t,...ve(r)});Cn.createWithPreprocess=(e,t,r)=>new Cn({schema:t,effect:{type:"preprocess",transform:e},typeName:D.ZodEffects,...ve(r)});Rn=class Rn extends Ie{_parse(e){if(this._getType(e)===K.undefined)return ar(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Rn.create=(e,t)=>new Rn({innerType:e,typeName:D.ZodOptional,...ve(t)});Zs=class Zs extends Ie{_parse(e){if(this._getType(e)===K.null)return ar(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Zs.create=(e,t)=>new Zs({innerType:e,typeName:D.ZodNullable,...ve(t)});El=class El extends Ie{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===K.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};El.create=(e,t)=>new El({innerType:e,typeName:D.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...ve(t)});Il=class Il extends Ie{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(wl(n))return n.then((s)=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Lr(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Lr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Il.create=(e,t)=>new Il({innerType:e,typeName:D.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...ve(t)});Vp=class Vp extends Ie{_parse(e){if(this._getType(e)!==K.nan){let r=this._getOrReturnCtx(e);return V(r,{code:L.invalid_type,expected:K.nan,received:r.parsedType}),fe}return{status:"valid",value:e.data}}};Vp.create=(e)=>new Vp({typeName:D.ZodNaN,...ve(e)});Mde=Symbol("zod_brand");Dv=class Dv extends Ie{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};Zp=class Zp extends Ie{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(s.status==="aborted")return fe;if(s.status==="dirty")return t.dirty(),Xi(s.value);else return this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return fe;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new Zp({in:e,out:t,typeName:D.ZodPipeline})}};Al=class Al extends Ie{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Vo(n))n.value=Object.freeze(n.value);return n};return wl(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}};Al.create=(e,t)=>new Al({innerType:e,typeName:D.ZodReadonly,...ve(t)});Nde={object:ft.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(D||(D={}));Lde=ps.create,Dde=ea.create,jde=Vp.create,Ude=ta.create,Bde=Dp.create,qde=vl.create,Fde=jp.create,Vde=_l.create,Zde=xl.create,Hde=Up.create,Gde=Zo.create,Kde=fs.create,Wde=Bp.create,Jde=An.create,bA=ft.create,Qde=ft.strictCreate,Xde=Sl.create,Yde=Lv.create,epe=$l.create,tpe=ms.create,rpe=qp.create,npe=Fp.create,spe=ra.create,ope=bl.create,ipe=kl.create,ape=Tl.create,cpe=Ho.create,lpe=Pl.create,upe=na.create,dpe=Cn.create,ppe=Rn.create,fpe=Zs.create,mpe=Cn.createWithPreprocess,hpe=Zp.create});var _A=b(()=>{Np();zv();fA();gl();vA();Mp()});var Rl=b(()=>{_A()});var jv=b(()=>{yr()});function Uv(e,t){let r={type:"object",shape:e??{},...ee(t)};return new J8(r)}var W8,J8;var xA=b(()=>{yr();rr();jv();W8=R("ZodMiniType",(e,t)=>{if(!e._zod)throw Error("Uninitialized schema in ZodMiniType.");He.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){sn(this,"with",e)},parse(e,t){return ch(this,e,t,{callee:this.parse})},parseAsync(e,t){return lh(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return rc(this,e,t)},safeParseAsync(e,t){return sc(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0})},clone(e,t){return pr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),J8=R("ZodMiniObject",(e,t)=>{Hh.init(e,t),W8.init(e,t),th(e,"shape",(r)=>r._zod.def.shape,!1)})});var SA=()=>{};var $A=()=>{};var kA=()=>{};var TA=b(()=>{yr();Zu();Nu();$A();kA();jv();xA();SA()});var Bv=b(()=>{TA()});function On(e){return!!e._zod}function Go(e){let t=Object.values(e);if(t.length===0)return Uv({});let r=t.every(On),n=t.every((s)=>!On(s));if(r)return Uv(e);if(n)return bA(e);throw Error("Mixed Zod versions detected in object shape.")}function Hs(e,t){if(On(e))return rc(e,t);return e.safeParse(t)}async function Hp(e,t){if(On(e))return await sc(e,t);return await e.safeParseAsync(t)}function Gs(e){if(!e)return;let t;if(On(e))t=e._zod?.def?.shape;else t=e.shape;if(!t)return;if(typeof t==="function")try{return t()}catch{return}return t}function sa(e){if(!e)return;if(typeof e==="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);if(n.length>0&&n.every((s)=>typeof s==="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse==="function")))return Go(e)}}if(On(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e;return}function Y8(e){if(e.length===0)return"object root";return e.reduce((t,r,n)=>{if(n===0)return String(r);if(typeof r==="number")return`${t}[${r}]`;return`${t}.${r}`},"")}function Gp(e){if(e&&typeof e==="object"){if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map((t)=>{if(!t.path?.length)return t.message;return`${t.message} at ${Y8(t.path)}`}).join(`
|
|
102
|
+
`);if("message"in e&&typeof e.message==="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function EA(e){return e.description}function IA(e){if(On(e))return e._zod?.def?.type==="optional";let t=e;if(typeof e.isOptional==="function")return e.isOptional();return t._def?.typeName==="ZodOptional"}function oa(e){if(On(e)){let o=e._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n;return}var Cl=b(()=>{Rl();Bv()});function Ks(e){return e==="completed"||e==="failed"||e==="cancelled"}var RA,AA,CA=(e)=>typeof e==="string"?{...AA,name:e}:{...AA,...e};var Kp=b(()=>{RA=Symbol("Let zodToJsonSchema decide on which parser to use"),AA={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"}});var OA=(e)=>{let t=CA(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};var qv=b(()=>{Kp()});function Fv(e,t,r,n){if(!n?.errorMessages)return;if(r)e.errorMessage={...e.errorMessage,[t]:r}}function Oe(e,t,r,n,s){e[t]=r,Fv(e,t,n,s)}var Wp=(e,t)=>{let r=0;for(;r<e.length&&r<t.length;r++)if(e[r]!==t[r])break;return[(e.length-r).toString(),...t.slice(r)].join("/")};function nt(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Wp(t,e.currentPath):t.join("/")}}var Wr=()=>{};function zA(e,t){let r={type:"array"};if(e.type?._def&&e.type?._def?.typeName!==D.ZodAny)r.items=me(e.type._def,{...t,currentPath:[...t.currentPath,"items"]});if(e.minLength)Oe(r,"minItems",e.minLength.value,e.minLength.message,t);if(e.maxLength)Oe(r,"maxItems",e.maxLength.value,e.maxLength.message,t);if(e.exactLength)Oe(r,"minItems",e.exactLength.value,e.exactLength.message,t),Oe(r,"maxItems",e.exactLength.value,e.exactLength.message,t);return r}var Vv=b(()=>{Rl();Et()});function MA(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":if(t.target==="jsonSchema7")if(n.inclusive)Oe(r,"minimum",n.value,n.message,t);else Oe(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;Oe(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)Oe(r,"maximum",n.value,n.message,t);else Oe(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;Oe(r,"maximum",n.value,n.message,t)}break;case"multipleOf":Oe(r,"multipleOf",n.value,n.message,t);break}return r}var Zv=()=>{};function NA(){return{type:"boolean"}}function Jp(e,t){return me(e.type._def,t)}var Qp=b(()=>{Et()});var LA=(e,t)=>me(e.innerType._def,t);var Hv=b(()=>{Et()});function Gv(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Gv(e,t,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return eF(e,t)}}var eF=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":Oe(r,"minimum",n.value,n.message,t);break;case"max":Oe(r,"maximum",n.value,n.message,t);break}return r};var Kv=()=>{};function DA(e,t){return{...me(e.innerType._def,t),default:e.defaultValue()}}var Wv=b(()=>{Et()});function jA(e,t){return t.effectStrategy==="input"?me(e.schema._def,t):nt(t)}var Jv=b(()=>{Et();Wr()});function UA(e){return{type:"string",enum:Array.from(e.values)}}function BA(e,t){let r=[me(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),me(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((o)=>!!o),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach((o)=>{if(tF(o)){if(s.push(...o.allOf),o.unevaluatedProperties===void 0)n=void 0}else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var tF=(e)=>{if("type"in e&&e.type==="string")return!1;return"allOf"in e};var Qv=b(()=>{Et()});function qA(e,t){let r=typeof e.value;if(r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string")return{type:Array.isArray(e.value)?"array":"object"};if(t.target==="openApi3")return{type:r==="bigint"?"integer":r,enum:[e.value]};return{type:r==="bigint"?"integer":r,const:e.value}}function Xp(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":Oe(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Oe(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":mn(r,"email",n.message,t);break;case"format:idn-email":mn(r,"idn-email",n.message,t);break;case"pattern:zod":cr(r,fn.email,n.message,t);break}break;case"url":mn(r,"uri",n.message,t);break;case"uuid":mn(r,"uuid",n.message,t);break;case"regex":cr(r,n.regex,n.message,t);break;case"cuid":cr(r,fn.cuid,n.message,t);break;case"cuid2":cr(r,fn.cuid2,n.message,t);break;case"startsWith":cr(r,RegExp(`^${Yv(n.value,t)}`),n.message,t);break;case"endsWith":cr(r,RegExp(`${Yv(n.value,t)}$`),n.message,t);break;case"datetime":mn(r,"date-time",n.message,t);break;case"date":mn(r,"date",n.message,t);break;case"time":mn(r,"time",n.message,t);break;case"duration":mn(r,"duration",n.message,t);break;case"length":Oe(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Oe(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{cr(r,RegExp(Yv(n.value,t)),n.message,t);break}case"ip":{if(n.version!=="v6")mn(r,"ipv4",n.message,t);if(n.version!=="v4")mn(r,"ipv6",n.message,t);break}case"base64url":cr(r,fn.base64url,n.message,t);break;case"jwt":cr(r,fn.jwt,n.message,t);break;case"cidr":{if(n.version!=="v6")cr(r,fn.ipv4Cidr,n.message,t);if(n.version!=="v4")cr(r,fn.ipv6Cidr,n.message,t);break}case"emoji":cr(r,fn.emoji(),n.message,t);break;case"ulid":{cr(r,fn.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{mn(r,"binary",n.message,t);break}case"contentEncoding:base64":{Oe(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{cr(r,fn.base64,n.message,t);break}}break}case"nanoid":cr(r,fn.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:((s)=>{})(n)}return r}function Yv(e,t){return t.patternStrategy==="escape"?nF(e):e}function nF(e){let t="";for(let r=0;r<e.length;r++){if(!rF.has(e[r]))t+="\\";t+=e[r]}return t}function mn(e,t,r,n){if(e.format||e.anyOf?.some((s)=>s.format)){if(!e.anyOf)e.anyOf=[];if(e.format){if(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage){if(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})}else Oe(e,"format",t,r,n)}function cr(e,t,r,n){if(e.pattern||e.allOf?.some((s)=>s.pattern)){if(!e.allOf)e.allOf=[];if(e.pattern){if(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage){if(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0)delete e.errorMessage}}e.allOf.push({pattern:FA(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})}else Oe(e,"pattern",FA(t,n),r,n)}function FA(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){if(a)s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1;else if(n[c+1]==="-"&&n[c+2]?.match(/[a-z]/))s+=n[c],a=!0;else s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
103
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
104
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
|
105
|
+
`:`[${n[c]}\r
|
|
106
|
+
]`;continue}if(s+=n[c],n[c]==="\\")o=!0;else if(i&&n[c]==="]")i=!1;else if(!i&&n[c]==="[")i=!0}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}var Xv=void 0,fn,rF;var Yp=b(()=>{fn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Xv===void 0)Xv=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Xv},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};rF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function ef(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,s)=>({...n,[s]:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",s]})??nt(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===D.ZodString&&e.keyType._def.checks?.length){let{type:n,...s}=Xp(e.keyType._def,t);return{...r,propertyNames:s}}else if(e.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===D.ZodBranded&&e.keyType._def.type._def.typeName===D.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...s}=Jp(e.keyType._def,t);return{...r,propertyNames:s}}return r}var tf=b(()=>{Rl();Et();Yp();Qp();Wr()});function VA(e,t){if(t.mapStrategy==="record")return ef(e,t);let r=me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||nt(t),n=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||nt(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var e_=b(()=>{Et();tf();Wr()});function ZA(e){let t=e.values,n=Object.keys(e.values).filter((o)=>typeof t[t[o]]!=="number").map((o)=>t[o]),s=Array.from(new Set(n.map((o)=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function HA(e){return e.target==="openAi"?void 0:{not:nt({...e,currentPath:[...e.currentPath,"not"]})}}var t_=b(()=>{Wr()});function GA(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}function WA(e,t){if(t.target==="openApi3")return KA(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in Ol)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Ol[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter((o)=>!n.includes(o))],[])};return KA(e,t)}var Ol,KA=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,s)=>me(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${s}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};var rf=b(()=>{Et();Ol={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"}});function JA(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:Ol[e.innerType._def.typeName],nullable:!0};return{type:[Ol[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=me(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var r_=b(()=>{Et();rf()});function QA(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Fv(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)Oe(r,"minimum",n.value,n.message,t);else Oe(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;Oe(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)Oe(r,"maximum",n.value,n.message,t);else Oe(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;Oe(r,"maximum",n.value,n.message,t)}break;case"multipleOf":Oe(r,"multipleOf",n.value,n.message,t);break}return r}var n_=()=>{};function XA(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},s=[],o=e.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let l=oF(c);if(l&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();l=!1}let u=me(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(u===void 0)continue;if(n.properties[a]=u,!l)s.push(a)}if(s.length)n.required=s;let i=sF(e,t);if(i!==void 0)n.additionalProperties=i;return n}function sF(e,t){if(e.catchall._def.typeName!=="ZodNever")return me(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function oF(e){try{return e.isOptional()}catch{return!0}}var s_=b(()=>{Et()});var YA=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return me(e.innerType._def,t);let r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:nt(t)},r]}:nt(t)};var o_=b(()=>{Et();Wr()});var eR=(e,t)=>{if(t.pipeStrategy==="input")return me(e.in._def,t);else if(t.pipeStrategy==="output")return me(e.out._def,t);let r=me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((s)=>s!==void 0)}};var i_=b(()=>{Et()});function tR(e,t){return me(e.type._def,t)}var a_=b(()=>{Et()});function rR(e,t){let n={type:"array",uniqueItems:!0,items:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)Oe(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)Oe(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}var c_=b(()=>{Et()});function nR(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var l_=b(()=>{Et()});function sR(e){return{not:nt(e)}}var u_=b(()=>{Wr()});function oR(e){return nt(e)}var d_=b(()=>{Wr()});var iR=(e,t)=>me(e.innerType._def,t);var p_=b(()=>{Et()});var aR=(e,t,r)=>{switch(t){case D.ZodString:return Xp(e,r);case D.ZodNumber:return QA(e,r);case D.ZodObject:return XA(e,r);case D.ZodBigInt:return MA(e,r);case D.ZodBoolean:return NA();case D.ZodDate:return Gv(e,r);case D.ZodUndefined:return sR(r);case D.ZodNull:return GA(r);case D.ZodArray:return zA(e,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return WA(e,r);case D.ZodIntersection:return BA(e,r);case D.ZodTuple:return nR(e,r);case D.ZodRecord:return ef(e,r);case D.ZodLiteral:return qA(e,r);case D.ZodEnum:return UA(e);case D.ZodNativeEnum:return ZA(e);case D.ZodNullable:return JA(e,r);case D.ZodOptional:return YA(e,r);case D.ZodMap:return VA(e,r);case D.ZodSet:return rR(e,r);case D.ZodLazy:return()=>e.getter()._def;case D.ZodPromise:return tR(e,r);case D.ZodNaN:case D.ZodNever:return HA(r);case D.ZodEffects:return jA(e,r);case D.ZodAny:return nt(r);case D.ZodUnknown:return oR(r);case D.ZodDefault:return DA(e,r);case D.ZodBranded:return Jp(e,r);case D.ZodReadonly:return iR(e,r);case D.ZodCatch:return LA(e,r);case D.ZodPipeline:return eR(e,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return((n)=>{return})(t)}};var f_=b(()=>{Rl();Wr();Vv();Zv();Qp();Hv();Kv();Wv();Jv();Qv();e_();t_();r_();n_();s_();o_();i_();a_();tf();c_();Yp();l_();u_();rf();d_();p_()});function me(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==RA)return a}if(n&&!r){let a=iF(n,t);if(a!==void 0)return a}let s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);let o=aR(e,e.typeName,t),i=typeof o==="function"?me(o(),t):o;if(i)aF(e,t,i);if(t.postProcess){let a=t.postProcess(i,e,t);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var iF=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Wp(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),nt(t);return t.$refStrategy==="seen"?nt(t):void 0}}},aF=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var Et=b(()=>{Kp();f_();Wr()});var cR=()=>{};var m_=(e,t)=>{let r=OA(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,u])=>({...c,[l]:me(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??nt(r)}),{}):void 0,s=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=me(e._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??nt(r),i=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(i!==void 0)o.title=i;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};var h_=b(()=>{Et();qv();Wr()});var lR=b(()=>{h_();Kp();qv();Et();cR();Wr();Vv();Zv();Qp();Hv();Kv();Wv();Jv();Qv();e_();t_();r_();n_();s_();o_();i_();a_();p_();tf();c_();Yp();l_();u_();rf();d_();f_();h_()});function cF(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function g_(e,t){if(On(e))return bc(e,{target:cF(t?.target),io:t?.pipeStrategy??"input"});return m_(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function y_(e){let r=Gs(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=oa(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function w_(e,t){let r=Hs(e,t);if(!r.success)throw r.error;return r.data}var b_=b(()=>{Bv();Cl();lR()});class v_{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(lp,(t)=>{this._oncancel(t)}),this.setNotificationHandler(pp,(t)=>{this._onprogress(t)}),this.setRequestHandler(dp,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(fp,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new te(ne.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(hp,async(t,r)=>{let n=async()=>{let s=t.params.taskId;if(!await this._taskStore.getTask(s,r.sessionId))throw new te(ne.InvalidParams,`Task not found: ${s}`);if(this._taskMessageQueue){let i;while(i=await this._taskMessageQueue.dequeue(s,r.sessionId)){if(i.type==="response"||i.type==="error"){let a=i.message,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),i.type==="response")l(a);else{let u=a,d=new te(u.error.code,u.error.message,u.error.data);l(d)}else{let u=i.type==="response"?"Response":"Error";this._onerror(Error(`${u} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}let o=await this._taskStore.getTask(s,r.sessionId);if(!o)throw new te(ne.InvalidParams,`Task not found: ${s}`);if(!Ks(o.status))return await this._waitForTaskUpdate(s,r.signal,r.sessionId),await n();if(Ks(o.status)){let i=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s,r.sessionId),{...i,_meta:{...i._meta,[qs]:{taskId:s}}}}return await n()};return await n()}),this.setRequestHandler(gp,async(t,r)=>{try{let{tasks:n,nextCursor:s}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:s,_meta:{}}}catch(n){throw new te(ne.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(wp,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new te(ne.InvalidParams,`Task not found: ${t.params.taskId}`);if(Ks(n.status))throw new te(ne.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);let s=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!s)throw new te(ne.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...s}}catch(n){if(n instanceof te)throw n;throw new te(ne.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),te.fromError(ne.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(s)=>{r?.(s),this._onerror(s)};let n=this._transport?.onmessage;this._transport.onmessage=(s,o)=>{if(n?.(s,o),is(s)||Hi(s))this._onresponse(s);else if(os(s))this._onrequest(s,o);else if(ZI(s))this._onnotification(s);else this._onerror(Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=te.fromError(ne.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,s=e.params?._meta?.[qs]?.taskId,o=n?.sessionId,i=this._taskStore,a=!0,c;if(s&&i&&this._taskMessageQueue&&o!==void 0)a=!1,c=(async()=>{if(!await i.getTask(s,o))throw new te(ne.InvalidParams,`Task not found: ${s}`);a=!0})();if(r===void 0){let f={jsonrpc:"2.0",id:e.id,error:{code:ne.MethodNotFound,message:"Method not found"}};if(s&&c){let m={type:"error",message:f,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(s,m,o),()=>n?.send(f)).catch((h)=>this._onerror(Error(`Failed to send an error response: ${h}`)))}else if(s&&this._taskMessageQueue)this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},n?.sessionId).catch((m)=>this._onerror(Error(`Failed to enqueue error response: ${m}`)));else n?.send(f).catch((m)=>this._onerror(Error(`Failed to send an error response: ${m}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=qI(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:l.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(f)=>{if(l.signal.aborted)return;let m={relatedRequestId:e.id};if(s)m.relatedTask={taskId:s};await this.notification(f,m)},sendRequest:async(f,m,h)=>{if(l.signal.aborted)throw new te(ne.ConnectionClosed,"Request was cancelled");let g={...h,relatedRequestId:e.id};if(s&&!g.relatedTask)g.relatedTask={taskId:s};let w=g.relatedTask?.taskId??s;if(w&&d)await d.updateTaskStatus(w,"input_required");return await this.request(f,m,g)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:s,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new te(ne.ConnectionClosed,"Request was cancelled");if(u)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async(f)=>{if(l.signal.aborted)return;let m={result:f,jsonrpc:"2.0",id:e.id};if(s&&this._taskMessageQueue)await this._enqueueTaskMessage(s,{type:"response",message:m,timestamp:Date.now()},n?.sessionId);else await n?.send(m)},async(f)=>{if(l.signal.aborted)return;let m={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(f.code)?f.code:ne.InternalError,message:f.message??"Internal error",...f.data!==void 0&&{data:f.data}}};if(s&&this._taskMessageQueue&&a)await this._enqueueTaskMessage(s,{type:"error",message:m,timestamp:Date.now()},n?.sessionId);else await n?.send(m)}).catch((f)=>this._onerror(Error(`Failed to send response: ${f}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===l)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),s=this._progressHandlers.get(n);if(!s){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),o(a);return}s(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),is(e))r(e);else{let o=new te(e.error.code,e.error.message,e.error.data);r(o)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let s=!1;if(is(e)&&e.result&&typeof e.result==="object"){let o=e.result;if(o.task&&typeof o.task==="object"){let i=o.task;if(typeof i.taskId==="string")s=!0,this._taskProgressTokens.set(i.taskId,t)}}if(!s)this._progressHandlers.delete(t);if(is(e))n(e);else{let o=te.fromError(e.error.code,e.error.message,e.error.data);n(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(o){yield{type:"error",error:o instanceof te?o:new te(ne.InternalError,String(o))}}return}let s;try{let o=await this.request(e,Gi,r);if(o.task)s=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new te(ne.InternalError,"Task creation did not return a task");while(!0){let i=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:i},Ks(i.status)){if(i.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:s},t,r)};else if(i.status==="failed")yield{type:"error",error:new te(ne.InternalError,`Task ${s} failed`)};else if(i.status==="cancelled")yield{type:"error",error:new te(ne.InternalError,`Task ${s} was cancelled`)};return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},t,r)};return}let a=i.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof te?o:new te(ne.InternalError,String(o))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o,task:i,relatedTask:a}=r??{};return new Promise((c,l)=>{let u=(w)=>{l(w)};if(!this._transport){u(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),i)this.assertTaskCapability(e.method)}catch(w){u(w);return}r?.signal?.throwIfAborted();let d=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:d};if(r?.onprogress)this._progressHandlers.set(d,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}};if(i)p.params={...p.params,task:i};if(a)p.params={...p.params,_meta:{...p.params?._meta||{},[qs]:a}};let f=(w)=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(w)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch((_)=>this._onerror(Error(`Failed to send cancellation: ${_}`)));let v=w instanceof te?w:new te(ne.RequestTimeout,String(w));l(v)};this._responseHandlers.set(d,(w)=>{if(r?.signal?.aborted)return;if(w instanceof Error)return l(w);try{let v=Hs(t,w.result);if(!v.success)l(v.error);else c(v.data)}catch(v){l(v)}}),r?.signal?.addEventListener("abort",()=>{f(r?.signal?.reason)});let m=r?.timeout??lF,h=()=>f(te.fromError(ne.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(d,m,r?.maxTotalTimeout,h,r?.resetTimeoutOnProgress??!1);let g=a?.taskId;if(g){let w=(v)=>{let _=this._responseHandlers.get(d);if(_)_(v);else this._onerror(Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,w),this._enqueueTaskMessage(g,{type:"request",message:p,timestamp:Date.now()}).catch((v)=>{this._cleanupTimeout(d),l(v)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch((w)=>{this._cleanupTimeout(d),l(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},mp,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},yp,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},GI,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[qs]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[qs]:t.relatedTask}}};this._transport?.send(i,t).catch((a)=>this._onerror(a))});return}let o={...e,jsonrpc:"2.0"};if(t?.relatedTask)o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[qs]:t.relatedTask}}};await this._transport.send(o,t)}setRequestHandler(e,t){let r=y_(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,s)=>{let o=w_(e,n);return Promise.resolve(t(o,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=y_(e);this._notificationHandlers.set(r,(n)=>{let s=w_(e,n);return Promise.resolve(t(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&os(n.message)){let s=n.message.id,o=this._requestResolvers.get(s);if(o)o(new te(ne.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s);else this._onerror(Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1000;try{let s=await this._taskStore?.getTask(e,r);if(s?.pollInterval)n=s.pollInterval}catch{}return new Promise((s,o)=>{if(t.aborted){o(new te(ne.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);t.addEventListener("abort",()=>{clearTimeout(i),o(new te(ne.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let s=await r.getTask(n,t);if(!s)throw new te(ne.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(n,s,o)=>{await r.storeTaskResult(n,s,o,t);let i=await r.getTask(n,t);if(i){let a=cl.parse({method:"notifications/tasks/status",params:i});if(await this.notification(a),Ks(i.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,s,o)=>{let i=await r.getTask(n,t);if(!i)throw new te(ne.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Ks(i.status))throw new te(ne.InvalidParams,`Cannot update task "${n}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,s,o,t);let a=await r.getTask(n,t);if(a){let c=cl.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Ks(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function uR(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function dR(e,t){let r={...e};for(let n in t){let s=n,o=t[s];if(o===void 0)continue;let i=r[s];if(uR(i)&&uR(o))r[s]={...i,...o};else r[s]=o}return r}var lF=60000;var pR=b(()=>{Cl();Bo();b_()});var Ml=H(function(hR){Object.defineProperty(hR,"__esModule",{value:!0});hR.regexpCode=hR.getEsmExportName=hR.getProperty=hR.safeStringify=hR.stringify=hR.strConcat=hR.addCodeArg=hR.str=hR._=hR.nil=hR._Code=hR.Name=hR.IDENTIFIER=hR._CodeOrName=void 0;class nf{}hR._CodeOrName=nf;hR.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class ia extends nf{constructor(e){super();if(!hR.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}hR.Name=ia;class hn extends nf{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,r)=>`${t}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,r)=>{if(r instanceof ia)t[r.str]=(t[r.str]||0)+1;return t},{})}}hR._Code=hn;hR.nil=new hn("");function fR(e,...t){let r=[e[0]],n=0;while(n<t.length)x_(r,t[n]),r.push(e[++n]);return new hn(r)}hR._=fR;var __=new hn("+");function mR(e,...t){let r=[zl(e[0])],n=0;while(n<t.length)r.push(__),x_(r,t[n]),r.push(__,zl(e[++n]));return uF(r),new hn(r)}hR.str=mR;function x_(e,t){if(t instanceof hn)e.push(...t._items);else if(t instanceof ia)e.push(t);else e.push(fF(t))}hR.addCodeArg=x_;function uF(e){let t=1;while(t<e.length-1){if(e[t]===__){let r=dF(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function dF(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof ia||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof ia))return`"${e}${t.slice(1)}`;return}function pF(e,t){return t.emptyStr()?e:e.emptyStr()?t:mR`${e}${t}`}hR.strConcat=pF;function fF(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:zl(Array.isArray(e)?e.join(","):e)}function mF(e){return new hn(zl(e))}hR.stringify=mF;function zl(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}hR.safeStringify=zl;function hF(e){return typeof e=="string"&&hR.IDENTIFIER.test(e)?new hn(`.${e}`):fR`[${e}]`}hR.getProperty=hF;function gF(e){if(typeof e=="string"&&hR.IDENTIFIER.test(e))return new hn(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}hR.getEsmExportName=gF;function yF(e){return new hn(e.toString())}hR.regexpCode=yF});var T_=H(function(bR){Object.defineProperty(bR,"__esModule",{value:!0});bR.ValueScope=bR.ValueScopeName=bR.Scope=bR.varKinds=bR.UsedValueState=void 0;var Ve=Ml();class yR extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var of;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(of||(bR.UsedValueState=of={}));bR.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};class $_{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof Ve.Name?e:this.name(e)}name(e){return new Ve.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,r;if(((r=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||r===void 0?void 0:r.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}bR.Scope=$_;class k_ extends Ve.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:r}){this.value=e,this.scopePath=Ve._`.${new Ve.Name(t)}[${r}]`}}bR.ValueScopeName=k_;var AF=Ve._`\n`;class wR extends $_{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?AF:Ve.nil}}get(){return this._scope}name(e){return new k_(e,this._newName(e))}value(e,t){var r;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let n=this.toName(e),{prefix:s}=n,o=(r=t.key)!==null&&r!==void 0?r:t.ref,i=this._values[s];if(i){let l=i.get(o);if(l)return l}else i=this._values[s]=new Map;i.set(o,n);let a=this._scope[s]||(this._scope[s]=[]),c=a.length;return a[c]=t.ref,n.setValue(t,{property:s,itemIndex:c}),n}getValue(e,t){let r=this._values[e];if(!r)return;return r.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(r)=>{if(r.scopePath===void 0)throw Error(`CodeGen: name "${r}" has no value`);return Ve._`${e}${r.scopePath}`})}scopeCode(e=this._values,t,r){return this._reduceValues(e,(n)=>{if(n.value===void 0)throw Error(`CodeGen: name "${n}" has no value`);return n.value.code},t,r)}_reduceValues(e,t,r={},n){let s=Ve.nil;for(let o in e){let i=e[o];if(!i)continue;let a=r[o]=r[o]||new Map;i.forEach((c)=>{if(a.has(c))return;a.set(c,of.Started);let l=t(c);if(l){let u=this.opts.es5?bR.varKinds.var:bR.varKinds.const;s=Ve._`${s}${u} ${c} = ${l};${this.opts._n}`}else if(l=n===null||n===void 0?void 0:n(c))s=Ve._`${s}${l}${this.opts._n}`;else throw new yR(c);a.set(c,of.Completed)})}return s}}bR.ValueScope=wR});var Se=H(function($r){Object.defineProperty($r,"__esModule",{value:!0});$r.or=$r.and=$r.not=$r.CodeGen=$r.operators=$r.varKinds=$r.ValueScopeName=$r.ValueScope=$r.Scope=$r.Name=$r.regexpCode=$r.stringify=$r.getProperty=$r.nil=$r.strConcat=$r.str=$r._=void 0;var W=Ml(),mt=T_(),Ws=Ml();Object.defineProperty($r,"_",{enumerable:!0,get:function(){return Ws._}});Object.defineProperty($r,"str",{enumerable:!0,get:function(){return Ws.str}});Object.defineProperty($r,"strConcat",{enumerable:!0,get:function(){return Ws.strConcat}});Object.defineProperty($r,"nil",{enumerable:!0,get:function(){return Ws.nil}});Object.defineProperty($r,"getProperty",{enumerable:!0,get:function(){return Ws.getProperty}});Object.defineProperty($r,"stringify",{enumerable:!0,get:function(){return Ws.stringify}});Object.defineProperty($r,"regexpCode",{enumerable:!0,get:function(){return Ws.regexpCode}});Object.defineProperty($r,"Name",{enumerable:!0,get:function(){return Ws.Name}});var pf=T_();Object.defineProperty($r,"Scope",{enumerable:!0,get:function(){return pf.Scope}});Object.defineProperty($r,"ValueScope",{enumerable:!0,get:function(){return pf.ValueScope}});Object.defineProperty($r,"ValueScopeName",{enumerable:!0,get:function(){return pf.ValueScopeName}});Object.defineProperty($r,"varKinds",{enumerable:!0,get:function(){return pf.varKinds}});$r.operators={GT:new W._Code(">"),GTE:new W._Code(">="),LT:new W._Code("<"),LTE:new W._Code("<="),EQ:new W._Code("==="),NEQ:new W._Code("!=="),NOT:new W._Code("!"),OR:new W._Code("||"),AND:new W._Code("&&"),ADD:new W._Code("+")};class Js{optimizeNodes(){return this}optimizeNames(e,t){return this}}class _R extends Js{constructor(e,t,r){super();this.varKind=e,this.name=t,this.rhs=r}render({es5:e,_n:t}){let r=e?mt.varKinds.var:this.varKind,n=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${n};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ca(this.rhs,e,t);return this}get names(){return this.rhs instanceof W._CodeOrName?this.rhs.names:{}}}class I_ extends Js{constructor(e,t,r){super();this.lhs=e,this.rhs=t,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof W.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ca(this.rhs,e,t),this}get names(){let e=this.lhs instanceof W.Name?{}:{...this.lhs.names};return df(e,this.rhs)}}class xR extends I_{constructor(e,t,r,n){super(e,r,n);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class SR extends Js{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class $R extends Js{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class kR extends Js{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class TR extends Js{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ca(this.code,e,t),this}get names(){return this.code instanceof W._CodeOrName?this.code.names:{}}}class ff extends Js{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,r)=>t+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let r=e[t].optimizeNodes();if(Array.isArray(r))e.splice(t,1,...r);else if(r)e[t]=r;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:r}=this,n=r.length;while(n--){let s=r[n];if(s.optimizeNames(e,t))continue;zF(e,s.names),r.splice(n,1)}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Ko(e,t.names),{})}}class Qs extends ff{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class PR extends ff{}class Nl extends Qs{}Nl.kind="else";class hs extends Qs{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let r=t.optimizeNodes();t=this.else=Array.isArray(r)?new Nl(r):r}if(t){if(e===!1)return t instanceof hs?t:t.nodes;if(this.nodes.length)return this;return new hs(CR(e),t instanceof hs?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ca(this.condition,e,t),this}get names(){let e=super.names;if(df(e,this.condition),this.else)Ko(e,this.else.names);return e}}hs.kind="if";class aa extends Qs{}aa.kind="for";class ER extends aa{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ca(this.iteration,e,t),this}get names(){return Ko(super.names,this.iteration.names)}}class IR extends aa{constructor(e,t,r,n){super();this.varKind=e,this.name=t,this.from=r,this.to=n}render(e){let t=e.es5?mt.varKinds.var:this.varKind,{name:r,from:n,to:s}=this;return`for(${t} ${r}=${n}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=df(super.names,this.from);return df(e,this.to)}}class P_ extends aa{constructor(e,t,r,n){super();this.loop=e,this.varKind=t,this.name=r,this.iterable=n}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ca(this.iterable,e,t),this}get names(){return Ko(super.names,this.iterable.names)}}class af extends Qs{constructor(e,t,r){super();this.name=e,this.args=t,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}af.kind="func";class cf extends ff{render(e){return"return "+super.render(e)}}cf.kind="return";class AR extends Qs{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var r,n;return super.optimizeNames(e,t),(r=this.catch)===null||r===void 0||r.optimizeNames(e,t),(n=this.finally)===null||n===void 0||n.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)Ko(e,this.catch.names);if(this.finally)Ko(e,this.finally.names);return e}}class lf extends Qs{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}lf.kind="catch";class uf extends Qs{render(e){return"finally"+super.render(e)}}uf.kind="finally";class RR{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
107
|
+
`:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new PR]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let r=this._extScope.value(e,t);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,r,n){let s=this._scope.toName(t);if(r!==void 0&&n)this._constants[s.str]=r;return this._leafNode(new _R(e,s,r)),s}const(e,t,r){return this._def(mt.varKinds.const,e,t,r)}let(e,t,r){return this._def(mt.varKinds.let,e,t,r)}var(e,t,r){return this._def(mt.varKinds.var,e,t,r)}assign(e,t,r){return this._leafNode(new I_(e,t,r))}add(e,t){return this._leafNode(new xR(e,$r.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==W.nil)this._leafNode(new TR(e));return this}object(...e){let t=["{"];for(let[r,n]of e){if(t.length>1)t.push(",");if(t.push(r),r!==n||this.opts.es5)t.push(":"),W.addCodeArg(t,n)}return t.push("}"),new W._Code(t)}if(e,t,r){if(this._blockNode(new hs(e)),t&&r)this.code(t).else().code(r).endIf();else if(t)this.code(t).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new hs(e))}else(){return this._elseNode(new Nl)}endIf(){return this._endBlockNode(hs,Nl)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new ER(e),t)}forRange(e,t,r,n,s=this.opts.es5?mt.varKinds.var:mt.varKinds.let){let o=this._scope.toName(e);return this._for(new IR(s,o,t,r),()=>n(o))}forOf(e,t,r,n=mt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof W.Name?t:this.var("_arr",t);return this.forRange("_i",0,W._`${o}.length`,(i)=>{this.var(s,W._`${o}[${i}]`),r(s)})}return this._for(new P_("of",n,s,t),()=>r(s))}forIn(e,t,r,n=this.opts.es5?mt.varKinds.var:mt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,W._`Object.keys(${t})`,r);let s=this._scope.toName(e);return this._for(new P_("in",n,s,t),()=>r(s))}endFor(){return this._endBlockNode(aa)}label(e){return this._leafNode(new SR(e))}break(e){return this._leafNode(new $R(e))}return(e){let t=new cf;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(cf)}try(e,t,r){if(!t&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let n=new AR;if(this._blockNode(n),this.code(e),t){let s=this.name("e");this._currNode=n.catch=new lf(s),t(s)}if(r)this._currNode=n.finally=new uf,this.code(r);return this._endBlockNode(lf,uf)}throw(e){return this._leafNode(new kR(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-t;if(r<0||e!==void 0&&r!==e)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=W.nil,r,n){if(this._blockNode(new af(e,t,r)),n)this.code(n).endFunc();return this}endFunc(){return this._endBlockNode(af)}optimize(e=1){while(e-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let r=this._currNode;if(r instanceof e||t&&r instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof hs))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}$r.CodeGen=RR;function Ko(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function df(e,t){return t instanceof W._CodeOrName?Ko(e,t.names):e}function ca(e,t,r){if(e instanceof W.Name)return n(e);if(!s(e))return e;return new W._Code(e._items.reduce((o,i)=>{if(i instanceof W.Name)i=n(i);if(i instanceof W._Code)o.push(...i._items);else o.push(i);return o},[]));function n(o){let i=r[o.str];if(i===void 0||t[o.str]!==1)return o;return delete t[o.str],i}function s(o){return o instanceof W._Code&&o._items.some((i)=>i instanceof W.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function zF(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function CR(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:W._`!${E_(e)}`}$r.not=CR;var MF=OR($r.operators.AND);function NF(...e){return e.reduce(MF)}$r.and=NF;var LF=OR($r.operators.OR);function DF(...e){return e.reduce(LF)}$r.or=DF;function OR(e){return(t,r)=>t===W.nil?r:r===W.nil?t:W._`${E_(t)} ${e} ${E_(r)}`}function E_(e){return e instanceof W.Name?e:W._`(${e})`}});var ze=H(function(FR){Object.defineProperty(FR,"__esModule",{value:!0});FR.checkStrictMode=FR.getErrorPath=FR.Type=FR.useFunc=FR.setEvaluated=FR.evaluatedPropsToName=FR.mergeEvaluated=FR.eachItem=FR.unescapeJsonPointer=FR.escapeJsonPointer=FR.escapeFragment=FR.unescapeFragment=FR.schemaRefOrVal=FR.schemaHasRulesButRef=FR.schemaHasRules=FR.checkUnknownRules=FR.alwaysValidSchema=FR.toHash=void 0;var ue=Se(),LR=Ml();function qF(e){let t={};for(let r of e)t[r]=!0;return t}FR.toHash=qF;function FF(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return DR(e,t),!jR(t,e.self.RULES.all)}FR.alwaysValidSchema=FF;function DR(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema)return;if(typeof t==="boolean")return;let s=n.RULES.keywords;for(let o in t)if(!s[o])qR(e,`unknown keyword: "${o}"`)}FR.checkUnknownRules=DR;function jR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}FR.schemaHasRules=jR;function VF(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}FR.schemaHasRulesButRef=VF;function ZF({topSchemaRef:e,schemaPath:t},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return ue._`${r}`}return ue._`${e}${t}${ue.getProperty(n)}`}FR.schemaRefOrVal=ZF;function HF(e){return UR(decodeURIComponent(e))}FR.unescapeFragment=HF;function GF(e){return encodeURIComponent(R_(e))}FR.escapeFragment=GF;function R_(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}FR.escapeJsonPointer=R_;function UR(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}FR.unescapeJsonPointer=UR;function KF(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}FR.eachItem=KF;function MR({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof ue.Name?(o instanceof ue.Name?e(s,o,i):t(s,o,i),i):o instanceof ue.Name?(t(s,i,o),o):r(o,i);return a===ue.Name&&!(c instanceof ue.Name)?n(s,c):c}}FR.mergeEvaluated={props:MR({mergeNames:(e,t,r)=>e.if(ue._`${r} !== true && ${t} !== undefined`,()=>{e.if(ue._`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,ue._`${r} || {}`).code(ue._`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if(ue._`${r} !== true`,()=>{if(t===!0)e.assign(r,!0);else e.assign(r,ue._`${r} || {}`),C_(e,r,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:BR}),items:MR({mergeNames:(e,t,r)=>e.if(ue._`${r} !== true && ${t} !== undefined`,()=>e.assign(r,ue._`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if(ue._`${r} !== true`,()=>e.assign(r,t===!0?!0:ue._`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function BR(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",ue._`{}`);if(t!==void 0)C_(e,r,t);return r}FR.evaluatedPropsToName=BR;function C_(e,t,r){Object.keys(r).forEach((n)=>e.assign(ue._`${t}${ue.getProperty(n)}`,!0))}FR.setEvaluated=C_;var NR={};function WF(e,t){return e.scopeValue("func",{ref:t,code:NR[t.code]||(NR[t.code]=new LR._Code(t.code))})}FR.useFunc=WF;var A_;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(A_||(FR.Type=A_={}));function JF(e,t,r){if(e instanceof ue.Name){let n=t===A_.Num;return r?n?ue._`"[" + ${e} + "]"`:ue._`"['" + ${e} + "']"`:n?ue._`"/" + ${e}`:ue._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?ue.getProperty(e).toString():"/"+R_(e)}FR.getErrorPath=JF;function qR(e,t,r=e.opts.strictSchema){if(!r)return;if(t=`strict mode: ${t}`,r===!0)throw Error(t);e.self.logger.warn(t)}FR.checkStrictMode=qR});var gs=H(function(ZR){Object.defineProperty(ZR,"__esModule",{value:!0});var De=Se(),mV={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};ZR.default=mV});var Ll=H(function(WR){Object.defineProperty(WR,"__esModule",{value:!0});WR.extendErrors=WR.resetErrorsCount=WR.reportExtraError=WR.reportError=WR.keyword$DataError=WR.keywordError=void 0;var J=Se(),Xs=ze(),lr=gs();WR.keywordError={message:({keyword:e})=>J.str`must pass "${e}" keyword validation`};WR.keyword$DataError={message:({keyword:e,schemaType:t})=>t?J.str`"${e}" keyword must be ${t} ($data)`:J.str`"${e}" keyword is invalid ($data)`};function gV(e,t=WR.keywordError,r,n){let{it:s}=e,{gen:o,compositeRule:i,allErrors:a}=s,c=KR(e,t,r);if(n!==null&&n!==void 0?n:i||a)HR(o,c);else GR(s,J._`[${c}]`)}WR.reportError=gV;function yV(e,t=WR.keywordError,r){let{it:n}=e,{gen:s,compositeRule:o,allErrors:i}=n,a=KR(e,t,r);if(HR(s,a),!(o||i))GR(n,lr.default.vErrors)}WR.reportExtraError=yV;function wV(e,t){e.assign(lr.default.errors,t),e.if(J._`${lr.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(J._`${lr.default.vErrors}.length`,t),()=>e.assign(lr.default.vErrors,null)))}WR.resetErrorsCount=wV;function bV({gen:e,keyword:t,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw Error("ajv implementation error");let i=e.name("err");e.forRange("i",s,lr.default.errors,(a)=>{if(e.const(i,J._`${lr.default.vErrors}[${a}]`),e.if(J._`${i}.instancePath === undefined`,()=>e.assign(J._`${i}.instancePath`,J.strConcat(lr.default.instancePath,o.errorPath))),e.assign(J._`${i}.schemaPath`,J.str`${o.errSchemaPath}/${t}`),o.opts.verbose)e.assign(J._`${i}.schema`,r),e.assign(J._`${i}.data`,n)})}WR.extendErrors=bV;function HR(e,t){let r=e.const("err",t);e.if(J._`${lr.default.vErrors} === null`,()=>e.assign(lr.default.vErrors,J._`[${r}]`),J._`${lr.default.vErrors}.push(${r})`),e.code(J._`${lr.default.errors}++`)}function GR(e,t){let{gen:r,validateName:n,schemaEnv:s}=e;if(s.$async)r.throw(J._`new ${e.ValidationError}(${t})`);else r.assign(J._`${n}.errors`,t),r.return(!1)}var Wo={keyword:new J.Name("keyword"),schemaPath:new J.Name("schemaPath"),params:new J.Name("params"),propertyName:new J.Name("propertyName"),message:new J.Name("message"),schema:new J.Name("schema"),parentSchema:new J.Name("parentSchema")};function KR(e,t,r){let{createErrors:n}=e.it;if(n===!1)return J._`{}`;return vV(e,t,r)}function vV(e,t,r={}){let{gen:n,it:s}=e,o=[_V(s,r),xV(e,r)];return SV(e,t,o),n.object(...o)}function _V({errorPath:e},{instancePath:t}){let r=t?J.str`${e}${Xs.getErrorPath(t,Xs.Type.Str)}`:e;return[lr.default.instancePath,J.strConcat(lr.default.instancePath,r)]}function xV({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let s=n?t:J.str`${t}/${e}`;if(r)s=J.str`${s}${Xs.getErrorPath(r,Xs.Type.Str)}`;return[Wo.schemaPath,s]}function SV(e,{params:t,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;if(n.push([Wo.keyword,s],[Wo.params,typeof t=="function"?t(e):t||J._`{}`]),c.messages)n.push([Wo.message,typeof r=="function"?r(e):r]);if(c.verbose)n.push([Wo.schema,i],[Wo.parentSchema,J._`${u}${d}`],[lr.default.data,o]);if(l)n.push([Wo.propertyName,l])}});var rC=H(function(eC){Object.defineProperty(eC,"__esModule",{value:!0});eC.boolOrEmptySchema=eC.topBoolOrEmptySchema=void 0;var QR=Ll(),XR=Se(),EV=gs(),IV={message:"boolean schema is false"};function AV(e){let{gen:t,schema:r,validateName:n}=e;if(r===!1)YR(e,!1);else if(typeof r=="object"&&r.$async===!0)t.return(EV.default.data);else t.assign(XR._`${n}.errors`,null),t.return(!0)}eC.topBoolOrEmptySchema=AV;function RV(e,t){let{gen:r,schema:n}=e;if(n===!1)r.var(t,!1),YR(e);else r.var(t,!0)}eC.boolOrEmptySchema=RV;function YR(e,t){let{gen:r,data:n}=e;QR.reportError({gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e},IV,void 0,t)}});var z_=H(function(nC){Object.defineProperty(nC,"__esModule",{value:!0});nC.getRules=nC.isJSONType=void 0;var OV=["string","number","integer","boolean","null","object","array"],zV=new Set(OV);function MV(e){return typeof e=="string"&&zV.has(e)}nC.isJSONType=MV;function NV(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}nC.getRules=NV});var M_=H(function(aC){Object.defineProperty(aC,"__esModule",{value:!0});aC.shouldUseRule=aC.shouldUseGroup=aC.schemaHasRulesForType=void 0;function DV({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&oC(e,n)}aC.schemaHasRulesForType=DV;function oC(e,t){return t.rules.some((r)=>iC(e,r))}aC.shouldUseGroup=oC;function iC(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some((n)=>e[n]!==void 0))}aC.shouldUseRule=iC});var Dl=H(function(mC){Object.defineProperty(mC,"__esModule",{value:!0});mC.reportTypeError=mC.checkDataTypes=mC.checkDataType=mC.coerceAndCheckDataType=mC.getJSONTypes=mC.getSchemaTypes=mC.DataType=void 0;var lC=z_(),uC=M_(),dC=Ll(),q=Se(),hf=ze(),la;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(la||(mC.DataType=la={}));function BV(e){let t=pC(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}mC.getSchemaTypes=BV;function pC(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(lC.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}mC.getJSONTypes=pC;function qV(e,t){let{gen:r,data:n,opts:s}=e,o=FV(t,s.coerceTypes),i=t.length>0&&!(o.length===0&&t.length===1&&uC.schemaHasRulesForType(e,t[0]));if(i){let a=L_(t,n,s.strictNumbers,la.Wrong);r.if(a,()=>{if(o.length)VV(e,t,o);else D_(e)})}return i}mC.coerceAndCheckDataType=qV;var fC=new Set(["string","number","integer","boolean","null"]);function FV(e,t){return t?e.filter((r)=>fC.has(r)||t==="array"&&r==="array"):[]}function VV(e,t,r){let{gen:n,data:s,opts:o}=e,i=n.let("dataType",q._`typeof ${s}`),a=n.let("coerced",q._`undefined`);if(o.coerceTypes==="array")n.if(q._`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,q._`${s}[0]`).assign(i,q._`typeof ${s}`).if(L_(t,s,o.strictNumbers),()=>n.assign(a,s)));n.if(q._`${a} !== undefined`);for(let l of r)if(fC.has(l)||l==="array"&&o.coerceTypes==="array")c(l);n.else(),D_(e),n.endIf(),n.if(q._`${a} !== undefined`,()=>{n.assign(s,a),ZV(e,a)});function c(l){switch(l){case"string":n.elseIf(q._`${i} == "number" || ${i} == "boolean"`).assign(a,q._`"" + ${s}`).elseIf(q._`${s} === null`).assign(a,q._`""`);return;case"number":n.elseIf(q._`${i} == "boolean" || ${s} === null
|
|
108
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,q._`+${s}`);return;case"integer":n.elseIf(q._`${i} === "boolean" || ${s} === null
|
|
109
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,q._`+${s}`);return;case"boolean":n.elseIf(q._`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf(q._`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf(q._`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf(q._`${i} === "string" || ${i} === "number"
|
|
110
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,q._`[${s}]`)}}}function ZV({gen:e,parentData:t,parentDataProperty:r},n){e.if(q._`${t} !== undefined`,()=>e.assign(q._`${t}[${r}]`,n))}function N_(e,t,r,n=la.Correct){let s=n===la.Correct?q.operators.EQ:q.operators.NEQ,o;switch(e){case"null":return q._`${t} ${s} null`;case"array":o=q._`Array.isArray(${t})`;break;case"object":o=q._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":o=i(q._`!(${t} % 1) && !isNaN(${t})`);break;case"number":o=i();break;default:return q._`typeof ${t} ${s} ${e}`}return n===la.Correct?o:q.not(o);function i(a=q.nil){return q.and(q._`typeof ${t} == "number"`,a,r?q._`isFinite(${t})`:q.nil)}}mC.checkDataType=N_;function L_(e,t,r,n){if(e.length===1)return N_(e[0],t,r,n);let s,o=hf.toHash(e);if(o.array&&o.object){let i=q._`typeof ${t} != "object"`;s=o.null?i:q._`!${t} || ${i}`,delete o.null,delete o.array,delete o.object}else s=q.nil;if(o.number)delete o.integer;for(let i in o)s=q.and(s,N_(i,t,r,n));return s}mC.checkDataTypes=L_;var HV={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?q._`{type: ${e}}`:q._`{type: ${t}}`};function D_(e){let t=GV(e);dC.reportError(t,HV)}mC.reportTypeError=D_;function GV(e){let{gen:t,data:r,schema:n}=e,s=hf.schemaRefOrVal(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:e}}});var vC=H(function(wC){Object.defineProperty(wC,"__esModule",{value:!0});wC.assignDefaults=void 0;var Jr=Se(),yC=ze();function e7(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let s in r)gC(e,s,r[s].default);else if(t==="array"&&Array.isArray(n))n.forEach((s,o)=>gC(e,o,s.default))}wC.assignDefaults=e7;function gC(e,t,r){let{gen:n,compositeRule:s,data:o,opts:i}=e;if(r===void 0)return;let a=Jr._`${o}${Jr.getProperty(t)}`;if(s){yC.checkStrictMode(e,`default is ignored for: ${a}`);return}let c=Jr._`${a} === undefined`;if(i.useDefaults==="empty")c=Jr._`${c} || ${a} === null || ${a} === ""`;n.if(c,Jr._`${a} = ${Jr.stringify(r)}`)}});var Qr=H(function($C){Object.defineProperty($C,"__esModule",{value:!0});$C.validateUnion=$C.validateArray=$C.usePattern=$C.callValidateCode=$C.schemaProperties=$C.allSchemaProperties=$C.noPropertyInData=$C.propertyInData=$C.isOwnProperty=$C.hasPropFunc=$C.reportMissingProp=$C.checkMissingProp=$C.checkReportMissingProp=void 0;var pe=Se(),ua=ze(),Ys=gs(),_C=ze();function t7(e,t){let{gen:r,data:n,it:s}=e;r.if(U_(r,n,t,s.opts.ownProperties),()=>{e.setParams({missingProperty:pe._`${t}`},!0),e.error()})}$C.checkReportMissingProp=t7;function r7({gen:e,data:t,it:{opts:r}},n,s){return pe.or(...n.map((o)=>pe.and(U_(e,t,o,r.ownProperties),pe._`${s} = ${o}`)))}$C.checkMissingProp=r7;function n7(e,t){e.setParams({missingProperty:t},!0),e.error()}$C.reportMissingProp=n7;function xC(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:pe._`Object.prototype.hasOwnProperty`})}$C.hasPropFunc=xC;function j_(e,t,r){return pe._`${xC(e)}.call(${t}, ${r})`}$C.isOwnProperty=j_;function s7(e,t,r,n){let s=pe._`${t}${pe.getProperty(r)} !== undefined`;return n?pe._`${s} && ${j_(e,t,r)}`:s}$C.propertyInData=s7;function U_(e,t,r,n){let s=pe._`${t}${pe.getProperty(r)} === undefined`;return n?pe.or(s,pe.not(j_(e,t,r))):s}$C.noPropertyInData=U_;function SC(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}$C.allSchemaProperties=SC;function o7(e,t){return SC(t).filter((r)=>!ua.alwaysValidSchema(e,t[r]))}$C.schemaProperties=o7;function i7({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,l){let u=l?pe._`${e}, ${t}, ${n}${s}`:t,d=[[Ys.default.instancePath,pe.strConcat(Ys.default.instancePath,o)],[Ys.default.parentData,i.parentData],[Ys.default.parentDataProperty,i.parentDataProperty],[Ys.default.rootData,Ys.default.rootData]];if(i.opts.dynamicRef)d.push([Ys.default.dynamicAnchors,Ys.default.dynamicAnchors]);let p=pe._`${u}, ${r.object(...d)}`;return c!==pe.nil?pe._`${a}.call(${c}, ${p})`:pe._`${a}(${p})`}$C.callValidateCode=i7;var a7=pe._`new RegExp`;function c7({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:s}=t.code,o=s(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:pe._`${s.code==="new RegExp"?a7:_C.useFunc(e,s)}(${r}, ${n})`})}$C.usePattern=c7;function l7(e){let{gen:t,data:r,keyword:n,it:s}=e,o=t.name("valid");if(s.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(o,!0),i(()=>t.break()),o;function i(a){let c=t.const("len",pe._`${r}.length`);t.forRange("i",0,c,(l)=>{e.subschema({keyword:n,dataProp:l,dataPropType:ua.Type.Num},o),t.if(pe.not(o),a)})}}$C.validateArray=l7;function u7(e){let{gen:t,schema:r,keyword:n,it:s}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>ua.alwaysValidSchema(s,c))&&!s.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let u=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);if(t.assign(i,pe._`${i} || ${a}`),!e.mergeValidEvaluated(u,a))t.if(pe.not(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}$C.validateUnion=u7});var CC=H(function(AC){Object.defineProperty(AC,"__esModule",{value:!0});AC.validateKeywordUsage=AC.validSchemaType=AC.funcKeywordCode=AC.macroKeywordCode=void 0;var Ue=Se(),Jo=gs(),PC=Qr(),EC=Ll();function S7(e,t){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=e,a=t.macro.call(i.self,s,o,i),c=IC(r,n,a);if(i.opts.validateSchema!==!1)i.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Ue.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}AC.macroKeywordCode=S7;function $7(e,t){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=e;T7(c,t);let l=!a&&t.compile?t.compile.call(c.self,o,i,c):t.validate,u=IC(n,s,l),d=n.let("valid");e.block$data(d,p),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function p(){if(t.errors===!1){if(h(),t.modifying)TC(e);g(()=>e.error())}else{let w=t.async?f():m();if(t.modifying)TC(e);g(()=>k7(e,w))}}function f(){let w=n.let("ruleErrs",null);return n.try(()=>h(Ue._`await `),(v)=>n.assign(d,!1).if(Ue._`${v} instanceof ${c.ValidationError}`,()=>n.assign(w,Ue._`${v}.errors`),()=>n.throw(v))),w}function m(){let w=Ue._`${u}.errors`;return n.assign(w,null),h(Ue.nil),w}function h(w=t.async?Ue._`await `:Ue.nil){let v=c.opts.passContext?Jo.default.this:Jo.default.self,_=!(("compile"in t)&&!a||t.schema===!1);n.assign(d,Ue._`${w}${PC.callValidateCode(e,u,v,_)}`,t.modifying)}function g(w){var v;n.if(Ue.not((v=t.valid)!==null&&v!==void 0?v:d),w)}}AC.funcKeywordCode=$7;function TC(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,Ue._`${n.parentData}[${n.parentDataProperty}]`))}function k7(e,t){let{gen:r}=e;r.if(Ue._`Array.isArray(${t})`,()=>{r.assign(Jo.default.vErrors,Ue._`${Jo.default.vErrors} === null ? ${t} : ${Jo.default.vErrors}.concat(${t})`).assign(Jo.default.errors,Ue._`${Jo.default.vErrors}.length`),EC.extendErrors(e)},()=>e.error())}function T7({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function IC(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:Ue.stringify(r)})}function P7(e,t,r=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}AC.validSchemaType=P7;function E7({schema:e,opts:t,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw Error("ajv implementation error");let i=s.dependencies;if(i===null||i===void 0?void 0:i.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema){if(!s.validateSchema(e[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}AC.validateKeywordUsage=E7});var MC=H(function(OC){Object.defineProperty(OC,"__esModule",{value:!0});OC.extendSubschemaMode=OC.extendSubschemaData=OC.getSubschema=void 0;var It=Se(),gf=ze();function C7(e,{keyword:t,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:It._`${e.schemaPath}${It.getProperty(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:It._`${e.schemaPath}${It.getProperty(t)}${It.getProperty(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${gf.escapeFragment(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw Error('either "keyword" or "schema" must be passed')}OC.getSubschema=C7;function O7(e,t,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=t,p=a.let("data",It._`${t.data}${It.getProperty(r)}`,!0);c(p),e.errorPath=It.str`${l}${gf.getErrorPath(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=It._`${r}`,e.dataPathArr=[...u,e.parentDataProperty]}if(s!==void 0){let l=s instanceof It.Name?s:a.let("data",s,!0);if(c(l),i!==void 0)e.propertyName=i}if(o)e.dataTypes=o;function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}OC.extendSubschemaData=O7;function z7(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){if(n!==void 0)e.compositeRule=n;if(s!==void 0)e.createErrors=s;if(o!==void 0)e.allErrors=o;e.jtdDiscriminator=t,e.jtdMetadata=r}OC.extendSubschemaMode=z7});var B_=H(function(hge,NC){NC.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var DC=H(function(gge,LC){var eo=LC.exports=function(e,t,r){if(typeof t=="function")r=t,t={};r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};yf(t,n,s,e,"",e)};eo.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};eo.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};eo.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};eo.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function yf(e,t,r,n,s,o,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,s,o,i,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in eo.arrayKeywords)for(var p=0;p<d.length;p++)yf(e,t,r,d[p],s+"/"+u+"/"+p,o,s,u,n,p)}else if(u in eo.propsKeywords){if(d&&typeof d=="object")for(var f in d)yf(e,t,r,d[f],s+"/"+u+"/"+L7(f),o,s,u,n,f)}else if(u in eo.keywords||e.allKeys&&!(u in eo.skipKeywords))yf(e,t,r,d,s+"/"+u,o,s,u,n)}r(n,s,o,i,a,c,l)}}function L7(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var jl=H(function(FC){Object.defineProperty(FC,"__esModule",{value:!0});FC.getSchemaRefs=FC.resolveUrl=FC.normalizeId=FC._getFullPath=FC.getFullPath=FC.inlineRef=void 0;var jC=ze(),D7=B_(),j7=DC(),U7=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function B7(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!q_(e);if(!t)return!1;return UC(e)<=t}FC.inlineRef=B7;var q7=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function q_(e){for(let t in e){if(q7.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(q_))return!0;if(typeof r=="object"&&q_(r))return!0}return!1}function UC(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,U7.has(r))continue;if(typeof e[r]=="object")jC.eachItem(e[r],(n)=>t+=UC(n));if(t===1/0)return 1/0}return t}function BC(e,t="",r){if(r!==!1)t=da(t);let n=e.parse(t);return qC(e,n)}FC.getFullPath=BC;function qC(e,t){return e.serialize(t).split("#")[0]+"#"}FC._getFullPath=qC;var F7=/#\/?$/;function da(e){return e?e.replace(F7,""):""}FC.normalizeId=da;function V7(e,t,r){return r=da(r),e.resolve(t,r)}FC.resolveUrl=V7;var Z7=/^[a-z_][-a-z0-9._]*$/i;function H7(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=da(e[r]||t),o={"":s},i=BC(n,s,!1),a={},c=new Set;return j7(e,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,g=o[m];if(typeof d[r]=="string")g=w.call(this,d[r]);v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),o[p]=g;function w(_){let C=this.opts.uriResolver.resolve;if(_=da(g?C(g,_):_),c.has(_))throw u(_);c.add(_);let k=this.refs[_];if(typeof k=="string")k=this.refs[k];if(typeof k=="object")l(d,k.schema,_);else if(_!==da(h))if(_[0]==="#")l(d,a[_],_),a[_]=d;else this.refs[_]=h;return _}function v(_){if(typeof _=="string"){if(!Z7.test(_))throw Error(`invalid anchor "${_}"`);w.call(this,`#${_}`)}}}),a;function l(d,p,f){if(p!==void 0&&!D7(d,p))throw u(f)}function u(d){return Error(`reference "${d}" resolves to more than one schema`)}}FC.getSchemaRefs=H7});var Ul=H(function(oO){Object.defineProperty(oO,"__esModule",{value:!0});oO.getData=oO.KeywordCxt=oO.validateFunctionCode=void 0;var bf=rC(),wf=Dl(),fa=M_(),to=Dl(),KC=vC(),Mn=CC(),pa=MC(),M=Se(),ge=gs(),WC=jl(),Ut=ze(),zn=Ll();function X7(e){if(XC(e)){if(YC(e),QC(e)){tZ(e);return}}JC(e,()=>bf.topBoolOrEmptySchema(e))}oO.validateFunctionCode=X7;function JC({gen:e,validateName:t,schema:r,schemaEnv:n,opts:s},o){if(s.code.es5)e.func(t,M._`${ge.default.data}, ${ge.default.valCxt}`,n.$async,()=>{e.code(M._`"use strict"; ${ZC(r,s)}`),eZ(e,s),e.code(o)});else e.func(t,M._`${ge.default.data}, ${Y7(s)}`,n.$async,()=>e.code(ZC(r,s)).code(o))}function Y7(e){return M._`{${ge.default.instancePath}="", ${ge.default.parentData}, ${ge.default.parentDataProperty}, ${ge.default.rootData}=${ge.default.data}${e.dynamicRef?M._`, ${ge.default.dynamicAnchors}={}`:M.nil}}={}`}function eZ(e,t){e.if(ge.default.valCxt,()=>{if(e.var(ge.default.instancePath,M._`${ge.default.valCxt}.${ge.default.instancePath}`),e.var(ge.default.parentData,M._`${ge.default.valCxt}.${ge.default.parentData}`),e.var(ge.default.parentDataProperty,M._`${ge.default.valCxt}.${ge.default.parentDataProperty}`),e.var(ge.default.rootData,M._`${ge.default.valCxt}.${ge.default.rootData}`),t.dynamicRef)e.var(ge.default.dynamicAnchors,M._`${ge.default.valCxt}.${ge.default.dynamicAnchors}`)},()=>{if(e.var(ge.default.instancePath,M._`""`),e.var(ge.default.parentData,M._`undefined`),e.var(ge.default.parentDataProperty,M._`undefined`),e.var(ge.default.rootData,ge.default.data),t.dynamicRef)e.var(ge.default.dynamicAnchors,M._`{}`)})}function tZ(e){let{schema:t,opts:r,gen:n}=e;JC(e,()=>{if(r.$comment&&t.$comment)tO(e);if(iZ(e),n.let(ge.default.vErrors,null),n.let(ge.default.errors,0),r.unevaluated)rZ(e);eO(e),lZ(e)});return}function rZ(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",M._`${r}.evaluated`),t.if(M._`${e.evaluated}.dynamicProps`,()=>t.assign(M._`${e.evaluated}.props`,M._`undefined`)),t.if(M._`${e.evaluated}.dynamicItems`,()=>t.assign(M._`${e.evaluated}.items`,M._`undefined`))}function ZC(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?M._`/*# sourceURL=${r} */`:M.nil}function nZ(e,t){if(XC(e)){if(YC(e),QC(e)){sZ(e,t);return}}bf.boolOrEmptySchema(e,t)}function QC({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function XC(e){return typeof e.schema!="boolean"}function sZ(e,t){let{schema:r,gen:n,opts:s}=e;if(s.$comment&&r.$comment)tO(e);aZ(e),cZ(e);let o=n.const("_errs",ge.default.errors);eO(e,o),n.var(t,M._`${o} === ${ge.default.errors}`)}function YC(e){Ut.checkUnknownRules(e),oZ(e)}function eO(e,t){if(e.opts.jtd)return HC(e,[],!1,t);let r=wf.getSchemaTypes(e.schema),n=wf.coerceAndCheckDataType(e,r);HC(e,r,!n,t)}function oZ(e){let{schema:t,errSchemaPath:r,opts:n,self:s}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&Ut.schemaHasRulesButRef(t,s.RULES))s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function iZ(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)Ut.checkStrictMode(e,"default is ignored in the schema root")}function aZ(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=WC.resolveUrl(e.opts.uriResolver,e.baseId,t)}function cZ(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function tO({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)e.code(M._`${ge.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=M.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(M._`${ge.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function lZ(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=e;if(r.$async)t.if(M._`${ge.default.errors} === 0`,()=>t.return(ge.default.data),()=>t.throw(M._`new ${s}(${ge.default.vErrors})`));else{if(t.assign(M._`${n}.errors`,ge.default.vErrors),o.unevaluated)uZ(e);t.return(M._`${ge.default.errors} === 0`)}}function uZ({gen:e,evaluated:t,props:r,items:n}){if(r instanceof M.Name)e.assign(M._`${t}.props`,r);if(n instanceof M.Name)e.assign(M._`${t}.items`,n)}function HC(e,t,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:l}=e,{RULES:u}=l;if(o.$ref&&(c.ignoreKeywordsWithRef||!Ut.schemaHasRulesButRef(o,u))){s.block(()=>nO(e,"$ref",u.all.$ref.definition));return}if(!c.jtd)dZ(e,t);s.block(()=>{for(let p of u.rules)d(p);d(u.post)});function d(p){if(!fa.shouldUseGroup(o,p))return;if(p.type){if(s.if(to.checkDataType(p.type,i,c.strictNumbers)),GC(e,p),t.length===1&&t[0]===p.type&&r)s.else(),to.reportTypeError(e);s.endIf()}else GC(e,p);if(!a)s.if(M._`${ge.default.errors} === ${n||0}`)}}function GC(e,t){let{gen:r,schema:n,opts:{useDefaults:s}}=e;if(s)KC.assignDefaults(e,t.type);r.block(()=>{for(let o of t.rules)if(fa.shouldUseRule(n,o))nO(e,o.keyword,o.definition,t.type)})}function dZ(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(pZ(e,t),!e.opts.allowUnionTypes)fZ(e,t);mZ(e,e.dataTypes)}function pZ(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!rO(e.dataTypes,r))F_(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),gZ(e,t)}function fZ(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))F_(e,"use allowUnionTypes to allow union type keyword")}function mZ(e,t){let r=e.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&fa.shouldUseRule(e.schema,s)){let{type:o}=s.definition;if(o.length&&!o.some((i)=>hZ(t,i)))F_(e,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function hZ(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function rO(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function gZ(e,t){let r=[];for(let n of e.dataTypes)if(rO(t,n))r.push(n);else if(t.includes("integer")&&n==="number")r.push("integer");e.dataTypes=r}function F_(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,Ut.checkStrictMode(e,t,e.opts.strictTypes)}class V_{constructor(e,t,r){if(Mn.validateKeywordUsage(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=Ut.schemaRefOrVal(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",sO(this.$data,e));else if(this.schemaCode=this.schemaValue,!Mn.validSchemaType(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",ge.default.errors)}result(e,t,r){this.failResult(M.not(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult(M.not(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(M._`${t} !== undefined && (${M.or(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?zn.reportExtraError:zn.reportError)(this,this.def.error,t)}$dataError(){zn.reportError(this,this.def.$dataError||zn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');zn.resetErrorsCount(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=M.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=M.nil,t=M.nil){if(!this.$data)return;let{gen:r,schemaCode:n,schemaType:s,def:o}=this;if(r.if(M.or(M._`${n} === undefined`,t)),e!==M.nil)r.assign(e,!0);if(s.length||o.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==M.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:n,it:s}=this;return M.or(o(),i());function o(){if(r.length){if(!(t instanceof M.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return M._`${to.checkDataTypes(a,t,s.opts.strictNumbers,to.DataType.Wrong)}`}return M.nil}function i(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return M._`!${a}(${t})`}return M.nil}}subschema(e,t){let r=pa.getSubschema(this.it,e);pa.extendSubschemaData(r,this.it,e),pa.extendSubschemaMode(r,e);let n={...this.it,...r,items:void 0,props:void 0};return nZ(n,t),n}mergeEvaluated(e,t){let{it:r,gen:n}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=Ut.mergeEvaluated.props(n,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=Ut.mergeEvaluated.items(n,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:n}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,M.Name)),!0}}oO.KeywordCxt=V_;function nO(e,t,r,n){let s=new V_(e,r,t);if("code"in r)r.code(s,n);else if(s.$data&&r.validate)Mn.funcKeywordCode(s,r);else if("macro"in r)Mn.macroKeywordCode(s,r);else if(r.compile||r.validate)Mn.funcKeywordCode(s,r)}var yZ=/^\/(?:[^~]|~0|~1)*$/,wZ=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function sO(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let s,o;if(e==="")return ge.default.rootData;if(e[0]==="/"){if(!yZ.test(e))throw Error(`Invalid JSON-pointer: ${e}`);s=e,o=ge.default.rootData}else{let l=wZ.exec(e);if(!l)throw Error(`Invalid JSON-pointer: ${e}`);let u=+l[1];if(s=l[2],s==="#"){if(u>=t)throw Error(c("property/index",u));return n[t-u]}if(u>t)throw Error(c("data",u));if(o=r[t-u],!s)return o}let i=o,a=s.split("/");for(let l of a)if(l)o=M._`${o}${M.getProperty(Ut.unescapeJsonPointer(l))}`,i=M._`${i} && ${o}`;return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${t}`}}oO.getData=sO});var vf=H(function(cO){Object.defineProperty(cO,"__esModule",{value:!0});class aO extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}cO.default=aO});var Bl=H(function(uO){Object.defineProperty(uO,"__esModule",{value:!0});var ma=jl();class lO extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`);this.missingRef=ma.resolveUrl(e,t,r),this.missingSchema=ma.normalizeId(ma.getFullPath(e,this.missingRef))}}uO.default=lO});var Sf=H(function(fO){Object.defineProperty(fO,"__esModule",{value:!0});fO.resolveSchema=fO.getCompilingSchema=fO.resolveRef=fO.compileSchema=fO.SchemaEnv=void 0;var ht=Se(),SZ=vf(),Qo=gs(),gt=jl(),_f=ze(),dO=Ul();class ql{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:gt.normalizeId(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}fO.SchemaEnv=ql;function H_(e){let t=pO.call(this,e);if(t)return t;let r=gt.getFullPath(this.opts.uriResolver,e.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ht.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;if(e.$async)a=i.scopeValue("Error",{ref:SZ.default,code:ht._`require("ajv/dist/runtime/validation_error").default`});let c=i.scopeName("validate");e.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Qo.default.data,parentData:Qo.default.parentData,parentDataProperty:Qo.default.parentDataProperty,dataNames:[Qo.default.data],dataPathArr:[ht.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:ht.stringify(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ht.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:ht._`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),dO.validateFunctionCode(l),i.optimize(this.opts.code.optimize);let d=i.toString();if(u=`${i.scopeRefs(Qo.default.scope)}return ${d}`,this.opts.code.process)u=this.opts.code.process(u,e);let f=Function(`${Qo.default.self}`,`${Qo.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async)f.$async=!0;if(this.opts.code.source===!0)f.source={validateName:c,validateCode:d,scopeValues:i._values};if(this.opts.unevaluated){let{props:m,items:h}=l;if(f.evaluated={props:m instanceof ht.Name?void 0:m,items:h instanceof ht.Name?void 0:h,dynamicProps:m instanceof ht.Name,dynamicItems:h instanceof ht.Name},f.source)f.source.evaluated=ht.stringify(f.evaluated)}return e.validate=f,e}catch(d){if(delete e.validate,delete e.validateName,u)this.logger.error("Error compiling schema, function code:",u);throw d}finally{this._compilations.delete(e)}}fO.compileSchema=H_;function $Z(e,t,r){var n;r=gt.resolveUrl(this.opts.uriResolver,t,r);let s=e.refs[r];if(s)return s;let o=PZ.call(this,e,r);if(o===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;if(i)o=new ql({schema:i,schemaId:a,root:e,baseId:t})}if(o===void 0)return;return e.refs[r]=kZ.call(this,o)}fO.resolveRef=$Z;function kZ(e){if(gt.inlineRef(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:H_.call(this,e)}function pO(e){for(let t of this._compilations)if(TZ(t,e))return t}fO.getCompilingSchema=pO;function TZ(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function PZ(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||xf.call(this,e,t)}function xf(e,t){let r=this.opts.uriResolver.parse(t),n=gt._getFullPath(this.opts.uriResolver,r),s=gt.getFullPath(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===s)return Z_.call(this,r,e);let o=gt.normalizeId(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=xf.call(this,e,i);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Z_.call(this,r,a)}if(typeof(i===null||i===void 0?void 0:i.schema)!=="object")return;if(!i.validate)H_.call(this,i);if(o===gt.normalizeId(t)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];if(l)s=gt.resolveUrl(this.opts.uriResolver,s,l);return new ql({schema:a,schemaId:c,root:e,baseId:s})}return Z_.call(this,r,i)}fO.resolveSchema=xf;var EZ=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Z_(e,{baseId:t,schema:r,root:n}){var s;if(((s=e.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[_f.unescapeFragment(a)];if(c===void 0)return;r=c;let l=typeof r==="object"&&r[this.opts.schemaId];if(!EZ.has(a)&&l)t=gt.resolveUrl(this.opts.uriResolver,t,l)}let o;if(typeof r!="boolean"&&r.$ref&&!_f.schemaHasRulesButRef(r,this.RULES)){let a=gt.resolveUrl(this.opts.uriResolver,t,r.$ref);o=xf.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new ql({schema:r,schemaId:i,root:n,baseId:t}),o.schema!==o.root.schema)return o;return}});var hO=H(function(xge,OZ){OZ.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var X_=H(function(Sge,SO){var zZ=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),K_=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),MZ=RegExp.prototype.test.bind(/^\d*$/u),Xo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),W_=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),yO=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),J_=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),NZ=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),kr=Array(256);for(let t=0;t<256;t++)kr[t]="%"+"0123456789ABCDEF"[t>>4]+"0123456789ABCDEF"[t&15];function er(e){if(e<2048)return kr[192|e>>6]+kr[128|e&63];if(e<65536)return kr[224|e>>12]+kr[128|e>>6&63]+kr[128|e&63];return kr[240|e>>18]+kr[128|e>>12&63]+kr[128|e>>6&63]+kr[128|e&63]}function LZ(e){let t="",r=0,n=0;for(n=0;n<e.length;n++){if(r=e[n].charCodeAt(0),r===48)continue;if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var DZ=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),jZ=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),UZ=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),BZ=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function qZ(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++){if(UZ(e[t]))continue;if(e[t]==="%"&&t+2<e.length&&Xo(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function gO(e){let t=-1,r=0,n=-1,s=0;for(let a=0;a<e.length;a++)if(e[a]==="0"){if(n===-1)n=a;if(s++,s>r)r=s,t=n}else n=-1,s=0;if(r<2)return e.join(":");let o=e.slice(0,t).join(":"),i=e.slice(t+r).join(":");return o+"::"+i}function FZ(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");if(t!==-1){if(r.length===1&&r[0]==="")r.length=0;if(n.length===1&&n[0]==="")n.length=0}let s=r.concat(n),o=0;for(let a=0;a<s.length;a++){let c=s[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==s.length-1||t!==-1&&n.length===0||!K_(c))return;o+=2;continue}if(!DZ(c))return;s[a]=parseInt(c,16).toString(16),o++}if(t===-1){if(o!==8)return;return gO(s)}if(o>=8)return;let i=s.slice(0,r.length);for(let a=o;a<8;a++)i.push("0");for(let a=r.length;a<s.length;a++)i.push(s[a]);return gO(i)}function G_(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&jZ(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(VZ(n,":")<2)return{host:e,isIPV6:!1,error:t};let s="",o=n.indexOf("%");if(o!==-1){let a=n.slice(o,o+3).toLowerCase()==="%25"?3:1;if(s=n.slice(o+a),!qZ(s))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,o)}let i=FZ(n);if(i===void 0)return{host:e,isIPV6:!1,error:!0};return{host:i+(s?"%"+s:""),escapedHost:i+(s?"%25"+s:""),isIPV6:!0}}function VZ(e,t){let r=0;for(let n=0;n<e.length;n++)if(e[n]===t)r++;return r}function wO(e){let t=e,r=[],n=-1,s=0;while(s=t.length){if(s===1)if(t===".")break;else if(t==="/"){r.push("/");break}else{r.push(t);break}else if(s===2){if(t[0]==="."){if(t[1]===".")break;else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."||t[1]==="/"){r.push("/");break}}}else if(s===3){if(t==="/.."){if(r.length!==0)r.pop();r.push("/");break}}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"){if(t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."){if(t[3]==="/"){if(t=t.slice(3),r.length!==0)r.pop();continue}}}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function ZZ(e){if(e===""||e[0]==="/")return wO(e);let t=e.split("/"),r=t.length-1,n=[],s=!1;for(let o=0;o<=r;o++){let i=t[o];if(i==="."||i===".."){if(i==="..")if(n.length!==0&&n[n.length-1]!=="..")n.pop();else n.push("..");s=o===r}else n.push(i)}if(s&&n[n.length-1]!=="..")n.push("");if(n.length===0||n[0]===""||n[0].includes(":"))n.unshift(".");return n.join("/")}var HZ={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},GZ=/[@/?#:]/g,KZ=/[@/?#]/g;function bO(e,t){let r=t?KZ:GZ;return r.lastIndex=0,e.replace(r,(n)=>HZ[n])}function vO(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let s=e.slice(n+1,n+3);if(Xo(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));if(t&&W_(i))r+=i;else r+="%"+o;n+=2;continue}}r+=e[n]}return r}function WZ(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let s=e.slice(r+1,r+3);if(Xo(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));if(i!=="."&&W_(i))t+=i;else t+="%"+o;r+=2;continue}}if(yO(n))t+=n;else{let s=e.charCodeAt(r);if(s<128)t+=xO(s)?n:kr[s];else if(s<55296||s>57343)t+=er(s);else if(s<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);if(o>=56320&&o<=57343)t+=er(65536+(s-55296<<10)+(o-56320)),r++;else t+=er(65533)}else t+=er(65533)}}return t}function JZ(e,t=!1){let r="",n=t&&e[0]!=="/";for(let s=0;s<e.length;s++){let o=e[s];if(o==="%"&&s+2<e.length){let i=e.slice(s+1,s+3);if(Xo(i)){r+="%"+i.toUpperCase(),s+=2;continue}}if(o==="/")n=!1;if(yO(o)&&(o!==":"||!n))r+=o;else{let i=e.charCodeAt(s);if(i<128)r+=kr[i];else if(i<55296||i>57343)r+=er(i);else if(i<=56319&&s+1<e.length){let a=e.charCodeAt(s+1);if(a>=56320&&a<=57343)r+=er(65536+(i-55296<<10)+(a-56320)),s++;else r+=er(65533)}else r+=er(65533)}}return r}function Q_(e,t){let r="";for(let n=0;n<e.length;n++){let s=e[n];if(s==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Xo(o)){r+="%"+o.toUpperCase(),n+=2;continue}}if(t(s))r+=s;else{let o=e.charCodeAt(n);if(o<128)r+=kr[o];else if(o<55296||o>57343)r+=er(o);else if(o<=56319&&n+1<e.length){let i=e.charCodeAt(n+1);if(i>=56320&&i<=57343)r+=er(65536+(o-55296<<10)+(i-56320)),n++;else r+=er(65533)}else r+=er(65533)}}return r}function _O(e){return Q_(e,NZ)}function QZ(e){return Q_(e,J_)}function XZ(e){return Q_(e,J_)}function xO(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function YZ(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let s=e.slice(r+1,r+3);if(Xo(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));if(W_(i))t+=i;else t+="%"+o;r+=2;continue}}if(J_(n))t+=n;else{let s=e.charCodeAt(r);if(s<128)t+=xO(s)?n:kr[s];else if(s<55296||s>57343)t+=er(s);else if(s<=56319&&r+1<e.length){let o=e.charCodeAt(r+1);if(o>=56320&&o<=57343)t+=er(65536+(s-55296<<10)+(o-56320)),r++;else t+=er(65533)}else t+=er(65533)}}return t}function eH(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Xo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function tH(e){let t=[];if(e.userinfo!==void 0)t.push(_O(e.userinfo)),t.push("@");if(e.host!==void 0){let r=e.host;if(!K_(r)){let n=G_(r);if(n.isIPV6!==!0&&n.isIPVFuture!==!0)r=vO(r,!0),n=G_(r);if(n.isIPV6===!0||n.isIPVFuture===!0)r=`[${n.escapedHost}]`;else r=bO(r,!1)}t.push(r)}if(typeof e.port==="number"||typeof e.port==="string"){let r=String(e.port);if(!MZ(r))throw TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}SO.exports={nonSimpleDomain:BZ,recomposeAuthority:tH,reescapeHostDelimiters:bO,normalizePercentEncoding:vO,normalizePathEncoding:WZ,serializePathEncoding:JZ,normalizeQueryFragmentEncoding:YZ,encodeUserinfo:_O,encodeQuery:QZ,encodeFragment:XZ,escapePreservingEscapes:eH,removeDotSegments:wO,removeDotSegmentsRelative:ZZ,isIPv4:K_,isUUID:zZ,normalizeIPv6:G_,stringArrayToHexStripped:LZ}});var EO=H(function($ge,PO){var{isUUID:rH}=X_(),nH=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,sH=["http","https","ws","wss","urn","urn:uuid"];function oH(e){return sH.indexOf(e)!==-1}function Y_(e){if(e.secure===!0)return!0;else if(e.secure===!1)return!1;else if(e.scheme)return e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S");else return!1}function $O(e){if(!e.host)e.error=e.error||"HTTP URIs must have a host.";return e}function kO(e){let t=String(e.scheme).toLowerCase()==="https";if(e.port===(t?443:80)||e.port==="")e.port=void 0;if(!e.path)e.path="/";return e}function iH(e){return e.secure=Y_(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function aH(e){if(e.port===(Y_(e)?443:80)||e.port==="")e.port=void 0;if(typeof e.secure==="boolean")e.scheme=e.secure?"wss":"ws",e.secure=void 0;if(e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function cH(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(nH);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let s=`${n}:${t.nid||e.nid}`,o=e0(s);if(e.path=void 0,o)e=o.parse(e,t)}else e.error=e.error||"URN can not be parsed.";return e}function lH(e,t){if(e.nid===void 0)throw Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),s=`${r}:${t.nid||n}`,o=e0(s);if(o)e=o.serialize(e,t);let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function uH(e,t){let r=e;if(r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!rH(r.uuid)))r.error=r.error||"UUID is not valid.";return r}function dH(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var TO={scheme:"http",domainHost:!0,parse:$O,serialize:kO},pH={scheme:"https",domainHost:TO.domainHost,parse:$O,serialize:kO},$f={scheme:"ws",domainHost:!0,parse:iH,serialize:aH},fH={scheme:"wss",domainHost:$f.domainHost,parse:$f.parse,serialize:$f.serialize},mH={scheme:"urn",parse:cH,serialize:lH,skipNormalize:!0},hH={scheme:"urn:uuid",parse:uH,serialize:dH,skipNormalize:!0},kf={http:TO,https:pH,ws:$f,wss:fH,urn:mH,"urn:uuid":hH};Object.setPrototypeOf(kf,null);function e0(e){return e&&(kf[e]||kf[e.toLowerCase()])||void 0}PO.exports={wsIsSecure:Y_,SCHEMES:kf,isValidSchemeName:oH,getSchemeHandler:e0}});var qO=H(function(kge,If){var{normalizeIPv6:OO,removeDotSegments:Vl,removeDotSegmentsRelative:zO,recomposeAuthority:gH,normalizePercentEncoding:t0,normalizePathEncoding:yH,serializePathEncoding:IO,normalizeQueryFragmentEncoding:AO,encodeQuery:wH,encodeFragment:bH,reescapeHostDelimiters:vH,isIPv4:MO,nonSimpleDomain:_H}=X_(),{SCHEMES:NO,getSchemeHandler:r0}=EO(),LO=/^[A-Za-z][A-Za-z0-9+.-]*$/u,xH=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function RO(e){let t=String(e);if(!LO.test(t))throw TypeError("URI scheme is malformed.");return t}function SH(e,t){if(typeof e==="string")e=CH(e,t);else if(typeof e==="object")e=Pf(Yo(e,t),t);return e}function $H(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=Tf(e,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:p,malformedSchemeSpecific:f,malformedHost:m,malformedScheme:h}=Tf(t,n);if(o||d||i||p||a||f||c||m||l||h)throw Error(s.error||u.error||"URI is malformed.");let g=DO(s,u,n,!0),w=r0(r&&r.scheme||g.scheme),v=g.host,_=v!==void 0&&v!==""&&(MO(v)||OO(v).isIPV6);if(UO(g,r||{},w,_))throw Error("URI host is malformed.");jO(g,r||{},w,_);let C=v&&v.indexOf("%")!==-1&&!/\P{ASCII}/u.test(v);if(g.error&&!C)throw Error(g.error);return n.skipEscape=!0,Yo(g,n)}function DO(e,t,r,n){let s={};if(!n)e=Pf(Yo(e,r),r),t=Pf(Yo(t,r),r);if(r=r||{},!r.tolerant&&t.scheme)s.scheme=t.scheme,s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=Vl(t.path||""),s.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)s.userinfo=t.userinfo,s.host=t.host,s.port=t.port,s.path=Vl(t.path||""),s.query=t.query;else{if(!t.path)if(s.path=e.path,t.query!==void 0)s.query=t.query;else s.query=e.query;else{if(t.path[0]==="/")s.path=Vl(t.path);else{let o=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;if(o&&!e.path)s.path="/"+t.path;else if(!e.path)s.path=t.path;else s.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path;s.path=e.scheme===void 0&&!o&&s.path[0]!=="/"?zO(s.path):Vl(s.path)}s.query=t.query}s.userinfo=e.userinfo,s.host=e.host,s.port=e.port}s.scheme=e.scheme}return s.fragment=t.fragment,s}function kH(e,t,r){let n=CO(e,r),s=CO(t,r);return n!==void 0&&s!==void 0&&n===s}function Yo(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),s=[];if(r.scheme)r.scheme=RO(r.scheme);let o=r0(n.scheme||r.scheme);if(o&&o.serialize)o.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,c=!n.skipEscape&&a;if(r.path!==void 0)if(!n.skipEscape)r.path=IO(r.path,c);else r.path=t0(r.path);if(n.reference!=="suffix"&&r.scheme)r.scheme=RO(r.scheme),s.push(r.scheme,":");let l=gH(r);if(l!==void 0){if(n.reference!=="suffix")s.push("//");if(s.push(l),r.path&&r.path[0]!=="/")s.push("/")}if(r.path!==void 0){let u=r.path;if(!n.absolutePath&&(!o||!o.absolutePath))u=a&&u[0]!=="/"?zO(u):Vl(u);if(a)u=IO(u,!0);if(l===void 0&&u[0]==="/"&&u[1]==="/")u="/%2F"+u.slice(2);s.push(u)}if(r.query!==void 0)s.push("?",wH(r.query));if(r.fragment!==void 0)s.push("#",bH(r.fragment));return s.join("")}var TH=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,PH=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,EH=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function IH(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port==="number"&&(e.port<0||e.port>65535))return"URI port is malformed.";return}function Fl(e){if(e===void 0)return!1;let t=e.indexOf("%");while(t!==-1){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function Ef(e){return e[0]==="["&&e[e.length-1]==="]"}function AH(e){let t=e[4];return Fl(e[3])||t!==void 0&&!Ef(t)&&Fl(t)||Fl(e[6])||Fl(e[7])||Fl(e[8])}function jO(e,t,r,n){if(UO(e,t,r,n))return e.error=e.error||"URI host is malformed.",!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Ef(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&_H(e.host)){let s;try{s=new URL("http://"+e.host)}catch(o){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+o,!0}if(!RH(s))return e.error=e.error||"URI host is malformed.",!0;e.host=s.hostname}return!1}function UO(e,t,r,n){return Boolean(e.host&&n===!1&&!Ef(e.host)&&(t.domainHost||r&&r.domainHost)&&xH.test(e.host))}function RH(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Tf(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1,i=!1,a=!1,c=!1,l=!1,u=!1;if(r.reference==="suffix")if(r.scheme)e=r.scheme+":"+e;else e="//"+e;let d=e.match(PH);if(d!==null&&d[1].indexOf("\\")!==-1)n.error="URI authority must not contain a literal backslash.",s=!0;let p=e.match(EH);if(p!==null){let m=p[1],h=m.replace(/[\t\n\r]/g,"");if(h.length>=2){if(h.slice(0,2)!=="//")n.error=n.error||"URI authority must not contain a literal backslash.",s=!0;else if(m.length!==h.length)n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0}}let f=e.match(TH);if(f){if(n.scheme=f[1],n.userinfo=f[3],n.host=f[4],n.port=parseInt(f[5],10),n.path=f[6]||"",n.query=f[7],n.fragment=f[8],n.scheme!==void 0)if(LO.test(n.scheme))n.scheme=n.scheme.toLowerCase();else n.error=n.error||"URI scheme is malformed.",l=!0;if(o=AH(f),o)n.error=n.error||"URI contains malformed percent-encoding.";if(isNaN(n.port))n.port=f[5];let m=IH(n,f);if(m!==void 0)n.error=n.error||m,s=!0;if(n.host)if(MO(n.host)===!1){let w=Ef(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,_=OO(n.host);if(u=_.isIPV6||_.isIPVFuture===!0,c=v&&(!w||_.error===!0),n.host=u?_.host:_.host.toLowerCase(),c)n.error=n.error||"URI host is malformed.",s=!0}else u=!0;if(n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path)n.reference="same-document";else if(n.scheme===void 0)n.reference="relative";else if(n.fragment===void 0)n.reference="absolute";else n.reference="uri";if(r.reference&&r.reference!=="suffix"&&r.reference!==n.reference)n.error=n.error||"URI is not a "+r.reference+" reference.";let h=r0(r.scheme||n.scheme);if(!c)a=jO(n,r,h,u);if(e.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=u?n.host:t0(n.host,!0);if(!u)g=t0(g.toLowerCase());n.host=u||r.scheme!=="null"?vH(g,u):g}if(!h||h&&!h.skipNormalize){if(n.path)n.path=yH(n.path);if(n.query)n.query=AO(n.query);if(n.fragment)n.fragment=AO(n.fragment)}if(h&&h.parse){if(h.parse(n,r),h===NO.urn&&n.nid===void 0)i=!0}}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}}function Pf(e,t){return Tf(e,t).parsed}function CH(e,t){return BO(e,t).normalized}function BO(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}=Tf(e,t);return{normalized:n||s||o||i||a?e:Yo(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:i,malformedScheme:a}}function CO(e,t){if(typeof e!=="string"&&typeof e!=="object")return;let r;try{r=typeof e==="string"?e:Yo(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=BO(r,t);return s||o||i||a||c?void 0:n}var n0={SCHEMES:NO,normalize:SH,resolve:$H,resolveComponent:DO,equal:kH,serialize:Yo,parse:Pf};If.exports=n0;If.exports.default=n0;If.exports.fastUri=n0});var ZO=H(function(VO){Object.defineProperty(VO,"__esModule",{value:!0});var FO=qO();FO.code='require("ajv/dist/runtime/uri").default';VO.default=FO});var t2=H(function(ys){Object.defineProperty(ys,"__esModule",{value:!0});ys.CodeGen=ys.Name=ys.nil=ys.stringify=ys.str=ys._=ys.KeywordCxt=void 0;var zH=Ul();Object.defineProperty(ys,"KeywordCxt",{enumerable:!0,get:function(){return zH.KeywordCxt}});var ga=Se();Object.defineProperty(ys,"_",{enumerable:!0,get:function(){return ga._}});Object.defineProperty(ys,"str",{enumerable:!0,get:function(){return ga.str}});Object.defineProperty(ys,"stringify",{enumerable:!0,get:function(){return ga.stringify}});Object.defineProperty(ys,"nil",{enumerable:!0,get:function(){return ga.nil}});Object.defineProperty(ys,"Name",{enumerable:!0,get:function(){return ga.Name}});Object.defineProperty(ys,"CodeGen",{enumerable:!0,get:function(){return ga.CodeGen}});var MH=vf(),JO=Bl(),QO=z_(),Nn=Sf(),XO=Se(),Ln=jl(),ro=Dl(),ha=ze(),HO=hO(),NH=ZO(),YO=(e,t)=>new RegExp(e,t);YO.code="new RegExp";var LH=["removeAdditional","useDefaults","coerceTypes"],DH=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),jH={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},UH={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},GO=200;function BH(e){var t,r,n,s,o,i,a,c,l,u,d,p,f,m,h,g,w,v,_,C,k,P,y,x,T;let I=e.strict,j=(t=e.code)===null||t===void 0?void 0:t.optimize,se=j===!0||j===void 0?1:j||0,we=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:YO,de=(s=e.uriResolver)!==null&&s!==void 0?s:NH.default;return{strictSchema:(i=(o=e.strictSchema)!==null&&o!==void 0?o:I)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:I)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=e.strictTypes)!==null&&l!==void 0?l:I)!==null&&u!==void 0?u:"log",strictTuples:(p=(d=e.strictTuples)!==null&&d!==void 0?d:I)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=e.strictRequired)!==null&&f!==void 0?f:I)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:se,regExp:we}:{optimize:se,regExp:we},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:GO,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:GO,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=e.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(C=e.schemaId)!==null&&C!==void 0?C:"$id",addUsedSchema:(k=e.addUsedSchema)!==null&&k!==void 0?k:!0,validateSchema:(P=e.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(y=e.validateFormats)!==null&&y!==void 0?y:!0,unicodeRegExp:(x=e.unicodeRegExp)!==null&&x!==void 0?x:!0,int32range:(T=e.int32range)!==null&&T!==void 0?T:!0,uriResolver:de}}class Af{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...BH(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new XO.ValueScope({scope:{},prefixes:DH,es5:t,lines:r}),this.logger=GH(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=QO.getRules(),KO.call(this,jH,e,"NOT SUPPORTED"),KO.call(this,UH,e,"DEPRECATED","warn"),this._metaOpts=ZH.call(this),e.formats)FH.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)VH.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);qH.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,n=HO;if(r==="id")n={...HO},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let n=r(t);if(!("$async"in r))this.errors=r.errors;return n}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(l,u){await s.call(this,l.$schema);let d=this._addSchema(l,u);return d.validate||o.call(this,d)}async function s(l){if(l&&!this.getSchema(l))await n.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(u){if(!(u instanceof JO.default))throw u;return i.call(this,u),await a.call(this,u.missingSchema),o.call(this,l)}}function i({missingSchema:l,missingRef:u}){if(this.refs[l])throw Error(`AnySchema ${l} is loaded but ${u} cannot be resolved`)}async function a(l){let u=await c.call(this,l);if(!this.refs[l])await s.call(this,u.$schema);if(!this.refs[l])this.addSchema(u,l,t)}async function c(l){let u=this._loading[l];if(u)return u;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,r,n);return this}let s;if(typeof e==="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw Error(`schema ${o} must be string`)}return t=Ln.normalizeId(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(r,e);if(!n&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw Error(s)}return n}getSchema(e){let t;while(typeof(t=WO.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,n=new Nn.SchemaEnv({schema:{},schemaId:r});if(t=Nn.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=WO.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=Ln.normalizeId(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(WH.call(this,r,t),!t)return ha.eachItem(r,(s)=>s0.call(this,s)),this;QH.call(this,t);let n={...t,type:ro.getJSONTypes(t.type),schemaType:ro.getJSONTypes(t.schemaType)};return ha.eachItem(r,n.type.length===0?(s)=>s0.call(this,s,n):(s)=>n.type.forEach((o)=>s0.call(this,s,n,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let n=r.rules.findIndex((s)=>s.keyword===e);if(n>=0)r.rules.splice(n,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((n)=>`${r}${n.instancePath} ${n.message}`).reduce((n,s)=>n+t+s)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let s=n.split("/").slice(1),o=e;for(let i of s)o=o[i];for(let i in r){let a=r[i];if(typeof a!="object")continue;let{$data:c}=a.definition,l=o[i];if(c&&l)o[i]=e2(l)}}return e}_removeAllSchemas(e,t){for(let r in e){let n=e[r];if(!t||t.test(r)){if(typeof n=="string")delete e[r];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[r]}}}_addSchema(e,t,r,n=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:i}=this.opts;if(typeof e=="object")o=e[i];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=Ln.normalizeId(o||r);let c=Ln.getSchemaRefs.call(this,e,r);if(a=new Nn.SchemaEnv({schema:e,schemaId:i,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),s&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(n)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else Nn.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Nn.compileSchema.call(this,e)}finally{this.opts=t}}}Af.ValidationError=MH.default;Af.MissingRefError=JO.default;ys.default=Af;function KO(e,t,r,n="error"){for(let s in e){let o=s;if(o in t)this.logger[n](`${r}: option ${s}. ${e[o]}`)}}function WO(e){return e=Ln.normalizeId(e),this.schemas[e]||this.refs[e]}function qH(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function FH(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function VH(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function ZH(){let e={...this.opts};for(let t of LH)delete e[t];return e}var HH={log(){},warn(){},error(){}};function GH(e){if(e===!1)return HH;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var KH=/^[a-z_$][a-z0-9_$:-]*$/i;function WH(e,t){let{RULES:r}=this;if(ha.eachItem(e,(n)=>{if(r.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!KH.test(n))throw Error(`Keyword ${n} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function s0(e,t,r){var n;let s=t===null||t===void 0?void 0:t.post;if(r&&s)throw Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(!i)i={type:r,rules:[]},o.rules.push(i);if(o.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:ro.getJSONTypes(t.type),schemaType:ro.getJSONTypes(t.schemaType)}};if(t.before)JH.call(this,i,a,t.before);else i.rules.push(a);o.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((c)=>this.addKeyword(c))}function JH(e,t,r){let n=e.rules.findIndex((s)=>s.keyword===r);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function QH(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=e2(t);e.validateSchema=this.compile(t,!0)}var XH={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function e2(e){return{anyOf:[e,XH]}}});var n2=H(function(r2){Object.defineProperty(r2,"__esModule",{value:!0});var tG={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};r2.default=tG});var a2=H(function(o2){Object.defineProperty(o2,"__esModule",{value:!0});o2.callRef=o2.getValidate=void 0;var nG=Bl(),Cf=Qr(),Ze=Se(),ya=gs(),Of=Sf(),no=ze(),sG={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:l}=o;if((r==="#"||r==="#/")&&s===l.baseId)return d();let u=Of.resolveRef.call(c,l,s,r);if(u===void 0)throw new nG.default(n.opts.uriResolver,s,r);if(u instanceof Of.SchemaEnv)return p(u);return f(u);function d(){if(o===l)return Rf(e,i,o,o.$async);let m=t.scopeValue("root",{ref:l});return Rf(e,Ze._`${m}.validate`,l,l.$async)}function p(m){let h=s2(e,m);Rf(e,h,m,m.$async)}function f(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:Ze.stringify(m)}:{ref:m}),g=t.name("valid"),w=e.subschema({schema:m,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(w),e.ok(g)}}};function s2(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):Ze._`${r.scopeValue("wrapper",{ref:t})}.validate`}o2.getValidate=s2;function Rf(e,t,r,n){let{gen:s,it:o}=e,{allErrors:i,schemaEnv:a,opts:c}=o,l=c.passContext?ya.default.this:Ze.nil;if(n)u();else d();function u(){if(!a.$async)throw Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{if(s.code(Ze._`await ${Cf.callValidateCode(e,t,l)}`),f(t),!i)s.assign(m,!0)},(h)=>{if(s.if(Ze._`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),!i)s.assign(m,!1)}),e.ok(m)}function d(){e.result(Cf.callValidateCode(e,t,l),()=>f(t),()=>p(t))}function p(m){let h=Ze._`${m}.errors`;s.assign(ya.default.vErrors,Ze._`${ya.default.vErrors} === null ? ${h} : ${ya.default.vErrors}.concat(${h})`),s.assign(ya.default.errors,Ze._`${ya.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let g=(h=r===null||r===void 0?void 0:r.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps){if(g.props!==void 0)o.props=no.mergeEvaluated.props(s,g.props,o.props)}else{let w=s.var("props",Ze._`${m}.evaluated.props`);o.props=no.mergeEvaluated.props(s,w,o.props,Ze.Name)}if(o.items!==!0)if(g&&!g.dynamicItems){if(g.items!==void 0)o.items=no.mergeEvaluated.items(s,g.items,o.items)}else{let w=s.var("items",Ze._`${m}.evaluated.items`);o.items=no.mergeEvaluated.items(s,w,o.items,Ze.Name)}}}o2.callRef=Rf;o2.default=sG});var l2=H(function(c2){Object.defineProperty(c2,"__esModule",{value:!0});var aG=n2(),cG=a2(),lG=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",aG.default,cG.default];c2.default=lG});var d2=H(function(u2){Object.defineProperty(u2,"__esModule",{value:!0});var oo=Se(),so=oo.operators,zf={maximum:{okStr:"<=",ok:so.LTE,fail:so.GT},minimum:{okStr:">=",ok:so.GTE,fail:so.LT},exclusiveMaximum:{okStr:"<",ok:so.LT,fail:so.GTE},exclusiveMinimum:{okStr:">",ok:so.GT,fail:so.LTE}},dG={message:({keyword:e,schemaCode:t})=>oo.str`must be ${zf[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>oo._`{comparison: ${zf[e].okStr}, limit: ${t}}`},pG={keyword:Object.keys(zf),type:"number",schemaType:"number",$data:!0,error:dG,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data(oo._`${r} ${zf[t].fail} ${n} || isNaN(${r})`)}};u2.default=pG});var f2=H(function(p2){Object.defineProperty(p2,"__esModule",{value:!0});var Dn=Se(),mG={message:({schemaCode:e})=>Dn.str`must be multiple of ${e}`,params:({schemaCode:e})=>Dn._`{multipleOf: ${e}}`},hG={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mG,code(e){let{gen:t,data:r,schemaCode:n,it:s}=e,o=s.opts.multipleOfPrecision,i=t.let("res"),a=o?Dn._`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:Dn._`${i} !== parseInt(${i})`;e.fail$data(Dn._`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};p2.default=hG});var g2=H(function(h2){Object.defineProperty(h2,"__esModule",{value:!0});function m2(e){let t=e.length,r=0,n=0,s;while(n<t)if(r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<t){if(s=e.charCodeAt(n),(s&64512)===56320)n++}return r}h2.default=m2;m2.code='require("ajv/dist/runtime/ucs2length").default'});var b2=H(function(w2){Object.defineProperty(w2,"__esModule",{value:!0});var Tr=Se(),y2=ze(),wG=g2(),bG={message({keyword:e,schemaCode:t}){return Tr.str`must NOT have ${e==="maxLength"?"more":"fewer"} than ${t} characters`},params:({schemaCode:e})=>Tr._`{limit: ${e}}`},vG={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bG,code(e){let{keyword:t,data:r,schemaCode:n,it:s}=e,o=t==="maxLength"?Tr.operators.GT:Tr.operators.LT,i=s.opts.unicode===!1?Tr._`${r}.length`:Tr._`${y2.useFunc(e.gen,wG.default)}(${r})`;e.fail$data(Tr._`${i} ${o} ${n}`)}};w2.default=vG});var S2=H(function(x2){Object.defineProperty(x2,"__esModule",{value:!0});var v2=Qr(),_2=ze(),Xr=Se(),xG={message:({schemaCode:e})=>Xr.str`must match pattern "${e}"`,params:({schemaCode:e})=>Xr._`{pattern: ${e}}`},SG={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xG,code(e){let{gen:t,data:r,$data:n,schema:s,schemaCode:o,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,l=c.code==="new RegExp"?Xr._`new RegExp`:_2.useFunc(t,c),u=t.let("valid");t.try(()=>t.assign(u,Xr._`${l}(${o}, ${a}).test(${r})`),()=>t.assign(u,!1)),e.fail$data(Xr._`!${u}`)}else{let c=v2.usePattern(e,s);e.fail$data(Xr._`!${c}.test(${r})`)}}};x2.default=SG});var k2=H(function($2){Object.defineProperty($2,"__esModule",{value:!0});var jn=Se(),kG={message({keyword:e,schemaCode:t}){return jn.str`must NOT have ${e==="maxProperties"?"more":"fewer"} than ${t} properties`},params:({schemaCode:e})=>jn._`{limit: ${e}}`},TG={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:kG,code(e){let{keyword:t,data:r,schemaCode:n}=e,s=t==="maxProperties"?jn.operators.GT:jn.operators.LT;e.fail$data(jn._`Object.keys(${r}).length ${s} ${n}`)}};$2.default=TG});var E2=H(function(P2){Object.defineProperty(P2,"__esModule",{value:!0});var Un=Qr(),Bn=Se(),T2=ze(),EG={message:({params:{missingProperty:e}})=>Bn.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Bn._`{missingProperty: ${e}}`},IG={keyword:"required",type:"object",schemaType:"array",$data:!0,error:EG,code(e){let{gen:t,schema:r,schemaCode:n,data:s,$data:o,it:i}=e,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors)l();else u();if(a.strictRequired){let f=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if((f===null||f===void 0?void 0:f[h])===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,w=`required property "${h}" is not defined at "${g}" (strictRequired)`;T2.checkStrictMode(i,w,i.opts.strictRequired)}}function l(){if(c||o)e.block$data(Bn.nil,d);else for(let f of r)Un.checkReportMissingProp(e,f)}function u(){let f=t.let("missing");if(c||o){let m=t.let("valid",!0);e.block$data(m,()=>p(f,m)),e.ok(m)}else t.if(Un.checkMissingProp(e,r,f)),Un.reportMissingProp(e,f),t.else()}function d(){t.forOf("prop",n,(f)=>{e.setParams({missingProperty:f}),t.if(Un.noPropertyInData(t,s,f,a.ownProperties),()=>e.error())})}function p(f,m){e.setParams({missingProperty:f}),t.forOf(f,n,()=>{t.assign(m,Un.propertyInData(t,s,f,a.ownProperties)),t.if(Bn.not(m),()=>{e.error(),t.break()})},Bn.nil)}}};P2.default=IG});var A2=H(function(I2){Object.defineProperty(I2,"__esModule",{value:!0});var qn=Se(),RG={message({keyword:e,schemaCode:t}){return qn.str`must NOT have ${e==="maxItems"?"more":"fewer"} than ${t} items`},params:({schemaCode:e})=>qn._`{limit: ${e}}`},CG={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:RG,code(e){let{keyword:t,data:r,schemaCode:n}=e,s=t==="maxItems"?qn.operators.GT:qn.operators.LT;e.fail$data(qn._`${r}.length ${s} ${n}`)}};I2.default=CG});var Mf=H(function(C2){Object.defineProperty(C2,"__esModule",{value:!0});var R2=B_();R2.code='require("ajv/dist/runtime/equal").default';C2.default=R2});var M2=H(function(z2){Object.defineProperty(z2,"__esModule",{value:!0});var wa=Dl(),Me=Se(),O2=ze(),MG=Mf(),NG={message:({params:{i:e,j:t}})=>Me.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Me._`{i: ${e}, j: ${t}}`},LG={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:NG,code(e){let{gen:t,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=e;if(!n&&!s)return;let c=t.let("valid"),l=o.items?wa.getSchemaTypes(o.items):[];e.block$data(c,u,Me._`${i} === false`),e.ok(c);function u(){let m=t.let("i",Me._`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if(Me._`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return l.length>0&&!l.some((m)=>m==="object"||m==="array")}function p(m,h){let g=t.name("item"),w=wa.checkDataTypes(l,g,a.opts.strictNumbers,wa.DataType.Wrong),v=t.const("indices",Me._`{}`);t.for(Me._`;${m}--;`,()=>{if(t.let(g,Me._`${r}[${m}]`),t.if(w,Me._`continue`),l.length>1)t.if(Me._`typeof ${g} == "string"`,Me._`${g} += "_"`);t.if(Me._`typeof ${v}[${g}] == "number"`,()=>{t.assign(h,Me._`${v}[${g}]`),e.error(),t.assign(c,!1).break()}).code(Me._`${v}[${g}] = ${m}`)})}function f(m,h){let g=O2.useFunc(t,MG.default),w=t.name("outer");t.label(w).for(Me._`;${m}--;`,()=>t.for(Me._`${h} = ${m}; ${h}--;`,()=>t.if(Me._`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};z2.default=LG});var D2=H(function(L2){Object.defineProperty(L2,"__esModule",{value:!0});var ba=Se(),N2=ze(),jG=Mf(),UG={message:"must be equal to constant",params:({schemaCode:e})=>ba._`{allowedValue: ${e}}`},BG={keyword:"const",$data:!0,error:UG,code(e){let{gen:t,data:r,$data:n,schemaCode:s,schema:o}=e;if(n||o&&typeof o=="object")e.fail$data(ba._`!${N2.useFunc(t,jG.default)}(${r}, ${s})`);else e.fail(ba._`${o} !== ${r}`)}};L2.default=BG});var B2=H(function(U2){Object.defineProperty(U2,"__esModule",{value:!0});var Fn=Se(),j2=ze(),FG=Mf(),VG={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Fn._`{allowedValues: ${e}}`},ZG={keyword:"enum",schemaType:"array",$data:!0,error:VG,code(e){let{gen:t,data:r,$data:n,schema:s,schemaCode:o,it:i}=e;if(!n&&s.length===0)throw Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,l=()=>c!==null&&c!==void 0?c:c=j2.useFunc(t,FG.default),u;if(a||n)u=t.let("valid"),e.block$data(u,d);else{if(!Array.isArray(s))throw Error("ajv implementation error");let f=t.const("vSchema",o);u=Fn.or(...s.map((m,h)=>p(f,h)))}e.pass(u);function d(){t.assign(u,!1),t.forOf("v",o,(f)=>t.if(Fn._`${l()}(${r}, ${f})`,()=>t.assign(u,!0).break()))}function p(f,m){let h=s[m];return typeof h==="object"&&h!==null?Fn._`${l()}(${r}, ${f}[${m}])`:Fn._`${r} === ${h}`}}};U2.default=ZG});var F2=H(function(q2){Object.defineProperty(q2,"__esModule",{value:!0});var GG=d2(),KG=f2(),WG=b2(),JG=S2(),QG=k2(),XG=E2(),YG=A2(),eK=M2(),tK=D2(),rK=B2(),nK=[GG.default,KG.default,WG.default,JG.default,QG.default,XG.default,YG.default,eK.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},tK.default,rK.default];q2.default=nK});var o0=H(function(Z2){Object.defineProperty(Z2,"__esModule",{value:!0});Z2.validateAdditionalItems=void 0;var Pr=Se(),va=ze(),oK={message:({params:{len:e}})=>Pr.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Pr._`{limit: ${e}}`},iK={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oK,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){va.checkStrictMode(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}V2(e,n)}};function V2(e,t){let{gen:r,schema:n,data:s,keyword:o,it:i}=e;i.items=!0;let a=r.const("len",Pr._`${s}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(Pr._`${a} <= ${t.length}`);else if(typeof n=="object"&&!va.alwaysValidSchema(i,n)){let l=r.var("valid",Pr._`${a} <= ${t.length}`);r.if(Pr.not(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,(u)=>{if(e.subschema({keyword:o,dataProp:u,dataPropType:va.Type.Num},l),!i.allErrors)r.if(Pr.not(l),()=>r.break())})}}Z2.validateAdditionalItems=V2;Z2.default=iK});var i0=H(function(W2){Object.defineProperty(W2,"__esModule",{value:!0});W2.validateTuple=void 0;var Nf=Se(),io=ze(),G2=Qr(),cK={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return K2(e,"additionalItems",t);if(r.items=!0,io.alwaysValidSchema(r,t))return;e.ok(G2.validateArray(e))}};function K2(e,t,r=e.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=e;if(u(s),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=io.mergeEvaluated.items(n,r.length,a.items);let c=n.name("valid"),l=n.const("len",Nf._`${o}.length`);r.forEach((d,p)=>{if(io.alwaysValidSchema(a,d))return;n.if(Nf._`${l} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c)});function u(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[t]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;io.checkStrictMode(a,g,p.strictTuples)}}}W2.validateTuple=K2;W2.default=cK});var Y2=H(function(X2){Object.defineProperty(X2,"__esModule",{value:!0});var Q2=i0(),uK={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>Q2.validateTuple(e,"items")};X2.default=uK});var sz=H(function(nz){Object.defineProperty(nz,"__esModule",{value:!0});var Lf=Se(),ez=ze(),tz=Qr(),rz=o0(),pK={message:({params:{len:e}})=>Lf.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>Lf._`{limit: ${e}}`},fK={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:pK,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:s}=r;if(n.items=!0,ez.alwaysValidSchema(n,t))return;if(s)rz.validateAdditionalItems(e,s);else e.ok(tz.validateArray(e))}};nz.default=fK});var iz=H(function(oz){Object.defineProperty(oz,"__esModule",{value:!0});var st=Se(),ao=ze(),hK={message:({params:{min:e,max:t}})=>t===void 0?st.str`must contain at least ${e} valid item(s)`:st.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?st._`{minContains: ${e}}`:st._`{minContains: ${e}, maxContains: ${t}}`},gK={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:hK,code(e){let{gen:t,schema:r,parentSchema:n,data:s,it:o}=e,i,a,{minContains:c,maxContains:l}=n;if(o.opts.next)i=c===void 0?1:c,a=l;else i=1;let u=t.const("len",st._`${s}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){ao.checkStrictMode(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){ao.checkStrictMode(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if(ao.alwaysValidSchema(o,r)){let h=st._`${u} >= ${i}`;if(a!==void 0)h=st._`${h} && ${u} <= ${a}`;e.pass(h);return}o.items=!0;let d=t.name("valid");if(a===void 0&&i===1)f(d,()=>t.if(d,()=>t.break()));else if(i===0){if(t.let(d,!0),a!==void 0)t.if(st._`${s}.length > 0`,p)}else t.let(d,!1),p();e.result(d,()=>e.reset());function p(){let h=t.name("_valid"),g=t.let("count",0);f(h,()=>t.if(h,()=>m(g)))}function f(h,g){t.forRange("i",0,u,(w)=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:ao.Type.Num,compositeRule:!0},h),g()})}function m(h){if(t.code(st._`${h}++`),a===void 0)t.if(st._`${h} >= ${i}`,()=>t.assign(d,!0).break());else if(t.if(st._`${h} > ${a}`,()=>t.assign(d,!1).break()),i===1)t.assign(d,!0);else t.if(st._`${h} >= ${i}`,()=>t.assign(d,!0))}}};oz.default=gK});var fz=H(function(uz){Object.defineProperty(uz,"__esModule",{value:!0});uz.validateSchemaDeps=uz.validatePropertyDeps=uz.error=void 0;var _a=Se(),az=ze(),Vn=Qr();uz.error={message:({params:{property:e,depsCount:t,deps:r}})=>_a.str`must have ${t===1?"property":"properties"} ${r} when property ${e} is present`,params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>_a._`{property: ${e},
|
|
111
|
+
missingProperty: ${n},
|
|
112
|
+
depsCount: ${t},
|
|
113
|
+
deps: ${r}}`};var wK={keyword:"dependencies",type:"object",schemaType:"object",error:uz.error,code(e){let[t,r]=bK(e);cz(e,t),lz(e,r)}};function bK({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let s=Array.isArray(e[n])?t:r;s[n]=e[n]}return[t,r]}function cz(e,t=e.schema){let{gen:r,data:n,it:s}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let c=Vn.propertyInData(r,n,i,s.opts.ownProperties);if(e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors)r.if(c,()=>{for(let l of a)Vn.checkReportMissingProp(e,l)});else r.if(_a._`${c} && (${Vn.checkMissingProp(e,a,o)})`),Vn.reportMissingProp(e,o),r.else()}}uz.validatePropertyDeps=cz;function lz(e,t=e.schema){let{gen:r,data:n,keyword:s,it:o}=e,i=r.name("valid");for(let a in t){if(az.alwaysValidSchema(o,t[a]))continue;r.if(Vn.propertyInData(r,n,a,o.opts.ownProperties),()=>{let c=e.subschema({keyword:s,schemaProp:a},i);e.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),e.ok(i)}}uz.validateSchemaDeps=lz;uz.default=wK});var gz=H(function(hz){Object.defineProperty(hz,"__esModule",{value:!0});var Df=Se(),mz=ze(),xK={message:"property name must be valid",params:({params:e})=>Df._`{propertyName: ${e.propertyName}}`},SK={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:xK,code(e){let{gen:t,schema:r,data:n,it:s}=e;if(mz.alwaysValidSchema(s,r))return;let o=t.name("valid");t.forIn("key",n,(i)=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),t.if(Df.not(o),()=>{if(e.error(!0),!s.allErrors)t.break()})}),e.ok(o)}};hz.default=SK});var a0=H(function(yz){Object.defineProperty(yz,"__esModule",{value:!0});var co=Qr(),yt=Se(),kK=gs(),lo=ze(),TK={message:"must NOT have additional properties",params:({params:e})=>yt._`{additionalProperty: ${e.additionalProperty}}`},PK={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:TK,code(e){let{gen:t,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=e;if(!o)throw Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&lo.alwaysValidSchema(i,r))return;let l=co.allSchemaProperties(n.properties),u=co.allSchemaProperties(n.patternProperties);d(),e.ok(yt._`${o} === ${kK.default.errors}`);function d(){t.forIn("key",s,(g)=>{if(!l.length&&!u.length)m(g);else t.if(p(g),()=>m(g))})}function p(g){let w;if(l.length>8){let v=lo.schemaRefOrVal(i,n.properties,"properties");w=co.isOwnProperty(t,v,g)}else if(l.length)w=yt.or(...l.map((v)=>yt._`${g} === ${v}`));else w=yt.nil;if(u.length)w=yt.or(w,...u.map((v)=>yt._`${co.usePattern(e,v)}.test(${g})`));return yt.not(w)}function f(g){t.code(yt._`delete ${s}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){if(e.setParams({additionalProperty:g}),e.error(),!a)t.break();return}if(typeof r=="object"&&!lo.alwaysValidSchema(i,r)){let w=t.name("valid");if(c.removeAdditional==="failing")h(g,w,!1),t.if(yt.not(w),()=>{e.reset(),f(g)});else if(h(g,w),!a)t.if(yt.not(w),()=>t.break())}}function h(g,w,v){let _={keyword:"additionalProperties",dataProp:g,dataPropType:lo.Type.Str};if(v===!1)Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(_,w)}}};yz.default=PK});var _z=H(function(vz){Object.defineProperty(vz,"__esModule",{value:!0});var bz=Ul(),jf=Qr(),xa=ze(),wz=a0(),IK={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:s,it:o}=e;if(o.opts.removeAdditional==="all"&&n.additionalProperties===void 0)wz.default.code(new bz.KeywordCxt(o,wz.default,"additionalProperties"));let i=jf.allSchemaProperties(r);for(let d of i)o.definedProperties.add(d);if(o.opts.unevaluated&&i.length&&o.props!==!0)o.props=xa.mergeEvaluated.props(t,xa.toHash(i),o.props);let a=i.filter((d)=>!xa.alwaysValidSchema(o,r[d]));if(a.length===0)return;let c=t.name("valid");for(let d of a){if(l(d))u(d);else{if(t.if(jf.propertyInData(t,s,d,o.opts.ownProperties)),u(d),!o.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(d),e.ok(c)}function l(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};vz.default=IK});var Sz=H(function(xz){Object.defineProperty(xz,"__esModule",{value:!0});var Uf=Qr(),uo=Se(),Bf=ze(),qf=ze(),RK={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:s,it:o}=e,{opts:i}=o,a=Uf.allSchemaProperties(r),c=a.filter((h)=>Bf.alwaysValidSchema(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&s.properties,u=t.name("valid");if(o.props!==!0&&!(o.props instanceof uo.Name))o.props=qf.evaluatedPropsToName(t,o.props);let{props:d}=o;p();function p(){for(let h of a){if(l)f(h);if(o.allErrors)m(h);else t.var(u,!0),m(h),t.if(u)}}function f(h){for(let g in l)if(new RegExp(h).test(g))Bf.checkStrictMode(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,(g)=>{t.if(uo._`${Uf.usePattern(e,h)}.test(${g})`,()=>{let w=c.includes(h);if(!w)e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:qf.Type.Str},u);if(o.opts.unevaluated&&d!==!0)t.assign(uo._`${d}[${g}]`,!0);else if(!w&&!o.allErrors)t.if(uo.not(u),()=>t.break())})})}}};xz.default=RK});var Tz=H(function(kz){Object.defineProperty(kz,"__esModule",{value:!0});var $z=ze(),OK={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if($z.alwaysValidSchema(n,r)){e.fail();return}let s=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),e.failResult(s,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};kz.default=OK});var Iz=H(function(Ez){Object.defineProperty(Ez,"__esModule",{value:!0});var Pz=Qr(),MK={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Pz.validateUnion,error:{message:"must match a schema in anyOf"}};Ez.default=MK});var Cz=H(function(Rz){Object.defineProperty(Rz,"__esModule",{value:!0});var po=Se(),Az=ze(),LK={message:"must match exactly one schema in oneOf",params:({params:e})=>po._`{passingSchemas: ${e.passing}}`},DK={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:LK,code(e){let{gen:t,schema:r,parentSchema:n,it:s}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(i,()=>e.reset(),()=>e.error(!0));function l(){o.forEach((u,d)=>{let p;if(Az.alwaysValidSchema(s,u))t.var(c,!0);else p=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c);if(d>0)t.if(po._`${c} && ${i}`).assign(i,!1).assign(a,po._`[${a}, ${d}]`).else();t.if(c,()=>{if(t.assign(i,!0),t.assign(a,d),p)e.mergeEvaluated(p,po.Name)})})}}};Rz.default=DK});var Mz=H(function(zz){Object.defineProperty(zz,"__esModule",{value:!0});var Oz=ze(),UK={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let s=t.name("valid");r.forEach((o,i)=>{if(Oz.alwaysValidSchema(n,o))return;let a=e.subschema({keyword:"allOf",schemaProp:i},s);e.ok(s),e.mergeEvaluated(a)})}};zz.default=UK});var Dz=H(function(Lz){Object.defineProperty(Lz,"__esModule",{value:!0});var fo=Se(),Ff=ze(),qK={message:({params:e})=>fo.str`must match "${e.ifClause}" schema`,params:({params:e})=>fo._`{failingKeyword: ${e.ifClause}}`},FK={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qK,code(e){let{gen:t,parentSchema:r,it:n}=e;if(r.then===void 0&&r.else===void 0)Ff.checkStrictMode(n,'"if" without "then" and "else" is ignored');let s=Nz(n,"then"),o=Nz(n,"else");if(!s&&!o)return;let i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),s&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(a,l("then",u),l("else",u))}else if(s)t.if(a,l("then"));else t.if(fo.not(a),l("else"));e.pass(i,()=>e.error(!0));function c(){let u=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(u)}function l(u,d){return()=>{let p=e.subschema({keyword:u},a);if(t.assign(i,a),e.mergeValidEvaluated(p,i),d)t.assign(d,fo._`${u}`);else e.setParams({ifClause:u})}}}};function Nz(e,t){let r=e.schema[t];return r!==void 0&&!Ff.alwaysValidSchema(e,r)}Lz.default=FK});var Bz=H(function(Uz){Object.defineProperty(Uz,"__esModule",{value:!0});var jz=ze(),ZK={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)jz.checkStrictMode(r,`"${e}" without "if" is ignored`)}};Uz.default=ZK});var Fz=H(function(qz){Object.defineProperty(qz,"__esModule",{value:!0});var GK=o0(),KK=Y2(),WK=i0(),JK=sz(),QK=iz(),XK=fz(),YK=gz(),eW=a0(),tW=_z(),rW=Sz(),nW=Tz(),sW=Iz(),oW=Cz(),iW=Mz(),aW=Dz(),cW=Bz();function lW(e=!1){let t=[nW.default,sW.default,oW.default,iW.default,aW.default,cW.default,YK.default,eW.default,XK.default,tW.default,rW.default];if(e)t.push(KK.default,JK.default);else t.push(GK.default,WK.default);return t.push(QK.default),t}qz.default=lW});var Zz=H(function(Vz){Object.defineProperty(Vz,"__esModule",{value:!0});var _e=Se(),dW={message:({schemaCode:e})=>_e.str`must match format "${e}"`,params:({schemaCode:e})=>_e._`{format: ${e}}`},pW={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:dW,code(e,t){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;if(s)p();else f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",_e._`${m}[${i}]`),g=r.let("fType"),w=r.let("format");r.if(_e._`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,_e._`${h}.type || "string"`).assign(w,_e._`${h}.validate`),()=>r.assign(g,_e._`"string"`).assign(w,h)),e.fail$data(_e.or(v(),_()));function v(){if(c.strictSchema===!1)return _e.nil;return _e._`${i} && !${w}`}function _(){let C=u.$async?_e._`(${h}.async ? await ${w}(${n}) : ${w}(${n}))`:_e._`${w}(${n})`,k=_e._`(typeof ${w} == "function" ? ${C} : ${w}.test(${n}))`;return _e._`${w} && ${w} !== true && ${g} === ${t} && !${k}`}}function f(){let m=d.formats[o];if(!m){v();return}if(m===!0)return;let[h,g,w]=_(m);if(h===t)e.pass(C());function v(){if(c.strictSchema===!1){d.logger.warn(k());return}throw Error(k());function k(){return`unknown format "${o}" ignored in schema at path "${l}"`}}function _(k){let P=k instanceof RegExp?_e.regexpCode(k):c.code.formats?_e._`${c.code.formats}${_e.getProperty(o)}`:void 0,y=r.scopeValue("formats",{key:o,ref:k,code:P});if(typeof k=="object"&&!(k instanceof RegExp))return[k.type||"string",k.validate,_e._`${y}.validate`];return["string",k,y]}function C(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw Error("async format in sync schema");return _e._`await ${w}(${n})`}return typeof g=="function"?_e._`${w}(${n})`:_e._`${w}.test(${n})`}}}};Vz.default=pW});var Gz=H(function(Hz){Object.defineProperty(Hz,"__esModule",{value:!0});var mW=Zz(),hW=[mW.default];Hz.default=hW});var Jz=H(function(Kz){Object.defineProperty(Kz,"__esModule",{value:!0});Kz.contentVocabulary=Kz.metadataVocabulary=void 0;Kz.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Kz.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Xz=H(function(Qz){Object.defineProperty(Qz,"__esModule",{value:!0});var wW=l2(),bW=F2(),vW=Fz(),_W=Gz(),Vf=Jz(),xW=[wW.default,bW.default,(0,vW.default)(),_W.default,Vf.metadataVocabulary,Vf.contentVocabulary];Qz.default=xW});var rM=H(function(eM){Object.defineProperty(eM,"__esModule",{value:!0});eM.DiscrError=void 0;var Yz;(function(e){e.Tag="tag",e.Mapping="mapping"})(Yz||(eM.DiscrError=Yz={}))});var oM=H(function(sM){Object.defineProperty(sM,"__esModule",{value:!0});var Yr=Se(),Sa=rM(),Zf=Sf(),$W=Bl(),nM=ze(),kW={message:({params:{discrError:e,tagName:t}})=>e===Sa.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>Yr._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},TW={keyword:"discriminator",type:"object",schemaType:"object",error:kW,code(e){let{gen:t,data:r,schema:n,parentSchema:s,it:o}=e,{oneOf:i}=s;if(!o.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!i)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",Yr._`${r}${Yr.getProperty(a)}`);t.if(Yr._`typeof ${l} == "string"`,()=>u(),()=>e.error(!1,{discrError:Sa.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function u(){let f=p();t.if(!1);for(let m in f)t.elseIf(Yr._`${l} === ${m}`),t.assign(c,d(f[m]));t.else(),e.error(!1,{discrError:Sa.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function d(f){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:f},m);return e.mergeEvaluated(h,Yr.Name),m}function p(){var f;let m={},h=w(s),g=!0;for(let C=0;C<i.length;C++){let k=i[C];if((k===null||k===void 0?void 0:k.$ref)&&!nM.schemaHasRulesButRef(k,o.self.RULES)){let y=k.$ref;if(k=Zf.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,y),k instanceof Zf.SchemaEnv)k=k.schema;if(k===void 0)throw new $W.default(o.opts.uriResolver,o.baseId,y)}let P=(f=k===null||k===void 0?void 0:k.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||w(k)),v(P,C)}if(!g)throw Error(`discriminator: "${a}" must be required`);return m;function w({required:C}){return Array.isArray(C)&&C.includes(a)}function v(C,k){if(C.const)_(C.const,k);else if(C.enum)for(let P of C.enum)_(P,k);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(C,k){if(typeof C!="string"||C in m)throw Error(`discriminator: "${a}" values must be unique strings`);m[C]=k}}}};sM.default=TW});var iM=H(function(bye,EW){EW.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var l0=H(function(Er,c0){Object.defineProperty(Er,"__esModule",{value:!0});Er.MissingRefError=Er.ValidationError=Er.CodeGen=Er.Name=Er.nil=Er.stringify=Er.str=Er._=Er.KeywordCxt=Er.Ajv=void 0;var IW=t2(),AW=Xz(),RW=oM(),aM=iM(),CW=["/properties"],Hf="http://json-schema.org/draft-07/schema";class Zl extends IW.default{_addVocabularies(){if(super._addVocabularies(),AW.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(RW.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(aM,CW):aM;this.addMetaSchema(e,Hf,!1),this.refs["http://json-schema.org/schema"]=Hf}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Hf)?Hf:void 0)}}Er.Ajv=Zl;c0.exports=Er=Zl;c0.exports.Ajv=Zl;Object.defineProperty(Er,"__esModule",{value:!0});Er.default=Zl;var OW=Ul();Object.defineProperty(Er,"KeywordCxt",{enumerable:!0,get:function(){return OW.KeywordCxt}});var $a=Se();Object.defineProperty(Er,"_",{enumerable:!0,get:function(){return $a._}});Object.defineProperty(Er,"str",{enumerable:!0,get:function(){return $a.str}});Object.defineProperty(Er,"stringify",{enumerable:!0,get:function(){return $a.stringify}});Object.defineProperty(Er,"nil",{enumerable:!0,get:function(){return $a.nil}});Object.defineProperty(Er,"Name",{enumerable:!0,get:function(){return $a.Name}});Object.defineProperty(Er,"CodeGen",{enumerable:!0,get:function(){return $a.CodeGen}});var zW=vf();Object.defineProperty(Er,"ValidationError",{enumerable:!0,get:function(){return zW.default}});var MW=Bl();Object.defineProperty(Er,"MissingRefError",{enumerable:!0,get:function(){return MW.default}})});var yM=H(function(hM){Object.defineProperty(hM,"__esModule",{value:!0});hM.formatNames=hM.fastFormats=hM.fullFormats=void 0;function Zn(e,t){return{validate:e,compare:t}}hM.fullFormats={date:Zn(dM,f0),time:Zn(d0(!0),m0),"date-time":Zn(cM(!0),fM),"iso-time":Zn(d0(),pM),"iso-date-time":Zn(cM(),mM),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:FW,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:JW,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:VW,int32:{type:"number",validate:GW},int64:{type:"number",validate:KW},float:{type:"number",validate:uM},double:{type:"number",validate:uM},password:!0,binary:!0};hM.fastFormats={...hM.fullFormats,date:Zn(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,f0),time:Zn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,m0),"date-time":Zn(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,fM),"iso-time":Zn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,pM),"iso-date-time":Zn(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mM),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};hM.formatNames=Object.keys(hM.fullFormats);function DW(e){return e%4===0&&(e%100!==0||e%400===0)}var jW=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,UW=[0,31,28,31,30,31,30,31,31,30,31,30,31];function dM(e){let t=jW.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],s=+t[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&DW(r)?29:UW[n])}function f0(e,t){if(!(e&&t))return;if(e>t)return 1;if(e<t)return-1;return 0}var u0=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function d0(e){return function(r){let n=u0.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let d=o-u*c,p=s-l*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function m0(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(!(r&&n))return;return r-n}function pM(e,t){if(!(e&&t))return;let r=u0.exec(e),n=u0.exec(t);if(!(r&&n))return;if(e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t)return 1;if(e<t)return-1;return 0}var p0=/t|\s/i;function cM(e){let t=d0(e);return function(n){let s=n.split(p0);return s.length===2&&dM(s[0])&&t(s[1])}}function fM(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(!(r&&n))return;return r-n}function mM(e,t){if(!(e&&t))return;let[r,n]=e.split(p0),[s,o]=t.split(p0),i=f0(r,s);if(i===void 0)return;return i||m0(n,o)}var BW=/\/|:/,qW=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function FW(e){return BW.test(e)&&qW.test(e)}var lM=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function VW(e){return lM.lastIndex=0,lM.test(e)}var ZW=-2147483648,HW=2147483647;function GW(e){return Number.isInteger(e)&&e<=HW&&e>=ZW}function KW(e){return Number.isInteger(e)}function uM(){return!0}var WW=/[^\\]\\Z/;function JW(e){if(WW.test(e))return!1;try{return new RegExp(e),!0}catch(t){return!1}}});var vM=H(function(bM){Object.defineProperty(bM,"__esModule",{value:!0});bM.formatLimitDefinition=void 0;var wM=l0(),wt=Se(),mo=wt.operators,Gf={formatMaximum:{okStr:"<=",ok:mo.LTE,fail:mo.GT},formatMinimum:{okStr:">=",ok:mo.GTE,fail:mo.LT},formatExclusiveMaximum:{okStr:"<",ok:mo.LT,fail:mo.GTE},formatExclusiveMinimum:{okStr:">",ok:mo.GT,fail:mo.LTE}},XW={message:({keyword:e,schemaCode:t})=>wt.str`should be ${Gf[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>wt._`{comparison: ${Gf[e].okStr}, limit: ${t}}`};bM.formatLimitDefinition={keyword:Object.keys(Gf),type:"string",schemaType:"string",$data:!0,error:XW,code(e){let{gen:t,data:r,schemaCode:n,keyword:s,it:o}=e,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new wM.KeywordCxt(o,a.RULES.all.format.definition,"format");if(c.$data)l();else u();function l(){let p=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=t.const("fmt",wt._`${p}[${c.schemaCode}]`);e.fail$data(wt.or(wt._`typeof ${f} != "object"`,wt._`${f} instanceof RegExp`,wt._`typeof ${f}.compare != "function"`,d(f)))}function u(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw Error(`"${s}": format "${p}" does not define "compare" function`);let m=t.scopeValue("formats",{key:p,ref:f,code:i.code.formats?wt._`${i.code.formats}${wt.getProperty(p)}`:void 0});e.fail$data(d(m))}function d(p){return wt._`${p}.compare(${r}, ${n}) ${Gf[s].fail} 0`}},dependencies:["format"]};var YW=(e)=>(e.addKeyword(bM.formatLimitDefinition),e);bM.default=YW});var $M=H(function(Hl,SM){Object.defineProperty(Hl,"__esModule",{value:!0});var en=yM(),tJ=vM(),ka=Se(),_M=new ka.Name("fullFormats"),rJ=new ka.Name("fastFormats"),y0=(e,t={keywords:!0})=>{if(Array.isArray(t))return xM(e,t,en.fullFormats,_M),e;let[r,n]=t.mode==="fast"?[en.fastFormats,rJ]:[en.fullFormats,_M],s=t.formats||en.formatNames;if(xM(e,s,r,n),t.keywords)(0,tJ.default)(e);return e};y0.get=(e,t="full")=>{let n=(t==="fast"?en.fastFormats:en.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function xM(e,t,r,n){var s,o;(s=(o=e.opts.code).formats)!==null&&s!==void 0||(o.formats=ka._`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}SM.exports=Hl=y0;Object.defineProperty(Hl,"__esModule",{value:!0});Hl.default=y0});function nJ(){let e=new kM.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return TM.default(e),e}class w0{constructor(e){this._ajv=e??nJ()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}var kM,TM;var PM=b(()=>{kM=rS(l0(),1),TM=rS($M(),1)});class b0{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.content],o=s.some((l)=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some((l)=>l.type==="tool_use");if(o){if(s.some((l)=>l.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter((d)=>d.type==="tool_use").map((d)=>d.id)),u=new Set(s.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(l.size!==u.size||![...l].every((d)=>u.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},dl,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let s=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Ji,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}var EM=b(()=>{Bo()});function IM(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function AM(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var v0;var RM=b(()=>{pR();Bo();PM();Cl();EM();v0=class v0 extends v_{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ul.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let s=this._loggingLevels.get(n);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new w0,this.setRequestHandler(up,(r)=>this._oninitialize(r)),this.setNotificationHandler(hv,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(xv,async(r,n)=>{let s=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=r.params,i=ul.safeParse(o);if(i.success)this._loggingLevels.set(s,i.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new b0(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=dR(this._capabilities,e)}setRequestHandler(e,t){let n=Gs(e)?.method;if(!n)throw Error("Schema is missing a method literal");let s=oa(n);if(typeof s!=="string")throw Error("Schema method literal must be a string");if(s==="tools/call"){let i=async(a,c)=>{let l=Hs(Wi,a);if(!l.success){let f=l.error instanceof Error?l.error.message:String(l.error);throw new te(ne.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:u}=l.data,d=await Promise.resolve(t(a,c));if(u.task){let f=Hs(Gi,d);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new te(ne.InvalidParams,`Invalid task creation result: ${m}`)}return f.data}let p=Hs(kp,d);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new te(ne.InvalidParams,`Invalid tools/call result: ${f}`)}return p.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){AM(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;IM(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Zi.includes(t)?t:uv,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},cp)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],s=n.some((c)=>c.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=o?Array.isArray(o.content)?o.content:[o.content]:[],a=i.some((c)=>c.type==="tool_use");if(s){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(i.filter((u)=>u.type==="tool_use").map((u)=>u.id)),l=new Set(n.filter((u)=>u.type==="tool_result").map((u)=>u.toolUseId));if(c.size!==l.size||![...c].every((u)=>l.has(u)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},Sv,t);return this.request({method:"sampling/createMessage",params:e},dl,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},Ji,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:n},Ji,t);if(s.action==="accept"&&s.content&&n.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(n.requestedSchema)(s.content);if(!i.valid)throw new te(ne.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(o){if(o instanceof te)throw o;throw new te(ne.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return s}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},$v,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function _0(e){return!!e&&typeof e==="object"&&OM in e}function zM(e){return e[OM]?.complete}var OM,CM;var MM=b(()=>{OM=Symbol.for("mcp.completable");(function(e){e.Completable="McpCompletable"})(CM||(CM={}))});function oJ(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!sJ.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function iJ(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function x0(e){let t=oJ(e);return iJ(e,t.warnings),t.isValid}var sJ;var NM=b(()=>{sJ=/^[A-Za-z0-9._-]{1,128}$/});class S0{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}function aJ(e,t){let r=0,n=[e];while(n.length>0){let s=n.pop();if(s===null||typeof s!=="object")continue;if(Array.isArray(s))for(let o of s){if(++r>t)return r;if(o!==null&&typeof o==="object")n.push(o)}else for(let o in s){if(!Object.prototype.hasOwnProperty.call(s,o))continue;if(++r>t)return r;let i=s[o];if(i!==null&&typeof i==="object")n.push(i)}}return r}function cJ(e){if(e===void 0||e===1/0)return;if(typeof e!=="number"||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}class k0{constructor(e,t){if(this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new v0(e,t),this._maxToolInputElements=cJ(t?.maxToolInputElements),t?.capabilities?.tools)this.setToolRequestHandlers();if(t?.capabilities?.resources)this.setResourceRequestHandlers();if(t?.capabilities?.prompts)this.setPromptRequestHandlers()}get experimental(){if(!this._experimental)this._experimental={tasks:new S0(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(ho($p)),this.server.assertCanSetRequestHandler(ho(Wi)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler($p,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=sa(t.inputSchema);return n?g_(n,{strictUnions:!0,pipeStrategy:"input"}):lJ})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=sa(t.outputSchema);if(n)r.outputSchema=g_(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Wi,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new te(ne.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new te(ne.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,s=r.execution?.taskSupport,o="createTask"in r.handler;if((s==="required"||s==="optional")&&!o)throw new te(ne.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!n)throw new te(ne.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!n&&o)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,i,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof te){if(r.code===ne.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&aJ(t,this._maxToolInputElements)>this._maxToolInputElements)throw new te(ne.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let s=sa(e.inputSchema)??e.inputSchema,o=await Hp(s,t??{});if(!o.success){let i="error"in o?o.error:"Unknown error",a=Gp(i);throw new te(ne.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return o.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new te(ne.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=sa(e.outputSchema),s=await Hp(n,t.structuredContent);if(!s.success){let o="error"in s?s.error:"Unknown error",i=Gp(o);throw new te(ne.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let o={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,o));else return await Promise.resolve(n.createTask(o))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),s=e.handler,o={...r,taskStore:r.taskStore},i=n?await Promise.resolve(s.createTask(n,o)):await Promise.resolve(s.createTask(o)),a=i.task.taskId,c=i.task,l=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((d)=>setTimeout(d,l));let u=await r.taskStore.getTask(a);if(!u)throw new te(ne.InternalError,`Task ${a} not found during polling`);c=u}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(ho(Tp)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Tp,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return YI(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return eA(e),this.handleResourceCompletion(e,e.params.ref);default:throw new te(ne.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new te(ne.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new te(ne.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return Gl;let s=Gs(r.argsSchema)?.[e.params.argument.name];if(!_0(s))return Gl;let o=zM(s);if(!o)return Gl;let i=await o(e.params.argument.value,e.params.context);return DM(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((o)=>o.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return Gl;throw new te(ne.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Gl;let s=await n(e.params.argument.value,e.params.context);return DM(s)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(ho(bp)),this.server.assertCanSetRequestHandler(ho(vp)),this.server.assertCanSetRequestHandler(ho(_p)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(bp,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([s,o])=>o.enabled).map(([s,o])=>({uri:s,name:o.name,...o.metadata})),n=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let o=await s.resourceTemplate.listCallback(t);for(let i of o.resources)n.push({...s.metadata,...i})}return{resources:[...r,...n]}}),this.server.setRequestHandler(vp,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(_p,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new te(ne.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let s of Object.values(this._registeredResourceTemplates)){let o=s.resourceTemplate.uriTemplate.match(r.toString());if(o)return s.readCallback(r,o,t)}throw new te(ne.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(ho(xp)),this.server.assertCanSetRequestHandler(ho(Sp)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xp,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?uJ(t.argsSchema):void 0}))})),this.server.setRequestHandler(Sp,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new te(ne.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new te(ne.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=sa(r.argsSchema),s=await Hp(n,e.params.arguments??{});if(!s.success){let a="error"in s?s.error:"Unknown error",c=Gp(a);throw new te(ne.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let o=s.data,i=r.callback;return await Promise.resolve(i(o,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let s=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,void 0,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,void 0,t,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,t,r,n,s){let o={name:e,title:t,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:(i)=>{if(typeof i.uri<"u"&&i.uri!==r){if(delete this._registeredResources[r],i.uri)this._registeredResources[i.uri]=o}if(typeof i.name<"u")o.name=i.name;if(typeof i.title<"u")o.title=i.title;if(typeof i.metadata<"u")o.metadata=i.metadata;if(typeof i.callback<"u")o.readCallback=i.callback;if(typeof i.enabled<"u")o.enabled=i.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=o,o}_createRegisteredResourceTemplate(e,t,r,n,s){let o={resourceTemplate:r,title:t,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=o}if(typeof c.title<"u")o.title=c.title;if(typeof c.template<"u")o.resourceTemplate=c.template;if(typeof c.metadata<"u")o.metadata=c.metadata;if(typeof c.callback<"u")o.readCallback=c.callback;if(typeof c.enabled<"u")o.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let i=r.uriTemplate.variableNames;if(Array.isArray(i)&&i.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return o}_createRegisteredPrompt(e,t,r,n,s){let o={title:t,description:r,argsSchema:n===void 0?void 0:Go(n),callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:(i)=>{if(typeof i.name<"u"&&i.name!==e){if(delete this._registeredPrompts[e],i.name)this._registeredPrompts[i.name]=o}if(typeof i.title<"u")o.title=i.title;if(typeof i.description<"u")o.description=i.description;if(typeof i.argsSchema<"u")o.argsSchema=Go(i.argsSchema);if(typeof i.callback<"u")o.callback=i.callback;if(typeof i.enabled<"u")o.enabled=i.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=o,n){if(Object.values(n).some((a)=>{let c=a instanceof Ju?a._def?.innerType:a;return _0(c)}))this.setCompletionRequestHandler()}return o}_createRegisteredTool(e,t,r,n,s,o,i,a,c){x0(e);let l={title:t,description:r,inputSchema:LM(n),outputSchema:LM(s),annotations:o,execution:i,_meta:a,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:(u)=>{if(typeof u.name<"u"&&u.name!==e){if(typeof u.name==="string")x0(u.name);if(delete this._registeredTools[e],u.name)this._registeredTools[u.name]=l}if(typeof u.title<"u")l.title=u.title;if(typeof u.description<"u")l.description=u.description;if(typeof u.paramsSchema<"u")l.inputSchema=Go(u.paramsSchema);if(typeof u.outputSchema<"u")l.outputSchema=Go(u.outputSchema);if(typeof u.callback<"u")l.handler=u.callback;if(typeof u.annotations<"u")l.annotations=u.annotations;if(typeof u._meta<"u")l._meta=u._meta;if(typeof u.enabled<"u")l.enabled=u.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,s,o;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if($0(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!$0(t[0]))o=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);o=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,n,s,o,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:s,inputSchema:o,outputSchema:i,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,s,o,i,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let s=t[0],o=this._createRegisteredPrompt(e,void 0,r,n,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:s,argsSchema:o}=t,i=this._createRegisteredPrompt(e,n,s,o,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}function jM(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function UM(e){return"_def"in e||"_zod"in e||jM(e)}function $0(e){if(typeof e!=="object"||e===null)return!1;if(UM(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(jM)}function LM(e){if(!e)return;if($0(e))return Go(e);if(!UM(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function uJ(e){let t=Gs(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let s=EA(n),o=IA(n);return{name:r,description:s,required:!o}})}function ho(e){let r=Gs(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=oa(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function DM(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var lJ,Gl;var BM=b(()=>{RM();Cl();b_();Bo();MM();NM();vc();lJ={type:"object",properties:{}};Gl={completion:{values:[],hasMore:!1}}});function dJ(e){return{content:[{type:"text",text:e.text},...e.images.map((t)=>({type:"image",...t}))],...e.isError&&{isError:!0}}}function Kl(e,t){let r=new k0({name:"hatchlight",version:t.version??MI},{instructions:Ap}),n=Cp(e,{allowPaid:t.allowPaid,spend:new hl(t.spendLimitUsd),files:t.files??!0,waitMs:t.waitMs,pollMs:t.pollMs});for(let s of n)r.registerTool(s.name,{title:s.title,description:s.description,inputSchema:s.input,...s.readOnly&&{annotations:{readOnlyHint:!0}}},async(o,i)=>{let a=0,c=i._meta?.progressToken,l=await s.run(o,{signal:i.signal,async progress(u){if(c==null)return;a++,await i.sendNotification({method:"notifications/progress",params:{progressToken:c,progress:a,message:u}})}});return dJ(l)});return r}var Kf=b(()=>{Pt();Fo();BM();Fo()});function mJ(e){if(!e)throw TypeError("argument string is required");var t=typeof e==="object"?hJ(e):e;if(typeof t!=="string")throw TypeError("argument string is required to be a string");var r=t.indexOf(";"),n=r!==-1?t.slice(0,r).trim():t.trim();if(!fJ.test(n))throw TypeError("invalid media type");var s=new gJ(n.toLowerCase());if(r!==-1){var o,i,a;qM.lastIndex=r;while(i=qM.exec(t)){if(i.index!==r)throw TypeError("invalid parameter format");if(r+=i[0].length,o=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34){if(a=a.slice(1,-1),a.indexOf("\\")!==-1)a=a.replace(pJ,"$1")}s.parameters[o]=a}if(r!==t.length)throw TypeError("invalid parameter format")}return s}function hJ(e){var t;if(typeof e.getHeader==="function")t=e.getHeader("content-type");else if(typeof e.headers==="object")t=e.headers&&e.headers["content-type"];if(typeof t!=="string")throw TypeError("content-type header is missing from object");return t}function gJ(e){this.parameters=Object.create(null),this.type=e}var qM,pJ,fJ,FM;var VM=b(()=>{/*!
|
|
114
|
+
* content-type
|
|
115
|
+
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
116
|
+
* MIT Licensed
|
|
117
|
+
*/qM=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,pJ=/\\([\u000b\u0020-\u00ff])/g,fJ=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;FM=mJ});function wJ(e){if(!e)return;try{return FM(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();if(t===""||e.slice(t.length).includes(","))return;return t}}function ZM(e){if(e==="application/json")return!0;return wJ(e)==="application/json"}var HM=b(()=>{VM()});function GM(e){return`Payload Too Large: Request body must not exceed ${e} bytes`}function KM(e){if(e===void 0)return 4194304;if(typeof e!=="number"||!Number.isFinite(e)||e<=0)throw RangeError(`maxRequestBodySize must be a positive number of bytes, got ${String(e)}`);return e}async function WM(e,t=4194304){if(Number(e.headers.get("content-length"))>t)return{tooLarge:!0};if(e.body===null)return{tooLarge:!1,text:""};let r=e.body.getReader(),n=new TextDecoder,s=0,o="";try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(s+=a.byteLength,s>t)return{tooLarge:!0};o+=n.decode(a,{stream:!0})}}finally{r.releaseLock()}return{tooLarge:!1,text:o+n.decode()}}var Wf=100;function QM(e,t){if(!Number.isFinite(e)||e<1)return;let r=setInterval(t,Math.min(e,2147483647));return r.unref?.(),r}var JM=15000;class T0{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._resumableStreams=new Set,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this._closed=!1,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._keepAliveMs=e.keepAliveMs??JM,this._maxRequestBodySize=KM(e.maxRequestBodySize)}startKeepAlive(e,t){if(this._closed)return;let r=QM(this._keepAliveMs,()=>{try{e.enqueue(t.encode(`: keepalive
|
|
118
|
+
|
|
119
|
+
`))}catch{if(r!==void 0)clearInterval(r)}});return r}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(e,t,r,n){let s={code:t,message:r};if(n?.data!==void 0)s.data=n.data;return new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...n?.headers}})}validateRequestHeaders(e){if(!this._enableDnsRebindingProtection)return;if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get("host");if(!t||!this._allowedHosts.includes(t)){let r=`Invalid Host header: ${t}`;return this.onerror?.(Error(r)),this.createJsonErrorResponse(403,-32000,r)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get("origin");if(t&&!this._allowedOrigins.includes(t)){let r=`Invalid Origin header: ${t}`;return this.onerror?.(Error(r)),this.createJsonErrorResponse(403,-32000,r)}}return}async handleRequest(e,t){if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let r=this.validateRequestHeaders(e);if(r)return r;switch(e.method){case"POST":return this.handlePostRequest(e,t);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,r,n){if(!this._eventStore)return;if(n<"2025-11-25")return;let s=await this._eventStore.storeEvent(r,{}),o=`id: ${s}
|
|
120
|
+
data:
|
|
121
|
+
|
|
122
|
+
`;if(this._retryInterval!==void 0)o=`id: ${s}
|
|
123
|
+
retry: ${this._retryInterval}
|
|
124
|
+
data:
|
|
125
|
+
|
|
126
|
+
`;e.enqueue(t.encode(o)),this._resumableStreams.add(r)}async handleGetRequest(e){if(!e.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept text/event-stream");let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let l=e.headers.get("last-event-id");if(l)return this.replayEvents(l)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32000,"Conflict: Only one SSE stream is allowed per session");let s=new TextEncoder,o,i=void 0,a=new ReadableStream({start:(l)=>{o=l},cancel:()=>{if(i!==void 0)clearInterval(i);if(this._streamMapping.get(this._standaloneSseStreamId)?.controller===o)this._streamMapping.delete(this._standaloneSseStreamId)}}),c={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};if(this.sessionId!==void 0)c["mcp-session-id"]=this.sessionId;return this._streamMapping.set(this._standaloneSseStreamId,{controller:o,encoder:s,cleanup:()=>{if(i!==void 0)clearInterval(i);this._streamMapping.delete(this._standaloneSseStreamId);try{o.close()}catch{}}}),i=this.startKeepAlive(o,s),new Response(a,{headers:c})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error("Event store not configured")),this.createJsonErrorResponse(400,-32000,"Event store not configured");try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32000,"Invalid event ID format");if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32000,"Conflict: Stream already has an active connection")}let r={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};if(this.sessionId!==void 0)r["mcp-session-id"]=this.sessionId;let n=new TextEncoder,s,o=void 0,i=void 0,a=!1,c=new ReadableStream({start:(u)=>{s=u},cancel:()=>{if(a=!0,o!==void 0)clearInterval(o);if(i!==void 0&&this._streamMapping.get(i)?.controller===s)this._streamMapping.delete(i)}}),l=new Set;if(i=await this._eventStore.replayEventsAfter(e,{send:async(u,d)=>{if(!this.writeSSEEvent(s,n,d,u)){this.onerror?.(Error("Failed replay events"));try{s.close()}catch{}}else l.add(u)}}),this._closed||a){try{s.close()}catch{}return this.createJsonErrorResponse(404,-32001,"Session not found")}return this._streamMapping.get(i)?.cleanup(),this._streamMapping.set(i,{controller:s,encoder:n,replayedEventIds:l,cleanup:()=>{if(o!==void 0)clearInterval(o);this._streamMapping.delete(i);try{s.close()}catch{}}}),this._resumableStreams.add(i),o=this.startKeepAlive(s,n),new Response(c,{headers:r})}catch(t){return this.onerror?.(t),this.createJsonErrorResponse(500,-32000,"Error replaying events")}}writeSSEEvent(e,t,r,n){try{let s=`event: message
|
|
127
|
+
`;if(n)s+=`id: ${n}
|
|
128
|
+
`;return s+=`data: ${JSON.stringify(r)}
|
|
129
|
+
|
|
130
|
+
`,e.enqueue(t.encode(s)),!0}catch(s){return this.onerror?.(s),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,t){try{let r=e.headers.get("accept");if(!r?.includes("application/json")||!r.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let n=e.headers.get("content-type");if(!ZM(n))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},o;if(t?.parsedBody!==void 0)o=t.parsedBody;else try{let w=await WM(e,this._maxRequestBodySize);if(w.tooLarge){let v=GM(this._maxRequestBodySize);return this.onerror?.(Error(v)),this.createJsonErrorResponse(413,-32000,v)}o=JSON.parse(w.text)}catch{return this.onerror?.(Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}if(Array.isArray(o)&&o.length>Wf)return this.onerror?.(Error(`Invalid Request: Batch must not exceed ${Wf} messages`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Batch must not exceed ${Wf} messages`);let i;try{if(Array.isArray(o))i=o.map((w)=>nl.parse(w));else i=[nl.parse(o)]}catch{return this.onerror?.(Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");let a=i.some(mv);if(a){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(i.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!a){let w=this.validateSession(e);if(w)return w;let v=this.validateProtocolVersion(e);if(v)return v}if(this._closed)return this.createJsonErrorResponse(404,-32001,"Session not found");if(!i.some(os)){for(let w of i)this.onmessage?.(w,{authInfo:t?.authInfo,requestInfo:s});return new Response(null,{status:202})}let l=crypto.randomUUID(),u=i.find((w)=>mv(w)),d=u?u.params.protocolVersion:e.headers.get("mcp-protocol-version")??jI;if(this._enableJsonResponse)return new Promise((w)=>{this._streamMapping.set(l,{resolveJson:w,cleanup:()=>{this._streamMapping.delete(l)}});for(let v of i)if(os(v))this._requestToStreamMapping.set(v.id,l);for(let v of i)this.onmessage?.(v,{authInfo:t?.authInfo,requestInfo:s})});let p=new TextEncoder,f,m=void 0,h=new ReadableStream({start:(w)=>{f=w},cancel:()=>{if(m!==void 0)clearInterval(m);if(this._streamMapping.get(l)?.controller===f)this._streamMapping.delete(l)}}),g={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"};if(this.sessionId!==void 0)g["mcp-session-id"]=this.sessionId;for(let w of i)if(os(w))this._streamMapping.set(l,{controller:f,encoder:p,cleanup:()=>{if(m!==void 0)clearInterval(m);this._streamMapping.delete(l);try{f.close()}catch{}}}),this._requestToStreamMapping.set(w.id,l);try{await this.writePrimingEvent(f,p,l,d);for(let w of i){let v,_;if(os(w)&&this._eventStore&&d>="2025-11-25")v=()=>{this.closeSSEStream(w.id)},_=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(w,{authInfo:t?.authInfo,requestInfo:s,closeSSEStream:v,closeStandaloneSSEStream:_})}}catch(w){this._streamMapping.get(l)?.cleanup(),this._resumableStreams.delete(l);for(let v of i)if(os(v))this._requestToStreamMapping.delete(v.id);throw w}if(this._streamMapping.get(l)?.controller===f)m=this.startKeepAlive(f,p);return new Response(h,{status:200,headers:g})}catch(r){return this.onerror?.(r),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(r)})}}async handleDeleteRequest(e){let t=this.validateSession(e);if(t)return t;let r=this.validateProtocolVersion(e);if(r)return r;try{return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),new Response(null,{status:200})}finally{await this.close()}}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let t=e.headers.get("mcp-session-id");if(!t)return this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(t!==this.sessionId)return this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(e){let t=e.headers.get("mcp-protocol-version");if(t!==null&&!Zi.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${Zi.join(", ")})`)),this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${Zi.join(", ")})`);return}async close(){if(this._closed)return;this._closed=!0,this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this._resumableStreams.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let r=this._streamMapping.get(t);if(r)r.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);if(e)e.cleanup()}async send(e,t){let r=t?.relatedRequestId;if(is(e)||Hi(e))r=e.id;if(r===void 0){if(is(e)||Hi(e))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let o;if(this._eventStore)o=await this._eventStore.storeEvent(this._standaloneSseStreamId,e);let i=this._streamMapping.get(this._standaloneSseStreamId);if(i===void 0)return;if(i.controller&&i.encoder&&(o===void 0||!i.replayedEventIds?.has(o)))this.writeSSEEvent(i.controller,i.encoder,e,o);return}let n=this._requestToStreamMapping.get(r);if(!n)throw Error(`No connection established for request ID: ${String(r)}`);let s=this._streamMapping.get(n);if(!this._enableJsonResponse){let o;if(this._eventStore)o=await this._eventStore.storeEvent(n,e),s=this._streamMapping.get(n);if(s?.controller&&s?.encoder&&(o===void 0||!s.replayedEventIds?.has(o))){if(this.writeSSEEvent(s.controller,s.encoder,e,o)&&o!==void 0)this._resumableStreams.add(n)}}if(is(e)||Hi(e)){this._requestResponseMap.set(r,e);let o=Array.from(this._requestToStreamMapping.entries()).filter(([a,c])=>c===n).map(([a])=>a);if(o.every((a)=>this._requestResponseMap.has(a))){if(!s){if(this._closed){for(let a of o)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);return}if(!this._enableJsonResponse&&this._eventStore&&this._resumableStreams.has(n)){for(let a of o)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);this._resumableStreams.delete(n);return}for(let a of o)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);throw Error(`No connection established for request ID: ${String(r)}`)}if(this._enableJsonResponse&&s.resolveJson){let a={"Content-Type":"application/json"};if(this.sessionId!==void 0)a["mcp-session-id"]=this.sessionId;let c=o.map((l)=>this._requestResponseMap.get(l));if(c.length===1)s.resolveJson(new Response(JSON.stringify(c[0]),{status:200,headers:a}));else s.resolveJson(new Response(JSON.stringify(c),{status:200,headers:a}))}else s.cleanup();for(let a of o)this._requestResponseMap.delete(a),this._requestToStreamMapping.delete(a);this._resumableStreams.delete(n)}}}}var XM=b(()=>{HM();Bo()});function P0(e){return async(t,r,n)=>{let s=new cs(r.origin,(a,c)=>{let l=new Headers(c?.headers);return l.set("authorization",`Bearer ${r.token}`),e.fetch(new Request(a,{...c,headers:l}))}),o=Kl(s,{allowPaid:r.allowPaid,spendLimitUsd:null,files:!1,version:e.version}),i=new T0({sessionIdGenerator:void 0,enableJsonResponse:!0,maxRequestBodySize:e.maxBodyBytes});await o.connect(i);try{return await i.handleRequest(t,{parsedBody:n})}finally{await o.close()}}}var YM=b(()=>{XM();Pp();Kf()});async function eN(e){let{url:t}=await fl(e.dataDir,e.launcher,e.serverArgs);await rN(new cs(t),e)}function vJ(e,t=!1){let r;try{r=new URL(e)}catch{throw Error(`Not a URL: ${e}`)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw Error(`Not an http or https URL: ${e}`);if(r.protocol==="http:"&&!bJ.test(r.hostname)&&!t)throw Error(`${r.origin} is plain http, so the token would cross the network readable. Use https, or pass --insecure if you accept that.`);return r.origin}function _J(e,t){return new cs(e,(r,n)=>{let s=new Headers(n?.headers);return s.set("authorization",`Bearer ${t}`),globalThis.fetch(r,{...n,headers:s})})}async function tN(e){let t=vJ(e.url,e.insecure),r=_J(t,e.token);await xJ(r),await rN(r,e)}async function xJ(e){try{await e.models()}catch(t){if(t instanceof as&&t.status===401)throw Error(`${e.baseUrl} refused the token: it may be mistyped, revoked or expired. Make a new one in Settings > Use with AI agents.`);if(t instanceof as&&t.code==="tokenScope")throw Error(`The token cannot list models: give it the read permission. (${t.message})`);throw t}}async function rN(e,t){let r=Kl(e,t),n=new Promise((s)=>{r.server.onclose=s,process.stdin.once("end",s),process.stdin.once("close",s)});await r.connect(new Tv),await n}var bJ;var Wl=b(()=>{oA();Pp();Pv();Kf();Pp();Pv();YM();Kf();bJ=/^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i});function nN(e,t){return $J[`${e.toUpperCase()} ${t}`]??null}function sN(e,t){return SJ[`${e.toUpperCase()} ${t}`]??"owner"}var SJ,$J;var E0=b(()=>{SJ={"GET /api/health":"public","GET /api/server":"public","GET /api/setup":"public","POST /api/setup":"public","POST /api/login":"public","GET /api/invites/:token":"public","POST /api/invites/:token/accept":"public","GET /api/password-resets/:token":"public","POST /api/password-resets/:token":"public","POST /api/logout":"account","GET /api/account":"account","DELETE /api/account/reset-notice":"account","PUT /api/account/keys/:id":"account","GET /api/keys/lost":"account","DELETE /api/keys/lost":"account","DELETE /api/account/keys/:id":"account","PUT /api/account/password":"account","GET /api/account/sessions":"account","DELETE /api/account/sessions":"account","DELETE /api/account/sessions/:id":"account","POST /api/account/totp":"account","PUT /api/account/totp":"account","DELETE /api/account/totp":"account","GET /api/account/tokens":"account","POST /api/account/tokens":"account","DELETE /api/account/tokens/:id":"account","GET /api/models":"member","GET /api/providers":"member","GET /api/sessions":"member","GET /api/sessions/:id":"member","DELETE /api/sessions/:id":"member","POST /api/turns":"member","GET /api/jobs/:id/preview":"member","POST /api/jobs/:id/cancel":"member","POST /api/jobs/:id/retry":"member","POST /api/assets":"member","GET /api/assets/:id":"member","DELETE /api/assets/:id":"member","GET /api/gallery":"member","POST /api/prompts/improve":"member","GET /api/assistant":"member","POST /api/assistant/messages":"member","GET /api/sessions/:id/assistant":"member","POST /api/sessions/:id/assistant/stop":"member","POST /api/sessions/:id/assistant/answers":"member","GET /api/events":"member","GET /api/settings":"member","PUT /api/settings":"member","GET /api/local-models":"member","GET /api/local-models/:id/demos/:index":"member","GET /api/loras":"member","GET /api/checkpoints":"member","GET /api/trainer":"member","GET /api/captioner":"member","POST /api/loras":"train","POST /api/trainings":"train","POST /api/trainings/cancel":"train","POST /api/trainings/finish":"train","GET /api/trainings/:id/samples/:step":"train","POST /api/captions":"train","POST /api/local-models/:id/install":"admin","POST /api/local-models/:id/cancel":"admin","DELETE /api/local-models/:id":"admin","DELETE /api/loras/:id":"admin","POST /api/checkpoints":"admin","PATCH /api/checkpoints/:id":"admin","DELETE /api/checkpoints/:id":"admin","GET /api/users":"admin","PATCH /api/users/:id":"admin","POST /api/users/:id/password":"admin","GET /api/users/:id/tokens":"admin","DELETE /api/users/:id/tokens/:token":"admin","GET /api/invites":"admin","POST /api/invites":"admin","DELETE /api/invites/:id":"admin","PUT /api/providers/:id/key":"owner","DELETE /api/providers/:id/key":"owner","GET /api/agents":"owner","PUT /api/agents/claude-desktop":"owner","DELETE /api/agents/claude-desktop":"owner","POST /api/local-models/location":"owner","POST /api/trainer/install":"owner","POST /api/trainer/install/cancel":"owner","DELETE /api/trainer":"owner"},$J={"GET /api/models":"read","GET /api/providers":"read","GET /api/sessions":"read","GET /api/sessions/:id":"read","GET /api/jobs/:id/preview":"read","GET /api/assets/:id":"read","GET /api/gallery":"read","GET /api/assistant":"read","GET /api/sessions/:id/assistant":"read","GET /api/events":"read","GET /api/settings":"read","GET /api/local-models":"read","GET /api/local-models/:id/demos/:index":"read","GET /api/loras":"read","GET /api/checkpoints":"read","GET /api/trainer":"read","GET /api/captioner":"read","DELETE /api/sessions/:id":"generate","POST /api/turns":"generate","POST /api/jobs/:id/cancel":"generate","POST /api/jobs/:id/retry":"generate","POST /api/assets":"generate","DELETE /api/assets/:id":"generate","POST /api/prompts/improve":"generate","POST /api/assistant/messages":"generate","POST /api/sessions/:id/assistant/stop":"generate","POST /api/sessions/:id/assistant/answers":"generate","POST /api/loras":"train","POST /api/trainings":"train","POST /api/trainings/cancel":"train","POST /api/trainings/finish":"train","GET /api/trainings/:id/samples/:step":"train","POST /api/captions":"train"}});import{copyFile as kJ,mkdir as TJ,readdir as PJ,readFile as EJ,realpath as IJ,rename as AJ,rm as RJ,stat as lN,writeFile as CJ}from"fs/promises";import{dirname as R0,resolve as I0}from"path";function OJ(e){let t=e.match(/^([A-Za-z]):[\\/](.*)$/);if(!t)return null;let[,r,n]=t;return`/mnt/${r.toLowerCase()}/${n.replaceAll("\\","/")}`}function zJ(e,t){if(!e||typeof e!=="object")return!1;let{command:r,args:n}=e;if(typeof r!=="string"||!Array.isArray(n))return!1;let s=n.map(String);if(!s.includes("mcp"))return!1;return r===t.command||[r,...s].some((o)=>o.split(/[\\/]/).some((i)=>i.startsWith(es)))}function C0(e,t){let r=e.mcpServers?.[es];return zJ(r,t)?r:void 0}function oN(e,t){if(!e.mcpServers||!C0(e,t))return!1;let{[es]:r,...n}=e.mcpServers;return e.mcpServers=n,!0}function MJ(e){if(!e.allowPaid)return[];return["--allow-paid",...e.spendLimitUsd!=null?["--spend-limit",String(e.spendLimitUsd)]:[]]}function LJ(e,t){let r=e.indexOf("mcp");if(r<0)return[];let n=new Set(["--allow-paid","--spend-limit",...t.args]),s=[];for(let o=r+1;o<e.length;o++){let i=e[o],a=NJ.has(i)?e.slice(o,o+2):[i];if(!n.has(i))s.push(...a);o+=a.length-1}return s}function DJ(e){if(!e||typeof e!=="object"||Array.isArray(e))return{};let t=Ri(es,""),r=Ri(Ds,""),n=(s)=>s.startsWith(t)?r+s.slice(t.length):s;return Object.fromEntries(Object.entries(e).map(([s,o])=>[n(s),s==="WSLENV"?String(o).split(":").map(n).join(":"):String(o)]))}function jJ(e){let t=e.indexOf("--spend-limit"),r=t>=0?e[t+1]??"":"",n=/^\d+(\.\d+)?$/.test(r)?Number(r):null;return{allowPaid:e.includes("--allow-paid"),spendLimitUsd:n}}async function iN(e){let t;try{t=await EJ(e,"utf8")}catch(o){if(o.code==="ENOENT")return{};throw A0(e)}let r=t.replace(/^\uFEFF/,"");if(!r.trim())return{};let n;try{n=JSON.parse(r)}catch{throw A0(e)}let s=n?.mcpServers;if(!n||typeof n!=="object"||Array.isArray(n)||s!=null&&(typeof s!=="object"||Array.isArray(s)))throw A0(e);return n}async function UJ(e,t){await TJ(R0(e),{recursive:!0});let r=await IJ(e).catch(()=>e),n=await lN(r).catch(()=>null),s=`${r}.before-hatchlight`;if(n&&!await Qf(s))await kJ(r,s);let o=`${r}.${crypto.randomUUID()}.tmp`;try{await CJ(o,`${JSON.stringify(t,null,2)}
|
|
131
|
+
`,{mode:n?n.mode&511:384}),await AJ(o,r)}catch(i){throw await RJ(o,{force:!0}),i}}class O0{load;setup=null;queue=Promise.resolve();constructor(e){this.load=e}get(){return this.setup??=this.load(),this.setup}async status(){let{code:e,codeInWsl:t,desktop:r,shell:n,claudeDesktopConfig:s}=await this.get(),o=(f)=>["claude","mcp","add",Ta,"--scope","user",...Object.entries(f.env??{}).flatMap(([m,h])=>["-e",`${m}=${h}`]),"--",f.command,...f.args],i=o(e),a=t?o(t):null,c={available:!1,connected:!1,current:!1,policy:null,problem:null};if(!s||!await Qf(R0(s)))return{claudeCode:i,claudeCodeWsl:a,shell:n,claudeDesktop:c};let l;try{l=await iN(s)}catch(f){return{claudeCode:i,claudeCodeWsl:a,shell:n,claudeDesktop:{...c,available:!0,problem:f.message}}}let u=l.mcpServers?.[Ta],d=u??C0(l,r),p=Array.isArray(d?.args)?d.args.map(String):[];return{claudeCode:i,claudeCodeWsl:a,shell:n,claudeDesktop:{available:!0,connected:d!=null,current:u!=null&&d?.command===r.command&&r.args.every((f,m)=>p[m]===f),policy:d?jJ(p):null,problem:null}}}connectClaudeDesktop(e){return this.change(async(t,{desktop:r})=>{let n=t.mcpServers?.[Ta]?void 0:C0(t,r);oN(t,r);let s={...DJ(n?.env),...r.env??{}};return t.mcpServers={...t.mcpServers??{},[Ta]:{command:r.command,args:[...r.args,...LJ(n?.args.map(String)??[],r),...MJ(e)],...Object.keys(s).length>0&&{env:s}}},!0})}disconnectClaudeDesktop(){return this.change(async(e,{desktop:t})=>{let r=oN(e,t);if(!e.mcpServers?.[Ta])return r;let{[Ta]:n,...s}=e.mcpServers;return e.mcpServers=s,!0})}change(e){let t=async()=>{let n=await this.get(),s=n.claudeDesktopConfig;if(!s||!await Qf(R0(s)))throw new O("Claude Desktop is not installed on this computer","claudeNotFound");let o=await iN(s);if(await e(o,n))await UJ(s,o)},r=this.queue.then(t,t);return this.queue=r.catch(()=>{}),r}}async function aN(e){try{let t=Bun.spawn(e,{cwd:"/",stdout:"pipe",stderr:"ignore"}),r=setTimeout(()=>t.kill(),5000),[n,s]=await Promise.all([new Response(t.stdout).text(),t.exited]);return clearTimeout(r),s===0?n.replaceAll("\r","").trim():null}catch{return null}}async function cN(e,t){let r=t(e,"Packages"),n=await PJ(r).catch(()=>[]);for(let s of n.filter((o)=>o.startsWith("Claude_"))){let o=t(r,s,"LocalCache","Roaming","Claude");if(await Qf(o))return o}return null}async function uN(e){let t=e.env??process.env,r=e.platform??process.platform,n=e.home??t.HOME??t.USERPROFILE??"",s=/\$bunfs|~BUN/.test(Bun.main),o=e.dataDir?["--data-dir",I0(e.dataDir)]:[],i=e.npmPackage?{command:"bunx",args:[e.npmPackage,"mcp",...o]}:{command:e.program??process.execPath,args:[...s?[]:[Bun.main],"mcp",...o,...e.resources?["--resources",I0(e.resources)]:[]]},a=Object.fromEntries(["DATA_DIR","MODELS_DIR"].flatMap((u)=>{let d=lt(t,u);return d?[[Ri(Ds,u),I0(d)]]:[]}));if(Object.keys(a).length>0)i.env=a;if(r==="win32"){let u=(...h)=>h.map(BJ).join("\\"),d=t.APPDATA??u(n,"AppData","Roaming"),p=t.LOCALAPPDATA??u(n,"AppData","Local"),f=await cN(p,u)??u(d,"Claude"),m=OJ(i.command);return{code:i,...m&&{codeInWsl:{command:m,args:i.args,...i.env&&{env:{...i.env,WSLENV:Object.keys(i.env).join(":")}}}},desktop:i,shell:"powershell",claudeDesktopConfig:u(f,Jf)}}if(r==="darwin")return{code:i,desktop:i,shell:"posix",claudeDesktopConfig:`${n}/Library/Application Support/Claude/${Jf}`};let c=t.WSL_DISTRO_NAME;if(c){let u=async(g)=>{let w=await aN(["cmd.exe","/c","echo",`%${g}%`]);return w&&!w.includes("%")?await aN(["wslpath","-u",w]):null},[d,p]=await Promise.all([u("APPDATA"),u("LOCALAPPDATA")]),f=(...g)=>g.join("/"),m=(p&&await cN(p,f))??(d?f(d,"Claude"):null),h=Object.entries(a).map(([g,w])=>`${g}=${w}`);return{code:i,desktop:{command:"wsl.exe",args:["-d",c,"-e",...h.length>0?["env",...h]:[],i.command,...i.args]},shell:"posix",claudeDesktopConfig:m?f(m,Jf):null}}let l=t.XDG_CONFIG_HOME??`${n}/.config`;return{code:i,desktop:i,shell:"posix",claudeDesktopConfig:`${l}/Claude/${Jf}`}}function BJ(e){let t=e.length;while(t>0&&e[t-1]==="\\")t--;return e.slice(0,t)}var Ta="hatchlight",NJ,Qf=(e)=>lN(e).then(()=>!0,()=>!1),A0=(e)=>new O("Claude Desktop's settings file cannot be read, so it is left as it is","claudeConfigUnreadable",{path:e}),Jf="claude_desktop_config.json";var dN=b(()=>{Pt();NJ=new Set(["--data-dir","--resources","--spend-limit"])});var ei;var Xf=b(()=>{ei=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause});this.res=t?.res,this.status=e}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var Pa;var Yf=b(()=>{Pa=Symbol()});var pN=()=>{};var fN=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var mN=b(()=>{pN()});async function FJ(e,t){if(!em(e)&&e.bodyCache.formData)return hN(await e.bodyCache.formData,t);let r=em(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),s=fN(n,r.get("Content-Type")||"");if(!em(e))e.bodyCache.formData=s;let o=await s;if(o)return hN(o,t);return{}}function hN(e,t){let r=Object.create(null),n={count:0};if(e.forEach((s,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=s;else VJ(r,o,s)}),t.dot)Object.entries(r).forEach(([s,o])=>{if(s.includes("."))ZJ(r,s,o,n),delete r[s]});return r}var qJ=1e4,em=(e)=>("headers"in e),yN=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(em(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(s==="multipart/form-data"||s==="application/x-www-form-urlencoded")return FJ(e,{all:r,dot:n});return{}},VJ=(e,t,r)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(r);else e[t]=[e[t],r];else if(!t.endsWith("[]"))e[t]=r;else e[t]=[r]},ZJ=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let s=e,o=t.split(".",34);if(o.length>33)gN();o.forEach((i,a)=>{if(a===o.length-1)s[i]=r;else{if(!s[i]||typeof s[i]!=="object"||Array.isArray(s[i])||s[i]instanceof File){if(n.count++>=qJ)gN();s[i]=Object.create(null)}s=s[i]}})},gN=()=>{throw Error("Nesting limit exceeded")};var wN=b(()=>{mN()});var N0=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},Jl=(e)=>{let{groups:t,path:r}=HJ(e),n=N0(r);return GJ(n,t)},HJ=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},GJ=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},tm,Ql=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;if(!tm[n])if(r[2])tm[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else tm[n]=[e,r[1],!0];return tm[n]}return null},rm=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},z0=(e)=>decodeURI(e.includes("%25")?e.replace(/%25/g,"%2525"):e),L0=(e)=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let o=t.indexOf("?",n),i=t.indexOf("#",n),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),c=t.slice(r,a),l=rm(c,z0);if(/%(?![0-9A-Fa-f]{2})/.test(c)){let u=new URL("http://localhost");if(u.pathname=l.replace(/[\\\t\n\r]/g,encodeURIComponent),rm(u.pathname,z0)!==l)return rm(c.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"),z0)}return l}else if(s===63||s===35)break}return t.slice(r,n)},bN=(e)=>{let t=L0(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},ti=(e,t,...r)=>{if(r.length)t=ti(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},nm=(e)=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach((s)=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(s.charCodeAt(s.length-1)===63){if(r.length===0&&n==="")r.push("/");else r.push(n);let o=s.slice(0,-1);n+="/"+o,r.push(n)}else n+="/"+s}),r.filter((s,o,i)=>i.indexOf(s)===o)},Ea=(e)=>e.indexOf("%")!==-1?rm(e,KJ):e,M0=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Ea(e)},vN=(e,t,r)=>{let n=e.indexOf("#",8);if(n!==-1)e=e.slice(0,n);let s;if(!r&&t&&!/[%+&=]/.test(t)){let a=e.indexOf("?",8),c=a;if(c===-1)return;if(!e.startsWith(t,c+1))c=e.indexOf(`&${t}`,c+1);while(c!==-1){let l=e.charCodeAt(c+t.length+1);if(l===61||l===38||isNaN(l)){if(c>a&&/(?:^|&)[^=&]*[%+]/.test(e.slice(a+1,c)))break;if(l===61){let u=c+t.length+2,d=e.indexOf("&",u);return M0(e.slice(u,d===-1?void 0:d))}return""}c=e.indexOf(`&${t}`,c+1)}if(s=/[%+]/.test(e),!s)return}let o=Object.create(null);s??=/[%+]/.test(e);let i=e.indexOf("?",8);while(i!==-1){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);if(c>a&&a!==-1)c=-1;let l=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(s)l=M0(l);if(i=a,l==="")continue;let u;if(c===-1)u="";else if(u=e.slice(c+1,a===-1?void 0:a),s)u=M0(u);if(r){if(!(o[l]&&Array.isArray(o[l])))o[l]=[];o[l].push(u)}else o[l]??=u}return t?o[t]:o},_N,xN=(e,t)=>vN(e,t,!0),KJ;var ws=b(()=>{tm={},_N=vN,KJ=decodeURIComponent});var SN;var $N=b(()=>{Xf();Yf();wN();ws();SN=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#o()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#s(t);return r&&Ea(r)}#o(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#s(this.#e[0][this.routeIndex][1][r]);if(n!==void 0)e[r]=Ea(n)}return e}#s(e){return this.#e[1]?this.#e[1][e]:e}query(e){return _N(this.url,e)}queries(e){return xN(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return yN(this,e)}#n=(e)=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let s in t)return t[s].then((o)=>{if(s==="json")o=JSON.stringify(o);let i=s==="formData"?void 0:r.headers.get("content-type");return new Response(o,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=r[e]()};json(){return this.#n("text").then((e)=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then((e)=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Pa](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}}});var sm,WJ=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},Xl=async(e,t,r,n,s)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let o=e.callbacks;if(!o?.length)return Promise.resolve(e);if(s)s[0]+=e;else s=[e];let i=Promise.all(o.map((a)=>a({phase:t,buffer:s,context:n}))).then((a)=>Promise.all(a.filter(Boolean).map((c)=>Xl(c,t,!1,n,s))).then(()=>s[0]));if(r)return WJ(await i,o);else return i};var D0=b(()=>{sm={Stringify:1,BeforeStream:2,Stream:3}});var kN="text/plain; charset=UTF-8",j0=(e,t)=>({"Content-Type":e,...t}),Yl=(e,t)=>new Response(e,t),U0=class{#t;#e;env={};#r;finalized=!1;error;#o;#s;#n;#u;#c;#l;#a;#d;#p;constructor(e,t){if(this.#t=e,t)this.#s=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#p=t.path,this.#d=t.matchResult}get req(){return this.#e??=new SN(this.#t,this.#p,this.#d),this.#e}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;else throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Yl(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Yl(e.body,e);for(let[t,r]of this.#n.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s)}else e.headers.set(t,r)}}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=(t)=>this.html(t),this.#c(...e));setLayout=(e)=>this.#u=e;getLayout=()=>this.#u;setRenderer=(e)=>{this.#c=e};header=(e,t,r)=>{if(this.finalized&&!this.#n.bodyUsed)this.#n=Yl(this.#n.body,this.#n);let n=this.#n?this.#n.headers:this.#a??=new Headers;if(t===void 0)n.delete(e);else if(r?.append)n.append(e,t);else n.set(e,t)};status=(e)=>{this.#o=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=(e)=>this.#r?this.#r.get(e):void 0;get var(){if(!this.#r)return{};return Object.fromEntries(this.#r)}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a;if(typeof t==="object"&&t.headers){n??=new Headers;for(let[o,i]of new Headers(t.headers))if(o==="set-cookie")n.append(o,i);else n.set(o,i)}if(r){if(!n){let o=0;for(let i in r)if(++o>1||typeof r[i]!=="string"){n=new Headers;break}}if(n)for(let o in r){let i=r[o];if(typeof i==="string")n.set(o,i);else{n.delete(o);for(let a of i)n.append(o,a)}}}let s=typeof t==="number"?t:t?.status??this.#o;return Yl(e,{status:s,headers:n??r})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#o&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,j0(kN,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,j0("application/json",r));html=(e,t,r)=>{let n=(s)=>this.#i(s,t,j0("text/html; charset=UTF-8",r));return typeof e==="object"?Xl(e,sm.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(r)?r:encodeURI(r)),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>Yl(),this.#l(this))};var om=b(()=>{$N();D0()});var B0=(e,t,r)=>(n,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw Error("next() called multiple times");o=a;let c,l=!1,u;if(e[a])u=e[a][0][0],n.req.routeIndex=a;else u=a===e.length&&s||void 0;if(u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else if(n.finalized===!1&&r)c=await r(n);if(c&&(n.finalized===!1||l))n.res=c;return n}};var TN=()=>{};var q0=(e)=>e.req[Pa][0].map(([[,t]])=>t),PN=(e,t)=>q0(e).at(t??e.req.routeIndex)?.path??"";var F0=b(()=>{Yf();ws()});var EN,im="Can not add a route since the matcher is already built.",am;var Ia=b(()=>{EN=["get","post","put","delete","options","patch","query"],am=class extends Error{}});var IN="__COMPOSED_HANDLER";var AN=()=>{};var RN=(e)=>{let t=e.length;while(t>0&&e.charCodeAt(t-1)===47)t--;return e.length-t},JJ=(e,t,r)=>{if(!/[:*]/.test(t))return t.length;let n=e.req.path,s=e.req[Pa],o=new Set,i=0;for(let a of Jl(t)){if(a[0]===":"&&a.endsWith("}?"))throw Error(`mount(): Optional regular expression parameters are not supported in "${r}".`);let c=Ql(a);if(c&&c!=="*"){let l=c[1];if(o.has(l))throw Error(`mount(): Duplicate path parameter "${l}" in "${r}".`);o.add(l)}if(c&&c!=="*"&&c[2]!==!0){let l=s.length===2?s[1][s[0][e.req.routeIndex][1][c[1]]]:s[0][e.req.routeIndex][1][c[1]];i+=l.length+1}else if(c||a.endsWith("*")){let l=n.indexOf("/",i+1);i=l===-1?n.length:l}else i+=a.length+1}return i},CN=(e,t,r)=>{if(/[^/]\*$/.test(r))throw Error(`mount(): Wildcard must follow "/" in "${r}".`);let n=JJ(e,t,r),s=e.req.path.slice(n)||"/";if(n>e.req.path.length||s[0]!=="/"||/\/(?:\.|%2e){1,2}(?:\/|$)/i.test(s))throw new ei(400,{message:"Invalid mounted path"});let o=e.req.raw.url;if(/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(o))throw new ei(400,{message:"Invalid mounted path"});let i=o.search(/[?#]/),a=RN(i===-1?o:o.slice(0,i));if(a>1&&RN(e.req.path)===a-1)throw new ei(400,{message:"Invalid mounted path"});let c=new URL(o);if(c.pathname=s.replace(/[\\\t\n\r]/g,encodeURIComponent),s.includes("%"));return new Request(c,e.req.raw)};var ON=b(()=>{Xf();Yf();ws()});var QJ=(e)=>e.text("404 Not Found",404),zN=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},MN=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...EN,"all"].forEach((s)=>{this[s]=(o,...i)=>{let a=s.toUpperCase();if(typeof o==="string")this.#t=o;else this.#o(a,this.#t,o);return i.forEach((c)=>{this.#o(a,this.#t,c)}),this}}),this.on=(s,o,...i)=>{for(let a of[o].flat()){this.#t=a;for(let c of[s].flat()){let l=c.toUpperCase();for(let u of i)this.#o(l,this.#t,u)}}return this},this.use=(s,...o)=>{if(typeof s==="string")this.#t=s;else this.#t="*",o.unshift(s);return o.forEach((i)=>{this.#o("ALL",this.#t,i)}),this};let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??L0:bN}#e(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=QJ;errorHandler=zN;route(t,r){let n=this.basePath(t);return r.routes.map((s)=>{let o;if(r.errorHandler===zN)o=s.handler;else o=async(i,a)=>(await B0([],r.errorHandler)(i,()=>s.handler(i,a))).res,o[IN]=s.handler;n.#o(s.method,s.path,o,s.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=ti(this._basePath,t),r}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#r=t,this);mount(t,r,n){let s,o;if(n)if(typeof n==="function")o=n;else if(o=n.optionHandler,n.replaceRequest===!1)s=(l)=>l;else s=n.replaceRequest;let i=o?(l)=>{let u=o(l);return Array.isArray(u)?u:[u]}:(l)=>{let u=void 0;try{u=l.executionCtx}catch{}return[l.env,u]},a=(l)=>{let u=PN(l);return CN(l,u.replace(/\/?\*$/,""),u)},c=async(l,u)=>{let d=await r(s?s(l.req.raw):a(l),...i(l));if(d)return d;await u()};return this.#o("ALL",ti(t,"*"),c),this}#o(t,r,n,s){r=ti(this._basePath,r);let o={basePath:s!==void 0?ti(this._basePath,s):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,o]),this.routes.push(o)}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,s){if(s==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let o=this.getPath(t,{env:n}),i=this.router.match(s,o),a=new U0(t,{path:o,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#s(u,a)}return l instanceof Promise?l.then((u)=>u||(a.finalized?a.res:this.#r(a))).catch((u)=>this.#s(u,a)):l??this.#r(a)}let c=B0(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#s(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,s)=>{if(t instanceof Request)return this.fetch(r?new Request(t,r):t,n,s);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${ti("/",t)}`,r),n,s)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var NN=b(()=>{TN();ws();om();F0();Ia();AN();ON()});var Dr=()=>Object.create(null);var eu=()=>{};function LN(e,t){let r=this.buildAllMatchers(),n=(s,o)=>{let i=r[s]||r.ALL,a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],V0];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=n,n(e,t)}var V0;var DN=b(()=>{Ia();V0=[]});function tQ(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e==="[^]*"||e==="(?:|/[^]*)")return t==="[^]*"?-1:1;else if(t==="[^]*"||t==="(?:|/[^]*)")return-1;if(e==="[^/]+")return 1;else if(t==="[^/]+")return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var XJ="[^/]+",YJ="[^]*",eQ="(?:|/[^]*)",go,jN,UN=class e{#t;#e;#r=Dr();insert(t,r,n,s,o){let i=this;for(let a=0,c=t.length;a<c;a++){let l=t[a],u=l.length===1?l==="*"?a===c-1?["","",YJ]:["","",XJ]:null:l==="/*"?["","",eQ]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let p=u[1],f=u[2]||"[^/]+";if(p&&u[2]){if(new RegExp(f).test(""))throw go;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw go;if(f.length===1&&jN.has(f))throw go}if(o.push(f),d=i.#r[f],!d){if(f!=="[^]*"&&f!=="(?:|/[^]*)"){for(let m in i.#r)if((f.length>1||m.length>1)&&m!=="[^]*"&&m!=="(?:|/[^]*)")throw go}d=i.#r[f]=new e}if(p!=="")d.#e??=s.varIndex++,n.push([p,d.#e])}else if(o.push(l),d=i.#r[l],!d){for(let p in i.#r)if(p.length>1&&p!=="[^]*"&&p!=="(?:|/[^]*)")throw go;d=i.#r[l]=new e}i=d}if(i.#t!==void 0)throw go;i.#t=r}buildRegExpStr(){let t=Object.keys(this.#r).sort(tQ).map((r)=>{let n=this.#r[r],s=n.buildRegExpStr();return s===""?"":(typeof n.#e==="number"?`(${r})@${n.#e}`:jN.has(r)?`\\${r}`:r)+s}).filter(Boolean);if(typeof this.#t==="number"&&this.#t!==-1)t.unshift(`#${this.#t}`);if(t.length===0)return"";if(t.length===1)return t[0];return"(?:"+t.join("|")+")"}};var Z0=b(()=>{eu();go=Symbol(),jN=new Set(".\\+*[^]$()")});var H0=class{#t={varIndex:0};#e=new UN;#r=0;paths=Dr();insert(e,t){let r=[];if(t){this.#e.insert(e.split(""),-1,[],this.#t,r),this.paths[e]=[-1,[],r];return}let n=[],s=[],o=e;for(let a=0;;){let c=!1;if(o=o.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,(l)=>{let u=`@\\${a}`;return s[a]=[u,l],a++,c=!0,u}),!c)break}let i=o.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let a=s.length-1;a>=0;a--){let[c]=s[a];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(c)!==-1){i[l]=i[l].replace(c,s[a][1]);break}}this.#e.insert(i,this.#r,n,this.#t,r),this.paths[e]=[this.#r++,n,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>{if(o!==void 0)return r[++t]=Number(o),"$()";if(i!==void 0)return n[Number(i)]=++t,"";return""}),[new RegExp(`^${e}`),r,n]}};var BN=b(()=>{eu();Z0()});function rQ(e){let t=e[e.length-1];return t==="[^]*"||t==="(?:|/[^]*)"}function nQ(e,t){let r=e.length-1;for(let n=0;n<r;n++)if(e[n]!==t[n])return!1;return e[r]==="[^]*"||t.length===r||t[r]==="/"}var qN=class{name="RegExpRouter";#t;#e;constructor(){this.#t={["ALL"]:[]},this.#e={["ALL"]:new H0}}#r(e,t){try{this.#e[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===go?new am(t):r}}add(e,t,r){let n=this.#t;if(!n)throw Error(im);let s=this.#e;if(!n[e]){s[e]=new H0,n[e]=[...n.ALL];for(let a in s.ALL.paths)this.#r(e,a)}if(t==="/*")t="*";let o=e==="ALL"?Object.keys(n):[e],i=nm(t)||[t];for(let a of i)for(let c of o){if(!s[c].paths[a])this.#r(c,a);n[c].push([r,a])}}match=LN;buildAllMatchers(){let e=Dr();for(let t of Object.keys(this.#t))e[t]=this.#o(t);return this.#t=this.#e=void 0,e}#o(e){let t=this.#t[e],r=this.#e[e],n=Dr(),s=[],[o,i,a]=r.buildRegExp(),c=Dr(),l=t.map(([d,p],f)=>((c[p]??=[]).push(f),[d,r.paths[p][1].reduceRight((m,[h,g])=>(m[h]=a[g],m),Dr())])),u=Object.keys(c).filter((d)=>rQ(r.paths[d][2]));for(let d in r.paths){let[p,,f]=r.paths[d],m=[...c[d]];for(let g of u)if(g!==d&&nQ(r.paths[g][2],f))m.push(...c[g]);let h=m.sort((g,w)=>g-w).map((g)=>l[g]);if(p===-1){let g=Math.max(-1,...h.flatMap(([,w])=>Object.values(w)));n[d]=[h,g===-1?V0:d.match(o).slice(0,g+1)]}else s[p]=h}return[o,i.map((d)=>s[d]),n]}};var FN=b(()=>{ws();Ia();eu();DN();Z0();BN()});var VN=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error(im);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw Error("Fatal error");let r=this.#t,n=this.#e,s=r.length,o=0,i;for(;o<s;o++){let a=r[o];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof am)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===s)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var ZN=b(()=>{Ia()});var G0,sQ=0,HN=class e{#t=[];#e=Dr();#r=[];#o;#s=G0;insert(t,r,n){let s=this,o=Jl(r),i=new Set,a=0;for(let c of o){let l=o[++a],u=Ql(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),p=d?u[0]:u||c,f=s.#e[p]||=new e;if(u&&!f.#o)f.#o=u,s.#r.push(f);if(s=f,d)i.add(u[1])}s.#t.push({[t]:{handler:n,possibleKeys:[...i],score:++sQ}})}#n(t,r,n,s,o){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c.ALL;if(l){l.params=Dr(),t.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let p=l.possibleKeys[u];l.params[p]=o?.[p]&&!u?o[p]:s[p]??o?.[p]}}}}search(t,r){let n=[];this.#s=G0;let s=[this],o=N0(r),i=[],a=o.length,c=null;for(let l=0;l<a;l++){let u=o[l],d=l===a-1,p=[];for(let m=0,h=s.length;m<h;m++){let g=s[m],w=g.#e[u];if(w)if(w.#s=g.#s,d){if(w.#e["*"])this.#n(n,w.#e["*"],t,g.#s);this.#n(n,w,t,g.#s)}else p.push(w);for(let v of g.#r){let _=v.#o,C=g.#s===G0?{}:{...g.#s};if(typeof _==="string"){if(_==="*"||u.startsWith(_.slice(0,-1))){if(this.#n(n,v,t,g.#s),_==="*")v.#s=C,p.push(v)}continue}let[,k,P]=_;if(!u&&P===!0)continue;if(P!==!0){if(!c){c=[];let T=r[0]==="/"?1:0;for(let I=0;I<a;I++)c[I]=T,T+=o[I].length+1}let y=r.slice(c[l]),x=P.exec(y);if(x){if(!Object.hasOwn(C,k))C[k]=x[0];if(this.#n(n,v,t,g.#s,C),x[0].length===y.length&&v.#e["*"])this.#n(n,v.#e["*"],t,g.#s,C);for(let T in v.#e){v.#s=C;let I=x[0].match(/\//g)?.length??0;(i[I]||=[]).push(v);break}continue}}if(P===!0||P.test(u)){if(!Object.hasOwn(C,k))C[k]=u;if(d){if(this.#n(n,v,t,C,g.#s),v.#e["*"])this.#n(n,v.#e["*"],t,C,g.#s)}else v.#s=C,p.push(v)}}}let f=i.shift();s=f?p.concat(f):p}if(n[1])n.sort((l,u)=>l.score-u.score);return[n.map(({handler:l,params:u})=>[l,u])]}};var GN=b(()=>{ws();Ia();eu();G0=Dr()});var K0=class{name="TrieRouter";#t=new HN;add(e,t,r){for(let n of nm(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};var W0=b(()=>{ws();GN()});var KN=b(()=>{W0()});var J0;var WN=b(()=>{NN();FN();ZN();W0();KN();J0=class extends MN{constructor(e={}){super(e);this.router=e.router??new VN({routers:[new qN,new K0]})}}});var JN=b(()=>{om();WN()});var oQ="Payload Too Large",cm=(e)=>{let t=e.onError||(()=>{let n=new Response(oQ,{status:413});throw new ei(413,{res:n})}),r=e.maxSize;return async function(s,o){if(!s.req.raw.body)return o();let i=s.req.raw.headers.has("transfer-encoding");if(s.req.raw.headers.has("content-length")&&!i)return parseInt(s.req.raw.headers.get("content-length")||"0",10)>r?t(s):o();let a=0,c=new Uint8Array(0),l=s.req.raw.body.getReader();for(;;){let{done:u,value:d}=await l.read();if(u)break;let p=a;if(a+=d.length,a>r)return t(s);if(a>c.length){let f=new Uint8Array(Math.min(r,Math.max(a,c.length*2)));f.set(c.subarray(0,p)),c=f}c.set(d,p)}return s.req.raw=new Request(s.req.raw,{body:c.subarray(0,a)}),o()}};var QN=b(()=>{Xf()});var Q0=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(e,t){this.writable=e,this.writer=e.getWriter(),this.encoder=new TextEncoder;let r=t.getReader();this.abortSubscribers.push(async()=>{await r.cancel()}),this.responseReadable=new ReadableStream({async pull(n){let{done:s,value:o}=await r.read();s?n.close():n.enqueue(o)},cancel:()=>{if(!this.closed)this.abort()}})}async write(e){try{if(typeof e==="string")e=this.encoder.encode(e);await this.writer.write(e)}catch{}return this}async writeln(e){return await this.write(e+`
|
|
132
|
+
`),this}sleep(e){return new Promise((t)=>setTimeout(t,e))}async close(){this.closed=!0;try{await this.writer.close()}catch{}}async pipe(e){this.writer.releaseLock();try{await e.pipeTo(this.writable,{preventClose:!0,preventAbort:!0})}finally{this.writer=this.writable.getWriter()}}onAbort(e){this.abortSubscribers.push(e)}abort(){if(!this.aborted)this.aborted=!0,this.abortSubscribers.forEach((e)=>{try{Promise.resolve(e()).catch(()=>{})}catch{}})}};var X0=()=>{};var lm=()=>{let e=typeof Bun<"u"?Bun.version:void 0;if(e===void 0)return!1;let t=e.startsWith("1.1")||e.startsWith("1.0")||e.startsWith("0.");return lm=()=>t,t};var Y0=()=>{};var ex=b(()=>{X0();Y0()});var XN,iQ=async(e,t,r)=>{try{await t(e)}catch(n){if(n instanceof Error&&r)await r(n,e),await e.writeSSE({event:"error",data:n.message});else console.error(n)}finally{e.close()}},aQ,tx=(e,t,r)=>{let{readable:n,writable:s}=new TransformStream,o=new XN(s,n);if(lm())e.req.raw.signal.addEventListener("abort",()=>{if(!o.closed)o.abort()});return aQ.set(o.responseReadable,e),e.header("Transfer-Encoding","chunked"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),iQ(o,t,r),e.newResponse(o.responseReadable)};var YN=b(()=>{D0();X0();Y0();XN=class extends Q0{constructor(e,t){super(e,t)}async writeSSE(e){let t=(await Xl(e.data,sm.Stringify,!1,{})).split(/\r\n|\r|\n/).map((n)=>`data: ${n}`).join(`
|
|
133
|
+
`);for(let n of["event","id"]){let s=e[n];if(s&&/[\r\n]/.test(s))throw Error(`${n} must not contain "\\r" or "\\n"`)}let r=[e.event&&`event: ${e.event}`,t,e.id!==void 0&&`id: ${e.id}`,e.retry!==void 0&&`retry: ${e.retry}`].filter(Boolean).join(`
|
|
134
|
+
`)+`
|
|
135
|
+
|
|
136
|
+
`;await this.write(r)}},aQ=new WeakMap});var e4=b(()=>{om();ex()});var t4=b(()=>{ex();YN();e4()});var lQ,uQ,dQ,r4=(e)=>{let t=0,r=e.length;while(t<r){let n=e.charCodeAt(t);if(n!==32&&n!==9)break;t++}while(r>t){let n=e.charCodeAt(r-1);if(n!==32&&n!==9)break;r--}return t===0&&r===e.length?e:e.slice(t,r)},rx=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let r=e.split(";"),n=Object.create(null);for(let s of r){let o=s.indexOf("=");if(o===-1)continue;let i=r4(s.substring(0,o));if(t&&t!==i||!uQ.test(i)||i in n)continue;let a=r4(s.substring(o+1));if(a.length>=2&&a.startsWith('"')&&a.endsWith('"'))a=a.slice(1,-1);if(dQ.test(a)){if(n[i]=Ea(a),t)break}}return n},pQ=(e,t,r={})=>{if(!lQ.test(e))throw Error("Invalid cookie name");let n=`${e}=${t}`;if(/^__secure-/i.test(e)&&!r.secure)throw Error("__Secure- Cookie must have Secure attributes");if(/^__host-/i.test(e)){if(!r.secure)throw Error("__Host- Cookie must have Secure attributes");if(r.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(r.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let s of["domain","path","sameSite","priority"])if(r[s]&&/[;\r\n]/.test(r[s]))throw Error(`${s} must not contain ";", "\\r", or "\\n"`);if(r&&typeof r.maxAge==="number"&&r.maxAge>=0){if(r.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");n+=`; Max-Age=${r.maxAge|0}`}if(r.domain&&r.prefix!=="host")n+=`; Domain=${r.domain}`;if(r.path)n+=`; Path=${r.path}`;if(r.expires){if(r.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");n+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly)n+="; HttpOnly";if(r.secure)n+="; Secure";if(r.sameSite)n+=`; SameSite=${r.sameSite.charAt(0).toUpperCase()+r.sameSite.slice(1)}`;if(r.priority)n+=`; Priority=${r.priority.charAt(0).toUpperCase()+r.priority.slice(1)}`;if(r.partitioned){if(!r.secure)throw Error("Partitioned Cookie must have Secure attributes");n+="; Partitioned"}return n},um=(e,t,r)=>(t=encodeURIComponent(t),pQ(e,t,r));var n4=b(()=>{ws();lQ=/^[\w!#$%&'*.^`|~+-]+$/,uQ=/^[!#-:<>-[\]-~]+$/,dQ=/^[ !#-:<-[\]-~]*$/});var dm=(e,t,r)=>{let n=e.req.raw.headers.get("Cookie");if(typeof t==="string"){if(!n)return;let s=t;if(r==="secure")s="__Secure-"+t;else if(r==="host")s="__Host-"+t;return rx(n,s)[s]}if(!n)return{};return rx(n)},fQ=(e,t,r)=>{let n;if(r?.prefix==="secure")n=um("__Secure-"+e,t,{path:"/",...r,secure:!0});else if(r?.prefix==="host")n=um("__Host-"+e,t,{...r,path:"/",secure:!0,domain:void 0});else n=um(e,t,{path:"/",...r});return n},pm=(e,t,r,n)=>{let s=fQ(t,r,n);e.header("Set-Cookie",s,{append:!0})},nx=(e,t,r)=>{let n=dm(e,t,r?.prefix);return pm(e,t,"",{...r,maxAge:0}),n};var s4=b(()=>{n4()});function ru(e,t){let r=tu(e);pm(e,r?sx:ox,t.token,{httpOnly:!0,secure:r,sameSite:"Lax",path:"/",maxAge:Math.max(0,Math.floor((t.expiresAt-Date.now())/1000))})}function fm(e,t){let r=tu(e);pm(e,r?o4:i4,t,{httpOnly:!0,secure:r,sameSite:"Lax",path:"/",maxAge:mQ})}function a4(e){return dm(e,tu(e)?o4:i4)}function c4(e){if(tu(e))nx(e,sx,{path:"/",secure:!0});else nx(e,ox,{path:"/"})}function hQ(e,t){let r=e.req.header("authorization");if(r!==void 0){let o=r.match(/^Bearer\s+(\S+)$/i);return o?.[1]?t.resolveApiToken(o[1]):null}let n=dm(e,tu(e)?sx:ox);if(!n)return null;let s=t.resolveSession(n);if(!s)return null;return ru(e,{user:s.user,token:n,expiresAt:s.expiresAt}),s}function gQ(e,t){switch(e){case"public":case"account":case"member":return!0;case"train":return sd(t);case"admin":return t.role==="owner"||t.role==="admin";case"owner":return t.role==="owner"}}function l4(e){let t=q0(e).find((n)=>n.method!=="ALL"&&n.path.startsWith("/api/")),r=e.req.method==="HEAD"?"GET":e.req.method;return t?{method:r,path:t.path}:null}function yQ(e){let t=l4(e);return t?sN(t.method,t.path):"member"}function u4(e){return async(t,r)=>{let n=yQ(t);if(n==="public")return r();let s=hQ(t,e);if(!s)throw new be("Sign in to go on","signInRequired",401);if(s.apiToken){if(n==="account"||n==="admin"||n==="owner")throw new be("Tokens cannot do this","forbidden",403);let o=l4(t),i=o?nN(o.method,o.path):"read";if(!i||!s.apiToken.scopes.includes(i))throw new be(i?`This API token needs the ${i} scope`:"API tokens cannot do this","tokenScope",403,{scope:i??""})}if(s.user.mustChangePassword&&n!=="account")throw new be("Choose a new password before going on","passwordChangeRequired",403);if(!gQ(n,s.user))throw new be("Your account cannot do this","forbidden",403);t.set("viewer",s),await r()}}var sx="__Host-hatchlight",ox="hatchlight_session",tu=(e)=>e.get("https")===!0,mQ=31536000,o4="__Host-hatchlight-device",i4="hatchlight_device";var ix=b(()=>{Pt();s4();F0();E0()});class yo{entries=new Map;now;freeTries;maxDelayMs;forgetMs;maxKeys;constructor(e={}){this.now=e.now??Date.now,this.freeTries=e.freeTries??5,this.maxDelayMs=e.maxDelayMs??900000,this.forgetMs=e.forgetMs??3600000,this.maxKeys=e.maxKeys??1e4}wait(e){let t=this.entries.get(e);if(!t)return 0;let r=this.now();if(r-t.lastAt>this.forgetMs)return this.entries.delete(e),0;return Math.max(0,t.nextAt-r)}fail(e){let t=this.now(),r=this.entries.get(e),n=r&&t-r.lastAt<=this.forgetMs?r.failures+1:1;this.set(e,n,t)}refund(e){let t=this.entries.get(e);if(!t)return;if(t.failures<=1){this.entries.delete(e);return}this.set(e,t.failures-1,t.lastAt)}set(e,t,r){let n=t-this.freeTries+1,s=n>0?Math.min(1000*2**(n-1),this.maxDelayMs):0;this.entries.delete(e),this.entries.set(e,{failures:t,nextAt:r+s,lastAt:r});while(this.entries.size>this.maxKeys){let o=this.entries.keys().next().value;this.entries.delete(o)}}succeed(e){this.entries.delete(e)}}function m4(e,t){let r=e.mode??lt(t,"MODE")??"personal";if(r!=="personal"&&r!=="server")throw new jr(`Unknown mode: ${r}. Use "personal" or "server"`);let n=e.host??lt(t,"HOST")??(r==="server"?"0.0.0.0":"127.0.0.1");if(r==="personal"){if(!lx(n))throw new jr(`Personal mode listens only on this computer (127.0.0.1, ::1 or localhost), not on ${n}. To reach Hatchlight from other machines, run it with --mode server, which has accounts`);return{mode:r,host:n,transport:null,loraQuota:null,assetQuotaBytes:null}}let s=lt(t,"PUBLIC_URL");if(!s)throw new jr("Server mode needs HATCHLIGHT_PUBLIC_URL, the address people open, such as https://hatchlight.example.com");let o=wQ(s),i=[new URL(o).hostname,...d4(lt(t,"ALLOWED_HOSTS")).map(bQ)],a=d4(lt(t,"TRUSTED_PROXIES")).map(g4),c=(p,f)=>{let m=lt(t,p);if(m===void 0)return f;let h=Number(m);if(!(Number.isFinite(h)&&h>=0))throw new jr(`HATCHLIGHT_${p} must be a number, 0 or more`);return h},l={files:Math.floor(c("LORA_FILES_PER_PERSON",mm.files)),bytes:Math.floor(c("LORA_GB_PER_PERSON",mm.bytes/1073741824)*1073741824)},d=lt(t,"ASSET_GB_PER_PERSON")===void 0?null:Math.floor(c("ASSET_GB_PER_PERSON",0)*1073741824);return{mode:r,host:n,transport:{publicOrigin:o,allowedHosts:i,trustedProxies:a},loraQuota:l,assetQuotaBytes:d}}function wQ(e){let t;try{t=new URL(e)}catch{throw new jr(`HATCHLIGHT_PUBLIC_URL is not an address: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new jr(`HATCHLIGHT_PUBLIC_URL must start with https:// or http://: ${e}`);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw new jr(`HATCHLIGHT_PUBLIC_URL must be only a scheme and a host, such as https://hatchlight.example.com: ${e}`);return t.origin}function bQ(e){let t;try{t=new URL(`http://${e}`)}catch{throw new jr(`Not a host name in HATCHLIGHT_ALLOWED_HOSTS: ${e}`)}if(t.username||t.password||t.pathname!=="/"||t.search)throw new jr(`Not a host name in HATCHLIGHT_ALLOWED_HOSTS: ${e}`);return t.hostname}function h4(e){if(!/^[\w.\-[\]:]+$/.test(e))return null;try{return new URL(`http://${e}`).hostname}catch{return null}}function g4(e){let[t="",r,...n]=e.split("/"),s=hm(t),o=()=>new jr(`Not an address or block in HATCHLIGHT_TRUSTED_PROXIES: ${e}`);if(!s||n.length)throw o();let i=!t.includes(":"),a=i?32:128,c=r===void 0?a:Number(r);if(r===""||!Number.isInteger(c)||c<0||c>a)throw o();return{bytes:s,prefix:i?c+96:c}}function cx(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function hm(e){let t=cx(e),r=t.indexOf("%"),n=r<0?t:t.slice(0,r),s=new Uint8Array(16);if(!n.includes(":")){let d=p4(n);if(!d)return null;return s[10]=255,s[11]=255,s.set(d,12),s}let o=n.split("::");if(o.length>2)return null;let i=(d)=>{if(!d)return[];let p=[],f=d.split(":");for(let[m,h]of f.entries())if(m===f.length-1&&h.includes(".")){let g=p4(h);if(!g)return null;p.push((g[0]??0)<<8|(g[1]??0)),p.push((g[2]??0)<<8|(g[3]??0))}else if(/^[0-9a-f]{1,4}$/i.test(h))p.push(Number.parseInt(h,16));else return null;return p},a=i(o[0]),c=i(o[1]);if(!a||!c)return null;let l=8-a.length-c.length;if(o.length===2?l<1:l!==0)return null;let u=[...a,...Array(l).fill(0),...c];for(let[d,p]of u.entries())s[d*2]=p>>8,s[d*2+1]=p&255;return s}function p4(e){let t=e.split(".");if(t.length!==4)return null;let r=[];for(let n of t){if(!/^\d{1,3}$/.test(n))return null;let s=Number(n);if(s>255)return null;r.push(s)}return r}function ax(e,t){let r=hm(e);if(!r)return!1;return t.some((n)=>{for(let s=0;s<n.prefix;s++){let o=s>>3,i=128>>(s&7);if(((r[o]??0)&i)!==((n.bytes[o]??0)&i))return!1}return!0})}function y4(e,t,r,n){let s={scheme:e.protocol.slice(0,-1),host:e.host,client:r};if(!r||!ax(r,n))return s;let o=f4(t.get("x-forwarded-proto")??void 0),i=f4(t.get("x-forwarded-host")??void 0),a=(t.get("x-forwarded-for")??"").split(",").map((l)=>l.trim()).filter(Boolean),c=r;while(a.length&&ax(c,n))c=a.pop();return{scheme:o==="https"||o==="http"?o:s.scheme,host:i??s.host,client:c}}function w4(e,t){let r=cx(e);if(r==="0.0.0.0"||r==="")return`http://127.0.0.1:${t}`;if(r==="::")return`http://[::1]:${t}`;return r.includes(":")?`http://[${r}]:${t}`:`http://${r}:${t}`}function lx(e){let t=cx(e).toLowerCase();return t==="localhost"||ax(t,vQ)}var mm,jr,d4=(e)=>(e??"").split(",").map((t)=>t.trim()).filter(Boolean),f4=(e)=>e?.split(",")[0]?.trim()||void 0,vQ;var gm=b(()=>{Pt();mm={files:20,bytes:10737418240};jr=class jr extends Error{};vQ=["127.0.0.0/8","::1/128"].map((e)=>g4(e))});function b4(e,t,r,n,s={byAddress:new yo({freeTries:20}),byNameAndAddress:new yo({freeTries:5}),byName:new yo({freeTries:50,maxDelayMs:30000}),joining:new yo({freeTries:10})}){let o=(d)=>({userAgent:d.req.header("user-agent")??null,ip:d.get("client")??null,signal:d.req.raw.signal}),i=new Map,a=(d,p)=>{let m=(i.get(d)??Promise.resolve()).catch(()=>{}).then(p),h=m.catch(()=>{});return i.set(d,h),h.then(()=>{if(i.get(d)===h)i.delete(d)}),m},c=(d,p)=>{if(typeof d!=="string")throw new O(`${p} must be text`);return d},l=async(d,p,f,m)=>{let h=`ip:${xQ(d.get("client"))}`,g=p?.trim().toLowerCase()??null,w=g===null?null:t.findUser(g),v=n.vouchesFor(a4(d),w),_=f==="joining"?[[s.joining,h]]:[[s.byAddress,h],...g?[[s.byNameAndAddress,`${g}|${h}`],...v?[]:[[s.byName,`user:${g}`]]]:[]],C=Math.max(..._.map(([P,y])=>P.wait(y)));if(C>0){let P=Math.ceil(C/1000);throw d.header("retry-after",String(P)),new be(`Too many tries. Wait ${P} seconds`,"tooManyAttempts",429,{seconds:P})}for(let[P,y]of _)P.fail(y);let k=()=>{for(let[P,y]of _)P.refund(y)};try{let P=await a(h,()=>(d.req.raw.signal.throwIfAborted(),m()));if(k(),g)s.byNameAndAddress.succeed(`${g}|${h}`);return P}catch(P){if(!(P instanceof be)||P.code==="totpRequired")k();throw P}};e.get("/api/setup",(d)=>d.json({needed:t.needsSetup()})),e.post("/api/setup",async(d)=>{let p=await r(d),f=await l(d,null,"joining",()=>t.setup({code:c(p.code,"code"),username:c(p.username,"username"),password:c(p.password,"password")},o(d)));return ru(d,f),fm(d,n.issue(f.user)),d.json(t.view(f.user,!0),201)}),e.post("/api/login",async(d)=>{let p=await r(d),f=c(p.username,"username");if(f.trim().length>32)throw new O("No such username","usernameInvalid");let m=await l(d,f,"signIn",()=>t.login({username:f,password:c(p.password,"password"),totp:typeof p.totp==="string"?p.totp:void 0},o(d)));return ru(d,m),fm(d,n.issue(m.user)),d.json(t.view(m.user,!0))}),e.post("/api/logout",(d)=>{let{user:p,sessionId:f}=d.get("viewer");if(f)t.logout(p.id,f);return c4(d),d.body(null,204)}),e.get("/api/account",(d)=>d.json(t.view(d.get("viewer").user,!0))),e.delete("/api/account/reset-notice",(d)=>(t.dismissResetNotice(d.get("viewer").user.id),d.body(null,204))),e.put("/api/account/password",async(d)=>{let p=await r(d),{user:f,sessionId:m}=d.get("viewer");return await l(d,f.username,"signIn",()=>t.changePassword(f.id,{current:c(p.current,"current"),next:c(p.next,"next")},m,d.req.raw.signal)),d.body(null,204)}),e.get("/api/account/sessions",(d)=>{let{user:p,sessionId:f}=d.get("viewer");return d.json(t.sessions(p.id,f))}),e.delete("/api/account/sessions",(d)=>{let{user:p,sessionId:f}=d.get("viewer");return t.revokeOtherSessions(p.id,f,{tokens:d.req.query("tokens")==="true"}),d.body(null,204)}),e.delete("/api/account/sessions/:id",(d)=>{let{user:p}=d.get("viewer");return t.revokeSession(p.id,d.req.param("id")),d.body(null,204)}),e.get("/api/account/tokens",(d)=>d.json(t.listApiTokens(d.get("viewer").user.id))),e.post("/api/account/tokens",async(d)=>{let p=await r(d),{user:f}=d.get("viewer");if(f.mustChangePassword)throw new be("Choose a new password before going on","passwordChangeRequired",403);if(!Array.isArray(p.scopes)||p.scopes.some((v)=>typeof v!=="string"))throw new O("scopes must be a list of scopes");let m=p.spendLimitUsd??null;if(m!==null&&typeof m!=="number")throw new O("spendLimitUsd must be a number or null");let h=p.expiresInDays;if(h!==void 0&&h!==null&&typeof h!=="number")throw new O("expiresInDays must be a number or null");let{token:g,view:w}=await l(d,f.username,"signIn",()=>t.createApiTokenConfirmed(f.id,{password:c(p.password,"password"),code:u(p.code,"code")},{name:c(p.name,"name"),scopes:p.scopes,spendLimitUsd:m,expiresInDays:h},d.req.raw.signal));return d.json({...w,token:g},201)}),e.delete("/api/account/tokens/:id",(d)=>(t.revokeApiToken(d.get("viewer").user.id,d.req.param("id")),d.body(null,204))),e.post("/api/account/totp",(d)=>d.json(t.startTotp(d.get("viewer").user.id)));let u=(d,p)=>d===void 0||d===null?void 0:c(d,p);e.put("/api/account/totp",async(d)=>{let p=await r(d),{user:f}=d.get("viewer");return await l(d,f.username,"signIn",()=>t.enableTotp(f.id,{secret:c(p.secret,"secret"),code:c(p.code,"code"),password:c(p.password,"password"),current:u(p.current,"current")},d.req.raw.signal)),d.body(null,204)}),e.delete("/api/account/totp",async(d)=>{let p=await r(d),{user:f}=d.get("viewer");return await l(d,f.username,"signIn",()=>t.disableTotp(f.id,{password:c(p.password,"password"),code:u(p.code,"code")},d.req.raw.signal)),d.body(null,204)}),e.get("/api/password-resets/:token",(d)=>{let p=t.passwordResetFor(d.req.param("token"));if(!p)throw new Ee("This link has expired or was already used","resetInvalid");return d.json(p)}),e.post("/api/password-resets/:token",async(d)=>{let p=await r(d);return await l(d,null,"joining",()=>t.usePasswordReset(d.req.param("token"),c(p.password,"password"),d.req.raw.signal)),d.body(null,204)}),e.get("/api/invites/:token",(d)=>{let p=t.inviteFor(d.req.param("token"));if(!p)throw new Ee("This invite has expired or was already used","inviteInvalid");return d.json({role:p.role,expiresAt:p.expiresAt})}),e.post("/api/invites/:token/accept",async(d)=>{let p=await r(d),f=await l(d,null,"joining",()=>t.acceptInvite(d.req.param("token"),{username:c(p.username,"username"),password:c(p.password,"password")},o(d)));return ru(d,f),fm(d,n.issue(f.user)),d.json(t.view(f.user,!0),201)}),e.get("/api/invites",(d)=>d.json(t.invites())),e.post("/api/invites",async(d)=>{let p=t.createInvite(d.get("viewer").user,_Q(await r(d)));return d.json(p,201)}),e.delete("/api/invites/:id",(d)=>(t.deleteInvite(d.req.param("id")),d.body(null,204))),e.get("/api/users",(d)=>d.json(t.users())),e.patch("/api/users/:id",async(d)=>{let p=await r(d),f={};if(p.role!==void 0)f.role=v4(p.role);for(let m of["canUsePaid","canTrain","disabled"]){if(p[m]===void 0)continue;if(typeof p[m]!=="boolean")throw new O(`${m} must be true or false`);f[m]=p[m]}if(p.monthlyLimitUsd!==void 0)f.monthlyLimitUsd=_4(p.monthlyLimitUsd);if(p.displayName!==void 0)f.displayName=c(p.displayName,"displayName");return d.json(t.updateUser(d.get("viewer").user,d.req.param("id"),f))}),e.get("/api/users/:id/tokens",(d)=>d.json(t.listApiTokensOf(d.get("viewer").user,d.req.param("id")))),e.delete("/api/users/:id/tokens/:token",(d)=>(t.revokeApiTokenOf(d.get("viewer").user,d.req.param("id"),d.req.param("token")),d.body(null,204))),e.post("/api/users/:id/password",(d)=>d.json(t.createPasswordReset(d.get("viewer").user,d.req.param("id")),201))}function v4(e){if(!Yu.includes(e))throw new O("role must be owner, admin or member");return e}function _4(e){if(e===null)return null;if(typeof e!=="number"||!Number.isFinite(e)||e<0)throw new O("monthlyLimitUsd must be zero or more, or null");return e}function _Q(e){return{role:v4(e.role??"member"),canUsePaid:e.canUsePaid===!0,canTrain:e.canTrain===!0,monthlyLimitUsd:_4(e.monthlyLimitUsd??null)}}function xQ(e){if(!e)return"unknown";let t=hm(e);if(!t)return e;if(t.slice(0,10).every((s)=>s===0)&&t[10]===255&&t[11]===255)return[...t.slice(12)].join(".");let n=[];for(let s=0;s<8;s+=2)n.push(((t[s]??0)<<8|(t[s+1]??0)).toString(16));return`${n.join(":")}::/64`}var x4=b(()=>{Pt();ix();gm()});import{createHmac as SQ,timingSafeEqual as $Q}from"crypto";import{chmodSync as kQ,existsSync as TQ,readFileSync as PQ,writeFileSync as EQ}from"fs";class ux{key;constructor(e){this.key=e}issue(e){let t=Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64url");return`${e.id}.${t}.${this.sign(e,t)}`}vouchesFor(e,t){if(!t)return!1;let[r,n,s,...o]=e?.split(".")??[];if(!r||!n||!s||o.length||r!==t.id)return!1;let i=Buffer.from(this.sign(t,n)),a=Buffer.from(s);return i.length===a.length&&$Q(i,a)}sign(e,t){return SQ("sha256",this.key).update(`${e.id}
|
|
137
|
+
${e.username}
|
|
138
|
+
${t}`).digest("base64url")}}function S4(e){if(TQ(e)){let r=PQ(e);if(r.byteLength>=32)return new Uint8Array(r)}let t=crypto.getRandomValues(new Uint8Array(32));return EQ(e,t,{mode:384}),kQ(e,384),t}var dx=()=>{};function OQ(e){return e.replace(/:\d+$/,"")}function LQ(e,t){let r=e?.match(/^bytes=(\d*)-(\d*)$/);if(!r||r[1]===""&&r[2]==="")return null;if(r[1]===""){let o=Math.min(Number(r[2]),t);return o===0?"unsatisfiable":{start:t-o,end:t-1}}let n=Number(r[1]),s=r[2]===""?t-1:Math.min(Number(r[2]),t-1);return n>=t||n>s?"unsatisfiable":{start:n,end:s}}function mx(e,t,r){let n={"content-type":r,"accept-ranges":"bytes","cache-control":"private, max-age=31536000, immutable","x-content-type-options":"nosniff","content-security-policy":"sandbox"},s=LQ(e.req.header("range"),t.size);if(s==="unsatisfiable")return new Response(null,{status:416,headers:{...n,"content-range":`bytes */${t.size}`}});if(s)return new Response(t.slice(s.start,s.end+1),{status:206,headers:{...n,"content-length":String(s.end-s.start+1),"content-range":`bytes ${s.start}-${s.end}/${t.size}`}});return new Response(t,{headers:{...n,"content-length":String(t.size)}})}function A4(e){return async(t,r)=>{let n=t.req.header("content-length");if(n!==void 0&&!t.req.header("transfer-encoding")&&Number(n)>e.maxSize)return e.onError(t);await r()}}function R4(e){let{service:t,engine:r,models:n}=e,s=e.server,o=s?e.accounts:void 0;if(s&&!o)throw Error("Server mode needs accounts");let i=e.resolveUser??(s?(y)=>{let{user:x,apiToken:T}=y.get("viewer");return{userId:x.id,tokenId:T?.ref??null}}:()=>As),a=new J0;if(a.use("*",async(y,x)=>{await x();let T=y.res.headers;for(let[I,j]of Object.entries(NQ))if(!T.has(I))T.set(I,j);if(y.get("https"))T.set("strict-transport-security","max-age=31536000")}),a.use("*",s?async(y,x)=>{let T=y4(new URL(y.req.url),y.req.raw.headers,px(y),s.trustedProxies),I=h4(T.host);if(!I||!(s.allowedHosts.includes(I)||T4.includes(I)))return y.json({error:"Forbidden host"},403);y.set("https",T.scheme==="https"),y.set("client",T.client);let j=y.req.header("origin"),se=new URL(`${T.scheme}://${T.host}`).origin;if(j){if(j!==se&&!e.allowedOrigins?.includes(j))return y.json({error:"Forbidden origin"},403)}else if(zQ.has(y.req.method)&&y.req.header("sec-fetch-site")!=="same-origin"&&!(/^Bearer\s/i.test(y.req.header("authorization")??"")&&y.req.header("cookie")===void 0))return y.json({error:"Missing origin"},403);await x()}:async(y,x)=>{let T=px(y);if(T!==null&&!lx(T))return y.json({error:"Forbidden address"},403);let I=new URL(y.req.url).host;if(!T4.includes(OQ(I)))return y.json({error:"Forbidden host"},403);let j=y.req.header("origin");if(j&&j!==`http://${I}`&&!e.allowedOrigins?.includes(j))return y.json({error:"Forbidden origin"},403);await x()}),a.get("/api/health",(y)=>y.json({ok:!0})),a.get("/api/server",(y)=>y.json({mode:s?"server":"personal",secure:y.get("https")===!0})),a.use("/api/*",async(y,x)=>{let T=new URL(y.req.url).pathname;if(["/api/loras","/api/checkpoints","/api/assets"].includes(T))return x();return cm({maxSize:E4,onError:(I)=>I.json({error:"The request is too large"},413)})(y,x)}),o&&e.mcp&&s){let y=e.mcp,x=new yo({freeTries:10}),T=new Map;a.all("/mcp",cm({maxSize:E4,onError:(I)=>I.json({error:"The request is too large"},413)}),async(I)=>{if(I.req.method!=="POST")return I.json({error:"Use POST"},405,{allow:"POST"});let j=I.get("client")??px(I)??"unknown",se=x.wait(j);if(se>0)throw new be("Too many wrong tokens. Try again later","tooManyAttempts",429,{seconds:Math.ceil(se/1000)});let we=I.req.header("authorization")?.match(/^Bearer\s+(\S+)$/i)?.[1],de=we?o.resolveApiToken(we):null;if(!we||!de?.apiToken)throw x.fail(j),I.header("www-authenticate",'Bearer realm="hatchlight"'),new be("An API token is needed: Authorization: Bearer <token>","signInRequired",401);if(de.user.mustChangePassword)throw new be("Choose a new password before going on","passwordChangeRequired",403);let qe=de.apiToken.ref??de.apiToken.id,Ye=T.get(qe)??0;if(Ye>=CQ)throw new be("This token has too many calls under way. Try again shortly","tooManyAttempts",429,{seconds:5});let Fe;try{Fe=JSON.parse(await I.req.text())}catch{return I.json(I4(-32700,"The body is not JSON"),400)}if(Array.isArray(Fe))return I.json(I4(-32600,"Batches are not accepted: send one message"),400);T.set(qe,Ye+1);try{return await y(I.req.raw,{token:we,origin:s.publicOrigin,allowPaid:de.apiToken.scopes.includes("paid")&&wi(de.user)},Fe)}finally{let Wt=(T.get(qe)??1)-1;if(Wt>0)T.set(qe,Wt);else T.delete(qe)}})}a.onError((y,x)=>{if(x.req.raw.signal.aborted)return new Response(null,{status:499});let T=(I)=>({error:I.message,...I.code&&{code:I.code,params:I.params}});if(y instanceof O)return x.json(T(y),400);if(y instanceof be){if(y.status===503)x.header("retry-after","5");return x.json(T(y),y.status)}if(y instanceof Ee)return x.json(T(y),404);if(y instanceof le&&y.code){if(AQ.has(y.code))return x.json(T(y),502);return console.error(y),x.json(T(y),500)}return console.error(y),x.json({error:"Internal error"},500)});let c=async(y)=>{let x=await y.req.json().catch(()=>null);if(!x||typeof x!=="object"||Array.isArray(x))throw new O("Expected a JSON object");return x};if(o)a.use("/api/*",u4(o)),b4(a,o,c,new ux(e.deviceKey??crypto.getRandomValues(new Uint8Array(32))));let l=(y,x)=>s?e.paidRefusal?.(i(y),x)??null:null;a.get("/api/models",async(y)=>{let x=t.listModels(),T=s?y.get("viewer").apiToken:null;if(!T||T.scopes.includes("paid"))return y.json(x);let I=new Set((await t.listProviders(i(y))).filter((j)=>j.requiresKey).map((j)=>j.id));return y.json(x.filter((j)=>!I.has(j.providerId)))}),a.get("/api/providers",async(y)=>{let x=await t.listProviders(i(y));if(!s)return y.json(x);let T=l(y,"personal")!==null,I=l(y,"server")!==null;return y.json(x.map((j)=>j.requiresKey&&j.keys?{...j,hasKey:!T&&(j.keys.personal||j.keys.server&&!I)}:j))});let u=e.agents;if(u)a.get("/api/agents",async(y)=>y.json(await u.status())),a.put("/api/agents/claude-desktop",async(y)=>{if(s)return fx(y);let x=await y.req.json().catch(()=>null),T=x?.spendLimitUsd??null;if(typeof x?.allowPaid!=="boolean"||T!==null&&!(typeof T==="number"&&Number.isFinite(T)&&T>=0))throw new O("allowPaid must be true or false, and spendLimitUsd zero or more, or null");return await u.connectClaudeDesktop({allowPaid:x.allowPaid,spendLimitUsd:x.allowPaid?T:null}),y.body(null,204)}),a.delete("/api/agents/claude-desktop",async(y)=>{if(s)return fx(y);return await u.disconnectClaudeDesktop(),y.body(null,204)});a.get("/api/keys/lost",(y)=>y.json({lost:e.keysLost?.({userId:i(y).userId,owner:!s||y.get("viewer").user.role==="owner"})??!1})),a.delete("/api/keys/lost",(y)=>(e.dismissKeysLost?.(i(y).userId),y.body(null,204)));let d=(y)=>s?rs:i(y);if(a.put("/api/providers/:id/key",async(y)=>{let{key:x}=await c(y);if(typeof x!=="string")throw new O("Missing key");return await t.setProviderKey(d(y),y.req.param("id"),x),y.body(null,204)}),a.delete("/api/providers/:id/key",async(y)=>(await t.deleteProviderKey(d(y),y.req.param("id")),y.body(null,204))),s){let y=(x)=>{let T=l(x,"personal");if(T)throw Ai(T)};a.put("/api/account/keys/:id",async(x)=>{y(x);let{key:T}=await c(x);if(typeof T!=="string")throw new O("Missing key");return await t.setProviderKey(i(x),x.req.param("id"),T),x.body(null,204)}),a.delete("/api/account/keys/:id",async(x)=>(await t.deleteProviderKey(i(x),x.req.param("id")),x.body(null,204)))}a.get("/api/sessions",async(y)=>y.json(await t.listSessions(i(y)))),a.get("/api/sessions/:id",async(y)=>y.json(await t.getSession(i(y),y.req.param("id")))),a.delete("/api/sessions/:id",async(y)=>(e.assistant?.forget(i(y),y.req.param("id")),await t.deleteSession(i(y),y.req.param("id")),y.body(null,204))),a.post("/api/turns",async(y)=>{let x=await c(y);if(!Array.isArray(x.modelIds)||x.modelIds.some((I)=>typeof I!=="string"))throw new O("modelIds must be a list of model ids");if(x.sessionId!=null&&typeof x.sessionId!=="string")throw new O("sessionId must be a string");if(s){let I=new Map((await t.listProviders(i(y))).map((se)=>[se.id,se])),j=new Map(t.listModels().map((se)=>[se.id,se]));for(let se of x.modelIds){let we=I.get(j.get(se)?.providerId??"");if(!we?.requiresKey)continue;let de=l(y,we.keys?.personal?"personal":"server");if(de)throw Ai(de)}}let T=await t.createTurn(i(y),x);return y.json(T,201)}),a.get("/api/jobs/:id/preview",(y)=>{let{data:x,mime:T}=t.jobPreview(i(y),y.req.param("id"));return new Response(x,{headers:{"content-type":T,"cache-control":"no-store"}})}),a.post("/api/jobs/:id/cancel",async(y)=>(await t.cancelJob(i(y),y.req.param("id")),y.body(null,204))),a.post("/api/jobs/:id/retry",async(y)=>(await t.retryJob(i(y),y.req.param("id")),y.body(null,204)));let p=new Set;a.post("/api/assets",async(y,x)=>{if(!o)return x();let{userId:T}=i(y),I=Number(y.req.header("content-length")??0)||0,j=o.storageRefusal(T,I);if(j)throw j;if(p.has(T))throw new be("Another of your uploads is still under way","uploadBusy",409);p.add(T);try{await x()}finally{p.delete(T)}},cm({maxSize:RQ,onError:(y)=>y.json({error:"The image is larger than 20 MB"},413)}),async(y)=>{let x=new Uint8Array(await y.req.arrayBuffer());if(x.byteLength===0)throw new O("Empty upload");let T=o?.storageRefusal(i(y).userId,x.byteLength);if(T)throw T;return y.json(await t.uploadAsset(i(y),x),201)}),a.delete("/api/assets/:id",async(y)=>(await t.deleteAsset(i(y),y.req.param("id")),y.body(null,204))),a.get("/api/assets/:id",async(y)=>{let{asset:x,blob:T}=await t.getAssetFile(i(y),y.req.param("id"));return mx(y,T,x.mime)});let f=(y)=>!s||["owner","admin"].includes(y.get("viewer").user.role);a.get("/api/local-models",async(y)=>{let x=await n.listWithMemory();if(f(y))return y.json(x);return y.json({...x,disk:{...x.disk,path:"",changeable:!1,moving:x.disk.moving&&{...x.disk.moving,to:""},moveError:null}})}),a.post("/api/prompts/improve",async(y)=>{if(!e.improvePrompt)throw new Ee("No writer here");let x=await c(y),{prompt:T,modelIds:I,editing:j,language:se}=x;if(typeof T!=="string"||!T.trim())throw new O("prompt must be some text");if(T.length>$4)throw new O(`prompt must be at most ${$4} characters`);if(!Array.isArray(I)||I.length>IQ||!I.every((de)=>typeof de==="string"))throw new O("modelIds must be a list of model ids");if(se!==void 0&&(typeof se!=="string"||!/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(se)))throw new O("language must be a language code such as pt-BR");let we=await e.improvePrompt(i(y),{prompt:T,modelIds:I,editing:j===!0,...typeof se==="string"&&{language:se}},y.req.raw.signal);return y.json({prompt:we})}),a.post("/api/local-models/:id/install",async(y)=>{let T=(await y.req.json().catch(()=>({})))?.variant;if(T!=null&&typeof T!=="string")throw new O("variant must be a string");return await n.install(y.req.param("id"),T??void 0),y.body(null,202)}),a.post("/api/local-models/:id/cancel",async(y)=>(await n.cancel(y.req.param("id")),y.body(null,204))),a.get("/api/settings",async(y)=>{if(!e.settings)throw new Ee("No settings here");return y.json(await e.settings.get(i(y)))}),a.put("/api/settings",async(y)=>{if(!e.settings)throw new Ee("No settings here");let x=await c(y);if(x.translateWith!==void 0&&!xc(x.translateWith))throw new O(`translateWith must be one of ${Hy.join(", ")}`);if(x.improveWith!==void 0&&!Rs(x.improveWith))throw new O(`improveWith must be one of ${td.join(", ")}`);if(x.assistantWith!==void 0&&!Rs(x.assistantWith))throw new O(`assistantWith must be one of ${td.join(", ")}`);return y.json(await e.settings.set(i(y),{...Rs(x.assistantWith)&&{assistantWith:x.assistantWith},...xc(x.translateWith)&&{translateWith:x.translateWith},...Rs(x.improveWith)&&{improveWith:x.improveWith}}))}),a.post("/api/local-models/location",async(y)=>{if(s)return fx(y);let x=await c(y);if(typeof x.path!=="string"||!x.path.trim())throw new O("path must name a folder");return await(e.moveModels??((I)=>n.relocate(I)))(x.path),y.body(null,202)}),a.delete("/api/local-models/:id",async(y)=>(await n.remove(y.req.param("id")),y.body(null,204)));let m=new Set;a.get("/api/loras",async(y)=>y.json(await n.loras.list())),a.post("/api/loras",A4({maxSize:ab,onError:(y)=>y.json({error:"This file is too large to be a LoRA",code:"loraTooLarge",params:{}},413)}),async(y)=>{let x=y.req.query("name")??"";if(!/\.safetensors$/i.test(x))throw new O("Choose a .safetensors file","loraUnreadable");let T=y.req.raw.body;if(!T)throw new O("Empty upload","loraUnreadable");let I=o?y.get("viewer").user:null,j=e.loraQuota??mm,se=I&&o&&!["owner","admin"].includes(I.role),we=()=>new be("You added as many LoRAs as this server allows","loraQuotaReached",403,{files:j.files,maxBytes:j.bytes});if(!se||!I||!o){let de=await n.loras.add(T,x);if(I)o?.recordLoraUpload(I.id,de.id,de.size);return y.json(de,201)}if(m.has(I.id))throw new be("Another of your LoRAs is still uploading","loraUploadBusy",409);m.add(I.id);try{let de=o.loraUsage(I.id,new Set((await n.loras.list()).map((Wt)=>Wt.id))),qe=j.bytes-de.bytes,Ye=Number(y.req.header("content-length")??0)||0;if(de.files>=j.files||Ye>qe)throw we();let Fe=await n.loras.add(T,x,{maxBytes:qe,error:we});return o.recordLoraUpload(I.id,Fe.id,Fe.size),y.json(Fe,201)}finally{m.delete(I.id)}}),a.delete("/api/loras/:id",async(y)=>(await n.loras.remove(y.req.param("id")),o?.forgetLoraUpload(y.req.param("id")),y.body(null,204))),a.get("/api/checkpoints",async(y)=>y.json(await n.checkpoints.list())),a.post("/api/checkpoints",A4({maxSize:Hc,onError:(y)=>y.json({error:"This file is too large",code:"checkpointTooLarge",params:{}},413)}),async(y)=>{let x=y.req.query("name")??"";if(!/\.safetensors$/i.test(x))throw new O("Choose a .safetensors file","checkpointUnreadable");let T=y.req.raw.body;if(!T)throw new O("Empty upload","checkpointUnreadable");return y.json(await n.checkpoints.add(T,x),201)}),a.patch("/api/checkpoints/:id",async(y)=>{let x=await c(y),T={};for(let I of["name","steps","cfgScale","clipSkip"])if(I in x)T[I]=x[I];return y.json(await n.checkpoints.update(y.req.param("id"),T))}),a.delete("/api/checkpoints/:id",async(y)=>(await n.checkpoints.remove(y.req.param("id")),y.body(null,204)));let h=0,g=()=>{if(!e.trainer)throw new Ee("No trainer here");return e.trainer},w=(y)=>["owner","admin"].includes(y.get("viewer").user.role),v=(y,x)=>!s||x.startedBy?.userId===i(y).userId||w(y),_=(y,x)=>x.training&&!v(y,x.training)?{...x,training:null}:x,C=async(y)=>{let x=(await g().status()).training;if(x&&!v(y,x))throw new be("Only who started this training can stop it","forbidden",403)};a.get("/api/trainer",async(y)=>y.json(_(y,await g().status()))),a.post("/api/trainer/install",async(y)=>(await g().install(),y.body(null,202))),a.post("/api/trainer/install/cancel",(y)=>(g().cancelInstall(),y.body(null,204))),a.delete("/api/trainer",async(y)=>(await g().remove(),y.body(null,204))),a.post("/api/trainings",async(y)=>{let x=await c(y),{name:T,trigger:I,steps:j,pictures:se,consent:we}=x;if(we!==!0)throw new O("Confirm the pictures are yours to use, and that anyone in them agreed","trainingNeedsConsent");if(typeof T!=="string"||typeof I!=="string")throw new O("name and trigger must be text");if(typeof j!=="number")throw new O("steps must be a number");if(!Array.isArray(se)||se.length>200)throw new O("pictures must be a list of pictures");if(await g().assertCanTrain(),h>0)throw new O("The trainer is busy","trainerBusy");let de=[];for(let Fe of se){let{assetId:Wt,caption:di}=Fe??{};if(typeof Wt!=="string"||di!=null&&typeof di!=="string")throw new O("Each picture needs an assetId and may have a caption");let{asset:Fa,blob:pi}=await t.getAssetFile(i(y),Wt),Va=P4[Fa.mime];if(!Va)throw new O("Only PNG, JPEG and WebP pictures can be trained on","uploadType");de.push({data:new Uint8Array(await pi.arrayBuffer()),extension:Va,caption:typeof di==="string"?di.slice(0,500):""})}let qe=s?y.get("viewer").user:null,Ye=await g().train({name:T,trigger:I,steps:j,pictures:de,startedBy:qe?{userId:qe.id,name:qe.displayName}:void 0});return y.json(Ye,202)}),a.post("/api/trainings/cancel",async(y)=>(await C(y),g().cancelTraining(),y.body(null,204))),a.post("/api/trainings/finish",async(y)=>(await C(y),g().finishTraining(),y.body(null,204))),a.get("/api/trainings/:id/samples/:step",async(y)=>{let x=(await g().status()).training;if(!x||!v(y,x))throw new Ee("Sample not found");let T=g().sampleFile(y.req.param("id"),Number(y.req.param("step"))),I=T?Bun.file(T):null;if(!I||!await I.exists())throw new Ee("Sample not found");return mx(y,I,"image/png")}),a.get("/api/captioner",async(y)=>y.json({ready:await e.captioner?.ready()??!1})),a.post("/api/captions",async(y)=>{let{assetId:x}=await c(y);if(typeof x!=="string")throw new O("assetId must be text");let T=e.captioner;if(!T||!await T.ready())throw new O("Install Qwen2.5-VL in Models to describe pictures","captionNeedsModel");if((await e.trainer?.status())?.training?.state==="running")throw new O("The trainer is busy","trainerBusy");let{asset:I,blob:j}=await t.getAssetFile(i(y),x);if(!P4[I.mime])throw new O("Only PNG, JPEG and WebP pictures can be trained on","uploadType");h++;try{let se=await T.caption({data:Buffer.from(await j.arrayBuffer()).toString("base64"),mimeType:I.mime},y.req.raw.signal);return y.json({caption:se})}finally{h--}}),a.get("/api/local-models/:id/demos/:index",async(y)=>{let x=Number(y.req.param("index"));if(!Number.isInteger(x))throw new Ee("Demo not found");let T=y.req.query("size")??"original";if(!fI(T))throw new O("Unknown demo size");let I=await n.demo(y.req.param("id"),x,T);return mx(y,I.blob,I.mime)}),a.get("/api/gallery",async(y)=>{let x=Number(y.req.query("limit")??60),T=y.req.query("before"),I=y.req.query("beforeId");if(!Number.isInteger(x)||x<1||x>200)throw new O("limit must be between 1 and 200");if(T==null!==(I==null)||Number.isNaN(Number(T??0)))throw new O("before and beforeId must be given together");return y.json(await t.listGallery(i(y),{limit:x,before:T!=null&&I!=null?{createdAt:Number(T),id:I}:void 0,query:y.req.query("query")||void 0}))});let k=()=>{if(!e.assistant)throw new Ee("No assistant here");return e.assistant},P=(y)=>{if(y===void 0)return;if(typeof y!=="string"||!/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(y))throw new O("language must be a language code such as pt-BR");return y};return a.get("/api/assistant",async(y)=>y.json({brain:e.assistantBrain?await e.assistantBrain(i(y)):null})),a.post("/api/assistant/messages",async(y)=>{let x=await c(y),{text:T,sessionId:I}=x;if(typeof T!=="string"||!T.trim())throw new O("text must be some words");if(T.length>k4)throw new O(`text must be at most ${k4} characters`);if(I!==void 0&&typeof I!=="string")throw new O("sessionId must be a session id");let j=P(x.language);return y.json(await k().send(i(y),{text:T,...I!==void 0&&{sessionId:I},...j&&{language:j}}))}),a.get("/api/sessions/:id/assistant",async(y)=>{let x=i(y);return await t.getSession(x,y.req.param("id")),y.json(await k().view(x,y.req.param("id")))}),a.post("/api/sessions/:id/assistant/stop",async(y)=>(k().stop(i(y),y.req.param("id")),y.body(null,204))),a.post("/api/sessions/:id/assistant/answers",async(y)=>{let x=await c(y),{entryId:T,approve:I}=x;if(typeof T!=="string"||typeof I!=="boolean")throw new O("entryId and approve (true or false) are needed");let j=i(y);return await t.getSession(j,y.req.param("id")),await k().answer(j,y.req.param("id"),T,I,P(x.language)),y.body(null,202)}),a.get("/api/events",(y)=>{let{userId:x}=i(y);return tx(y,async(T)=>{let I=(Fe)=>void T.writeSSE({event:Fe.type,data:JSON.stringify(Fe)}),j=r.subscribe((Fe,Wt)=>{if(Fe===x)I(Wt)}),se=f(y),we=n.subscribe((Fe)=>I(Fe.type==="models.moving"&&!se?{...Fe,to:""}:Fe)),de=e.trainer?.subscribe((Fe)=>{let Wt=_(y,Fe.trainer);I({...Fe,trainer:Wt})}),qe=e.assistant?.subscribe((Fe,Wt)=>{if(Fe===x)I(Wt)}),Ye=()=>{j(),we(),de?.(),qe?.()};T.onAbort(Ye),await T.writeSSE({event:"ready",data:"{}"});while(!T.aborted&&!T.closed)await T.sleep(15000),await T.writeSSE({event:"ping",data:"{}"});Ye()})}),a.all("/api/*",(y)=>y.json({error:"Not found"},404)),a}var $4=1000,IQ=50,k4=4000,AQ,T4,RQ=20971520,P4,E4=1048576,CQ=4,I4=(e,t)=>({jsonrpc:"2.0",error:{code:e,message:t},id:null}),zQ,MQ,NQ,px=(e)=>e.env?.peer??null,fx=(e)=>e.json({error:"Not available when Hatchlight runs as a server",code:"notOnServer"},403);var C4=b(()=>{Pt();JN();QN();t4();x4();ix();dx();gm();AQ=new Set(["connectionLost","improveFailed","localAssistantUnavailable","noConnection","providerBusy"]),T4=["localhost","127.0.0.1","[::1]"],P4={"image/png":"png","image/jpeg":"jpg","image/webp":"webp"};zQ=new Set(["POST","PUT","PATCH","DELETE"]),MQ=["default-src 'self'","script-src 'self'","style-src 'self'","img-src 'self' data: blob:","media-src 'self' blob:","font-src 'self' data:","connect-src 'self' ipc: http://ipc.localhost","object-src 'none'","base-uri 'none'","form-action 'self'","frame-ancestors 'none'"].join("; "),NQ={"content-security-policy":MQ,"x-frame-options":"DENY","referrer-policy":"no-referrer","x-content-type-options":"nosniff","permissions-policy":"camera=(), microphone=(), geolocation=(), payment=(), usb=()"}});function bs(e,t){return new Promise((r,n)=>{if(t.aborted)return n(t.reason);let s=setTimeout(()=>{t.removeEventListener("abort",o),r()},e),o=()=>{clearTimeout(s),n(t.reason)};t.addEventListener("abort",o,{once:!0})})}function vs(e,t){return`data:${t};base64,${Buffer.from(e).toString("base64")}`}async function gn(e){let t=await e.text().catch(()=>"");try{let r=JSON.parse(t),n=r.detail??r.error?.message??r.error??r.message;if(typeof n==="string")return n;if(n)return JSON.stringify(n)}catch{}return t.slice(0,300)||`HTTP ${e.status}`}async function tr(e,t,r,n){try{return await e(t,r)}catch(s){let o=s,i=o.code??o.cause?.code;if(!r.signal?.aborted&&typeof i==="string"&&DQ.has(i))throw new le(`Could not reach ${n}`,"noConnection",{provider:n},{});throw s}}async function ur(e,t,r=jQ){let n=await gn(e);if(r.includes(e.status))return new le(n,"providerBusy",{provider:t},{afterMs:UQ(e)});return new le(n)}function Ra(e){return{type:"failed",error:e.message,...e.code&&{code:e.code,params:e.params},...e.retry&&{retry:e.retry}}}function UQ(e){let t=e.headers.get("retry-after");if(!t)return;let r=Number(t);if(Number.isFinite(r))return Math.max(0,r*1000);let n=Date.parse(t);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}var DQ,jQ,Aa;var wo=b(()=>{Pt();DQ=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ConnectionRefused","FailedToOpenSocket"]);jQ=[429,503],Aa=[429]});function hx(e,t,r){return{id:`fal/${e}`,providerId:"fal",providerModelId:e,name:t,media:"image",...r}}function Ca(e){let{image:t}=e;return{spec:hx(e.text,e.name,{media:"video",operations:t?["generate","edit"]:["generate"],capabilities:{aspectRatios:e.ratios,seed:e.seed,maxCount:1,maxReferenceImages:t?1:0,durations:e.durations},pricing:{usdPerSecond:e.usdPerSecond}}),endpoint:(r)=>t&&r.length>0?t.endpoint:e.text,input:(r,n)=>{let[s]=n,o=t&&s;return{prompt:r.prompt,...r.durationSeconds!=null&&{duration:e.duration(r.durationSeconds)},...r.aspectRatio&&(!o||t.takesRatio)&&{aspect_ratio:r.aspectRatio},...r.seed!=null&&{seed:r.seed},...o&&{[t.field]:vs(s.data,s.mime)},...r.extras}}}}function z4(e,t){return{spec:hx(e,t,{operations:["generate"],capabilities:{aspectRatios:Object.keys(O4),seed:!0,maxCount:4,maxReferenceImages:0,englishPrompts:!0}}),endpoint:()=>e,input:(r)=>({prompt:r.prompt,num_images:r.count,output_format:"png",...r.aspectRatio&&{image_size:O4[r.aspectRatio]},...r.seed!=null&&{seed:r.seed},...r.extras})}}function Oa(e){if(typeof e!=="string"||!e.startsWith(`${N4}/`))throw Error("fal returned an unexpected request URL");return e}class ym{fetch;pollMs;id="fal";name="fal";keyEnv="FAL_KEY";requiresKey=!0;resumable=!0;constructor(e=globalThis.fetch,t=1000){this.fetch=e;this.pollMs=t}listModels(){return M4.map((e)=>e.spec)}headers(e){return{authorization:`Key ${e.apiKey}`}}async submit(e,t){let r=M4.find((o)=>o.spec.id===e.model.id);if(!r)throw Error(`Unknown fal model: ${e.model.id}`);let n=await tr(this.fetch,`${N4}/${r.endpoint(e.references)}`,{method:"POST",headers:{...this.headers(t),"content-type":"application/json"},body:JSON.stringify(r.input(e.params,e.references)),signal:t.signal},this.name);if(!n.ok)throw await ur(n,this.name);let s=await n.json();return{statusUrl:Oa(s.status_url),responseUrl:Oa(s.response_url),cancelUrl:Oa(s.cancel_url)}}async*events(e,t){let r={headers:this.headers(t),signal:t.signal},n=Oa(e.statusUrl),s=0;for(;;){let c=await this.fetch(n,r).catch((u)=>{if(t.signal.aborted)throw u;return null});if(!c||c.status===429||c.status>=500){if(++s>BQ){yield{type:"failed",error:c?await gn(c):"Lost the connection to fal",code:"connectionLost",params:{provider:this.name}};return}await bs(this.pollMs*2**s,t.signal);continue}if(s=0,!c.ok){yield{type:"failed",error:await gn(c)};return}let l=await c.json();if(l.status==="COMPLETED"){if(l.error){yield{type:"failed",error:l.error};return}break}yield{type:"progress",...l.status==="IN_QUEUE"?{message:`In queue (position ${l.queue_position??0})`,stage:"queued",position:l.queue_position??0}:{message:"Generating",stage:"generating"}},await bs(this.pollMs,t.signal)}let o=await this.fetch(Oa(e.responseUrl),r);if(!o.ok){yield{type:"failed",error:await gn(o)};return}let i=await o.json(),a=i.video?[i.video]:i.images??[];if(a.length===0){yield{type:"failed",error:"fal returned no result"};return}yield{type:"completed",outputs:a.map((c)=>({url:c.url,mime:i.video&&!c.content_type?.startsWith("video/")?"video/mp4":c.content_type}))}}async cancel(e,t){await this.fetch(Oa(e.cancelUrl),{method:"PUT",headers:this.headers(t),signal:t.signal})}}var N4="https://queue.fal.run",BQ=5,qQ,O4,M4;var gx=b(()=>{wo();qQ=["21:9","16:9","3:2","4:3","5:4","1:1","4:5","3:4","2:3","9:16"],O4={"1:1":"square_hd","4:3":"landscape_4_3","16:9":"landscape_16_9","3:4":"portrait_4_3","9:16":"portrait_16_9"};M4=[z4("fal-ai/flux/schnell","FLUX.1 schnell"),z4("fal-ai/flux/dev","FLUX.1 dev"),{spec:hx("fal-ai/nano-banana","Nano Banana",{operations:["generate","edit"],capabilities:{aspectRatios:qQ,seed:!0,maxCount:4,maxReferenceImages:4}}),endpoint:(e)=>e.length>0?"fal-ai/nano-banana/edit":"fal-ai/nano-banana",input:(e,t)=>({prompt:e.prompt,num_images:e.count,output_format:"png",...e.aspectRatio&&{aspect_ratio:e.aspectRatio},...e.seed!=null&&{seed:e.seed},...t.length>0&&{image_urls:t.map((r)=>vs(r.data,r.mime))},...e.extras})},Ca({name:"Veo 3.1 Fast",text:"fal-ai/veo3.1/fast",ratios:["16:9","9:16"],durations:[4,6,8],duration:(e)=>`${e}s`,seed:!0,usdPerSecond:0.15}),Ca({name:"Veo 3",text:"fal-ai/veo3",image:{endpoint:"fal-ai/veo3/image-to-video",field:"image_url",takesRatio:!0},ratios:["16:9","9:16"],durations:[4,6,8],duration:(e)=>`${e}s`,seed:!0,usdPerSecond:0.4}),Ca({name:"Kling 2.5 Turbo Pro",text:"fal-ai/kling-video/v2.5-turbo/pro/text-to-video",image:{endpoint:"fal-ai/kling-video/v2.5-turbo/pro/image-to-video",field:"image_url",takesRatio:!1},ratios:["16:9","9:16","1:1"],durations:[5,10],duration:String,seed:!1,usdPerSecond:0.07}),Ca({name:"Kling 4",text:"kling/v4/text-to-video",image:{endpoint:"kling/v4/image-to-video",field:"start_image_url",takesRatio:!1},ratios:["16:9","9:16","1:1","21:9"],durations:[5,10,15],duration:Number,seed:!1,usdPerSecond:0.235}),Ca({name:"Hailuo H3",text:"minimax/h3/text-to-video",ratios:["21:9","16:9","4:3","1:1","3:4","9:16"],durations:[5,10,15],duration:Number,seed:!0,usdPerSecond:0.13}),Ca({name:"Wan 3.0",text:"alibaba/wan-3.0/text-to-video",ratios:[],durations:[5,10,15],duration:Number,seed:!0,usdPerSecond:0.2})]});class wm{fetch;id="google";name="Google Gemini";keyEnv="GEMINI_API_KEY";requiresKey=!0;resumable=!1;constructor(e=globalThis.fetch){this.fetch=e}listModels(){return ZQ.map(([e,t,r])=>({id:`google/${e}`,providerId:"google",providerModelId:e,name:t,media:"image",operations:["generate","edit"],capabilities:{aspectRatios:VQ,seed:!1,maxCount:1,maxReferenceImages:r}}))}async submit(e){let{params:t,references:r}=e;return{model:e.model.providerModelId,body:{contents:[{parts:[...r.map((n)=>({inlineData:{mimeType:n.mime,data:Buffer.from(n.data).toString("base64")}})),{text:t.prompt}]}],generationConfig:{responseModalities:["IMAGE"],...t.aspectRatio&&{imageConfig:{aspectRatio:t.aspectRatio}},...t.extras}}}}async*events(e,t){yield{type:"progress",message:"Generating",stage:"generating"};let r=await tr(this.fetch,`${FQ}/${e.model}:generateContent`,{method:"POST",headers:{"x-goog-api-key":t.apiKey??"","content-type":"application/json"},body:JSON.stringify(e.body),signal:t.signal},this.name);if(!r.ok){yield Ra(await ur(r,this.name,Aa));return}let n=await r.json(),s=n.candidates?.[0],o=(s?.content?.parts??[]).flatMap((i)=>i.inlineData??[]);if(o.length===0){let i=n.promptFeedback?.blockReason??s?.finishReason;yield{type:"failed",error:i?`Gemini returned no image (${i})`:"Gemini returned no image"};return}yield{type:"completed",outputs:o.map((i)=>({data:new Uint8Array(Buffer.from(i.data,"base64")),mime:i.mimeType}))}}}var FQ="https://generativelanguage.googleapis.com/v1beta/models",VQ,ZQ;var yx=b(()=>{wo();VQ=["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"],ZQ=[["gemini-3-pro-image","Nano Banana Pro",14],["gemini-2.5-flash-image","Nano Banana",3]]});class bm{fetch;id="openai";name="OpenAI";keyEnv="OPENAI_API_KEY";requiresKey=!0;resumable=!1;constructor(e=globalThis.fetch){this.fetch=e}listModels(){return GQ.map(([e,t])=>({id:`openai/${e}`,providerId:"openai",providerModelId:e,name:t,media:"image",operations:["generate","edit"],capabilities:{aspectRatios:Object.keys(L4),seed:!1,maxCount:4,maxReferenceImages:16}}))}async submit(e){let{params:t,references:r}=e,n={model:e.model.providerModelId,prompt:t.prompt,n:t.count,...t.aspectRatio&&{size:L4[t.aspectRatio]},...t.extras};if(r.length===0)return{path:"generations",body:n};return n.images=r.map((s)=>({image_url:vs(s.data,s.mime)})),{path:"edits",body:n}}async*events(e,t){yield{type:"progress",message:"Generating",stage:"generating"};let r=await tr(this.fetch,`${HQ}/${e.path}`,{method:"POST",headers:{authorization:`Bearer ${t.apiKey}`,"content-type":"application/json"},body:JSON.stringify(e.body),signal:t.signal},this.name);if(!r.ok){yield Ra(await ur(r,this.name,Aa));return}let n=await r.json(),s=(n.data??[]).flatMap((o)=>o.b64_json??[]);if(s.length===0){yield{type:"failed",error:"OpenAI returned no images"};return}yield{type:"completed",outputs:s.map((o)=>({data:new Uint8Array(Buffer.from(o,"base64")),mime:`image/${n.output_format??"png"}`}))}}}var HQ="https://api.openai.com/v1/images",L4,GQ;var wx=b(()=>{wo();L4={"1:1":"1024x1024","3:2":"1536x1024","2:3":"1024x1536"},GQ=[["gpt-image-2.5-sunburst","GPT Image 2.5 Sunburst"],["gpt-image-2.5-flare","GPT Image 2.5 Flare"],["gpt-image-2","GPT Image 2"]]});class vm{fetch;pollMs;id="openrouter";name="OpenRouter";keyEnv="OPENROUTER_API_KEY";requiresKey=!0;resumable=!1;constructor(e=globalThis.fetch,t=3000){this.fetch=e;this.pollMs=t}isResumable(e){return e.kind==="video"}listModels(){let e=(t,r)=>({id:`openrouter/${t}`,providerId:"openrouter",providerModelId:t,name:r,operations:["generate","edit"]});return[...WQ.map(([t,r,n,s,o,i])=>({...e(t,r),media:"image",capabilities:{aspectRatios:n,seed:i,maxCount:s,maxReferenceImages:o}})),...JQ.map(([t,r,n,s,o])=>({...e(t,r),media:"video",capabilities:{aspectRatios:n,seed:o,maxCount:1,maxReferenceImages:1,durations:s}}))]}headers(e){return{authorization:`Bearer ${e.apiKey}`}}post(e,t,r){return tr(this.fetch,`${D4}/${e}`,{method:"POST",headers:{...this.headers(r),"content-type":"application/json"},body:JSON.stringify(t),signal:r.signal},this.name)}async submit(e,t){let{model:r,params:n,references:s}=e,o=s.map((l)=>({type:"image_url",image_url:{url:vs(l.data,l.mime)}})),i={model:r.providerModelId,prompt:n.prompt,...n.aspectRatio&&{aspect_ratio:n.aspectRatio},...n.seed!=null&&{seed:n.seed}};if(r.media==="image"){if(n.count>1)i.n=n.count;if(o.length>0)i.input_references=o;return{kind:"image",body:{...i,...n.extras}}}if(n.durationSeconds!=null)i.duration=n.durationSeconds;if(o.length>0)i.frame_images=o.map((l)=>({...l,frame_type:"first_frame"}));let a=await this.post("videos",{...i,...n.extras},t);if(!a.ok)throw await ur(a,this.name);let c=await a.json();if(typeof c.id!=="string"||!/^[\w-]+$/.test(c.id))throw Error("OpenRouter returned an unexpected job id");return{kind:"video",id:c.id}}events(e,t){return e.kind==="image"?this.image(e.body,t):this.video(e.id,t)}async*image(e,t){yield{type:"progress",message:"Generating",stage:"generating"};let r=await this.post("images",e,t);if(!r.ok){yield Ra(await ur(r,this.name,Aa));return}let n=await r.json(),s=(n.data??[]).filter((o)=>o.b64_json);if(s.length===0){yield{type:"failed",error:n.error?.message??"OpenRouter returned no images"};return}yield{type:"completed",outputs:s.map((o)=>({data:new Uint8Array(Buffer.from(o.b64_json,"base64")),mime:o.media_type??"image/png"})),...n.usage?.cost!=null&&{costUsd:n.usage.cost}}}async*video(e,t){if(!/^[\w-]+$/.test(e))throw Error("Invalid OpenRouter job id");let r=`${D4}/videos/${e}`,n={headers:this.headers(t),signal:t.signal},s=0;for(;;){let o=await this.fetch(r,n).catch((a)=>{if(t.signal.aborted)throw a;return null});if(!o||o.status===429||o.status>=500){if(++s>KQ){yield{type:"failed",error:o?await gn(o):"Lost the connection to OpenRouter",code:"connectionLost",params:{provider:this.name}};return}await bs(this.pollMs*2**s,t.signal);continue}if(s=0,!o.ok){yield{type:"failed",error:await gn(o)};return}let i=await o.json();if(i.status==="completed"){yield{type:"completed",outputs:[{url:`${r}/content?index=0`,headers:this.headers(t)}],...i.usage?.cost!=null&&{costUsd:i.usage.cost}};return}if(i.status!=="pending"&&i.status!=="in_progress"){yield{type:"failed",error:typeof i.error==="string"&&i.error?i.error:`The video job ${i.status??"ended without a status"}`};return}yield{type:"progress",...i.status==="pending"?{message:"In queue",stage:"queued"}:{message:"Generating",stage:"generating"}},await bs(this.pollMs,t.signal)}}}var D4="https://openrouter.ai/api/v1",KQ=5,WQ,JQ;var bx=b(()=>{wo();WQ=[["google/gemini-nano-banana-2.1","Nano Banana 2.1",["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"],1,14,!1],["openai/gpt-image-2.6-sunburst","GPT Image 2.6 Sunburst",["1:1","3:2","2:3","4:3","3:4","16:9","9:16","21:9"],4,16,!1],["openai/gpt-image-2.6-flare","GPT Image 2.6 Flare",["1:1","3:2","2:3","4:3","3:4","16:9","9:16","21:9"],4,16,!1],["black-forest-labs/flux-3-image","FLUX 3 Image",["21:9","16:9","3:2","4:3","5:4","1:1","4:5","3:4","2:3","9:16"],1,10,!1],["bytedance-seed/seedream-5-5","Seedream 5.5",["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"],1,10,!0],["qwen/qwen-image-3-pro","Qwen Image 3 Pro",["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9"],4,3,!0]],JQ=[["google/veo-3.1-fast","Veo 3.1 Fast",["16:9","9:16"],[4,6,8],!0],["google/veo-3.1-lite","Veo 3.1 Lite",["16:9","9:16"],[4,6,8],!0],["kwaivgi/kling-v3.0-std","Kling 3.0 Standard",["16:9","9:16","1:1"],[5,10,15],!1],["alibaba/wan-3.0","Wan 3.0",["16:9","4:3","1:1","3:4","9:16"],[5,10,15],!0],["minimax/hailuo-3","Hailuo H3",["21:9","16:9","4:3","1:1","3:4","9:16"],[5,10,15],!1],["runway/gen-4.5","Runway Gen-4.5",["16:9","9:16"],[5,10],!0]]});function j4(e){return QQ[e]}function vx(e){let t=e.listModels.bind(e);return e.listModels=()=>t().map((r)=>{let n=r.profile??j4(r.id);return n?{...r,profile:n}:r}),e}var Te,QQ;var _m=b(()=>{Te={sdxlTurbo:{family:"sdxl-turbo",name:"SDXL Turbo",author:"Stability AI",speed:3,quality:1,text:!1,bestFor:["speed","drafts"],sample:"sdxl-turbo.webp"},sdxl:{family:"sdxl",name:"Stable Diffusion XL",author:"Stability AI",speed:1,quality:2,text:!1,bestFor:["illustration"],sample:"sdxl.webp"},fluxSchnell:{family:"flux-schnell",name:"FLUX.1 schnell",author:"Black Forest Labs",speed:2,quality:2,text:!0,bestFor:["photo","text"],sample:"flux-schnell.webp"},fluxPro:{family:"flux-pro",name:"FLUX",author:"Black Forest Labs",speed:2,quality:3,text:!0,bestFor:["photo","detail"]},zImage:{family:"z-image-turbo",name:"Z-Image Turbo",author:"Tongyi-MAI",speed:2,quality:3,text:!0,bestFor:["photo"],sample:"z-image-turbo.webp"},nanoBanana:{family:"nano-banana",name:"Nano Banana",author:"Google",speed:2,quality:3,text:!0,bestFor:["editing","text"]},nanoBananaPro:{family:"nano-banana-pro",name:"Nano Banana Pro",author:"Google",speed:1,quality:3,text:!0,bestFor:["text","detail"]},gptImage:{family:"gpt-image",name:"GPT Image",author:"OpenAI",speed:1,quality:3,text:!0,bestFor:["instructions","text"]},seedream:{family:"seedream",name:"Seedream",author:"ByteDance",speed:2,quality:3,text:!0,bestFor:["photo","detail"]},qwenImage:{family:"qwen-image",name:"Qwen Image",author:"Alibaba",speed:2,quality:3,text:!0,bestFor:["text","illustration"]},veo:{family:"veo",name:"Veo",author:"Google",speed:2,quality:3,text:!1,bestFor:["cinema","sound"]},kling:{family:"kling",name:"Kling",author:"Kuaishou",speed:2,quality:3,text:!1,bestFor:["motion"]},hailuo:{family:"hailuo",name:"Hailuo",author:"MiniMax",speed:2,quality:2,text:!1,bestFor:["motion"]},wanCloud:{family:"wan",name:"Wan",author:"Alibaba",speed:2,quality:2,text:!1,bestFor:["motion"]},runway:{family:"runway",name:"Runway",author:"Runway",speed:2,quality:3,text:!1,bestFor:["cinema"]},wanLocal:{family:"wan-local",name:"Wan 2.1",author:"Alibaba",speed:1,quality:1,text:!1,bestFor:["motion"]}},QQ={"fal/fal-ai/flux/schnell":Te.fluxSchnell,"replicate/black-forest-labs/flux-schnell":Te.fluxSchnell,"fal/fal-ai/flux/dev":Te.fluxPro,"replicate/black-forest-labs/flux-1.1-pro":Te.fluxPro,"openrouter/black-forest-labs/flux-3-image":Te.fluxPro,"fal/fal-ai/nano-banana":Te.nanoBanana,"google/gemini-2.5-flash-image":Te.nanoBanana,"openrouter/google/gemini-nano-banana-2.1":Te.nanoBanana,"google/gemini-3-pro-image":Te.nanoBananaPro,"openai/gpt-image-2.5-sunburst":Te.gptImage,"openai/gpt-image-2.5-flare":Te.gptImage,"openai/gpt-image-2":Te.gptImage,"openrouter/openai/gpt-image-2.6-sunburst":Te.gptImage,"openrouter/openai/gpt-image-2.6-flare":Te.gptImage,"openrouter/bytedance-seed/seedream-5-5":Te.seedream,"openrouter/qwen/qwen-image-3-pro":Te.qwenImage,"fal/fal-ai/veo3.1/fast":Te.veo,"fal/fal-ai/veo3":Te.veo,"replicate/google/veo-3.1-fast":Te.veo,"openrouter/google/veo-3.1-fast":Te.veo,"openrouter/google/veo-3.1-lite":Te.veo,"fal/fal-ai/kling-video/v2.5-turbo/pro/text-to-video":Te.kling,"fal/kling/v4/text-to-video":Te.kling,"replicate/kwaivgi/kling-v2.5-turbo-pro":Te.kling,"openrouter/kwaivgi/kling-v3.0-std":Te.kling,"fal/minimax/h3/text-to-video":Te.hailuo,"replicate/minimax/hailuo-02":Te.hailuo,"openrouter/minimax/hailuo-3":Te.hailuo,"fal/alibaba/wan-3.0/text-to-video":Te.wanCloud,"replicate/wan-video/wan-2.2-t2v-fast":Te.wanCloud,"openrouter/alibaba/wan-3.0":Te.wanCloud,"openrouter/runway/gen-4.5":Te.runway}});function Sm(e,t,r,n){return{id:`replicate/${e}`,providerId:"replicate",providerModelId:e,name:t,media:r,operations:n.maxReferenceImages>0?["generate","edit"]:["generate"],capabilities:n}}function $m(e){return{prompt:e.prompt,...e.aspectRatio&&{aspect_ratio:e.aspectRatio},...e.seed!=null&&{seed:e.seed}}}function _x(e,t,r){return{spec:Sm(e,t,"video",{aspectRatios:r.ratios,seed:r.seed,maxCount:1,maxReferenceImages:1,durations:r.durations}),input:(n,[s])=>({...$m(n),...n.durationSeconds!=null&&{duration:n.durationSeconds},...s&&{[r.imageField]:vs(s.data,s.mime)},...n.extras})}}function xm(e){if(typeof e!=="string"||!e.startsWith(`${q4}/`))throw Error("Replicate returned an unexpected request URL");return e}class km{fetch;pollMs;id="replicate";name="Replicate";keyEnv="REPLICATE_API_TOKEN";requiresKey=!0;resumable=!0;constructor(e=globalThis.fetch,t=1500){this.fetch=e;this.pollMs=t}listModels(){return B4.map((e)=>e.spec)}headers(e){return{authorization:`Bearer ${e.apiKey}`}}async submit(e,t){let r=B4.find((o)=>o.spec.id===e.model.id);if(!r)throw Error(`Unknown Replicate model: ${e.model.id}`);let n=await tr(this.fetch,`${q4}/models/${r.spec.providerModelId}/predictions`,{method:"POST",headers:{...this.headers(t),"content-type":"application/json"},body:JSON.stringify({input:r.input(e.params,e.references)}),signal:t.signal},this.name);if(!n.ok)throw await ur(n,this.name);let s=await n.json();return{getUrl:xm(s.urls?.get),cancelUrl:xm(s.urls?.cancel)}}async*events(e,t){let r={headers:this.headers(t),signal:t.signal},n=xm(e.getUrl),s=0;for(;;){let o=await this.fetch(n,r).catch((a)=>{if(t.signal.aborted)throw a;return null});if(!o||o.status===429||o.status>=500){if(++s>XQ){yield{type:"failed",error:o?await gn(o):"Lost the connection to Replicate",code:"connectionLost",params:{provider:this.name}};return}await bs(this.pollMs*2**s,t.signal);continue}if(s=0,!o.ok){yield{type:"failed",error:await gn(o)};return}let i=await o.json();if(i.status==="succeeded"){let a=[i.output].flat().filter((c)=>typeof c==="string");if(a.length===0){yield{type:"failed",error:"Replicate returned no result"};return}yield{type:"completed",outputs:a.map((c)=>({url:c}))};return}if(i.status!=="starting"&&i.status!=="processing"){yield{type:"failed",error:typeof i.error==="string"&&i.error?i.error:`The prediction was ${i.status}`};return}yield{type:"progress",...i.status==="starting"?{message:"Starting",stage:"starting"}:{message:"Generating",stage:"generating"}},await bs(this.pollMs,t.signal)}}async cancel(e,t){await this.fetch(xm(e.cancelUrl),{method:"POST",headers:this.headers(t),signal:t.signal})}}var q4="https://api.replicate.com/v1",XQ=5,U4,B4;var xx=b(()=>{wo();U4=["1:1","16:9","9:16","4:3","3:4","3:2","2:3"];B4=[{spec:Sm("black-forest-labs/flux-schnell","FLUX.1 schnell","image",{aspectRatios:U4,seed:!0,maxCount:4,maxReferenceImages:0,englishPrompts:!0}),input:(e)=>({...$m(e),num_outputs:e.count,output_format:"png",...e.extras})},{spec:Sm("black-forest-labs/flux-1.1-pro","FLUX 1.1 Pro","image",{aspectRatios:U4,seed:!0,maxCount:1,maxReferenceImages:0,englishPrompts:!0}),input:(e)=>({...$m(e),output_format:"png",...e.extras})},_x("google/veo-3.1-fast","Veo 3.1 Fast",{ratios:["16:9","9:16"],durations:[4,6,8],seed:!0,imageField:"image"}),_x("kwaivgi/kling-v2.5-turbo-pro","Kling 2.5 Turbo Pro",{ratios:["16:9","9:16","1:1"],durations:[5,10],seed:!1,imageField:"start_image"}),_x("minimax/hailuo-02","Hailuo 02",{ratios:[],durations:[6,10],seed:!1,imageField:"first_frame_image"}),{spec:Sm("wan-video/wan-2.2-t2v-fast","Wan 2.2 Fast","video",{aspectRatios:["16:9","9:16"],seed:!0,maxCount:1,maxReferenceImages:0}),input:(e)=>({...$m(e),...e.extras})}]});function V4(e){let t=[],r=!1,n=(s,o,i=!1)=>{let a=t.at(-1);if(a&&i&&r)a.parts.push(...o);else t.push({role:s,parts:o});r=i};for(let s of e)if(s.role==="user")n("user",F4(s.content));else if(s.role==="assistant")n("model",[...s.text?[{text:s.text}]:[],...s.toolCalls.map((o)=>({functionCall:{name:o.name,args:o.arguments},...o.signature&&{thoughtSignature:o.signature}}))]);else{let o=s.content.filter((i)=>i.type==="text").map((i)=>i.type==="text"?i.text:"").join(`
|
|
139
|
+
`);n("user",[{functionResponse:{name:s.name,response:{result:o}}},...F4(s.content.filter((i)=>i.type==="image"))],!0)}return t}function Z4(e){let t=e.candidates?.[0]?.content?.parts??[],r=[],n=[];for(let s of t){if(s.thought)continue;if(s.functionCall)r.push({id:s.functionCall.id??`call_${r.length}`,name:s.functionCall.name,arguments:s.functionCall.args??{},...s.thoughtSignature&&{signature:s.thoughtSignature}});else if(s.text)n.push(s.text)}return{text:n.join("").trim(),toolCalls:r}}class Pm{service;apiKey;fetch;vision=!0;model=0;constructor(e,t,r=(n,s)=>globalThis.fetch(n,s)){this.service=e;this.apiKey=t;this.fetch=r}async chat(e,t,r,n){let s=YQ[this.service];for(let o=this.model;o<s.length;o++){let i=await this.ask(s[o],e,t,r,n);if(i.status===404)continue;if(!i.ok)throw await ur(i,Tm[this.service]);this.model=o;let a=await i.json();return this.service==="google"?Z4(a):ad(a)}throw new le(`${Tm[this.service]} has none of the models Hatchlight's assistant uses`)}ask(e,t,r,n,s){if(this.service==="google")return tr(this.fetch,`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,{method:"POST",headers:{"x-goog-api-key":this.apiKey,"content-type":"application/json"},body:JSON.stringify({systemInstruction:{parts:[{text:t}]},contents:V4(r),...n.length>0&&{tools:[{functionDeclarations:n.map((i)=>({name:i.name,description:i.description,parametersJsonSchema:i.parameters}))}]}}),signal:s},Tm.google);let o=this.service==="openai"?"https://api.openai.com/v1/chat/completions":"https://openrouter.ai/api/v1/chat/completions";return tr(this.fetch,o,{method:"POST",headers:{authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"},body:JSON.stringify({model:e,messages:od(t,r,!0),...n.length>0&&{tools:id(n)}}),signal:s},Tm[this.service])}}var YQ,Tm,F4=(e)=>e.map((t)=>t.type==="text"?{text:t.text}:{inlineData:{mimeType:t.mimeType,data:t.data}});var H4=b(()=>{Pt();wo();YQ={openai:["gpt-5-mini","gpt-4.1-mini","gpt-4o-mini"],google:["gemini-3.5-flash","gemini-2.5-flash"],openrouter:["google/gemini-3.5-flash","openai/gpt-5-mini","google/gemini-2.5-flash"]},Tm={openai:"OpenAI",google:"Google Gemini",openrouter:"OpenRouter"}});function $x(){return[{id:"sd-cpp",name:"stable-diffusion.cpp",homepage:"https://github.com/leejet/stable-diffusion.cpp",license:"MIT",builds:[ri("cuda","win32","x64",[za("sd-master-532d2c1-bin-win-cuda12-x64.zip",412365497,"b087219145a382cc1b1e826318289e1f672b9bb6965977734ef0deb85fe2d03a"),za("cudart-sd-bin-win-cu12-x64.zip",563452046,"fe20366827d357c00797eebb58244dddab7fd9a348d70090c3871004c320f38d")],{minNvidiaDriver:"527.41"}),ri("rocm","win32","x64",[za("sd-master-532d2c1-bin-win-rocm-10.1.0-x64.zip",283581117,"b10fcc88f5a37adc1b63e0c1bd06fcbc8212340a68b96022b45d72e64c9e45a1")]),ri("vulkan","win32","x64",[za("sd-master-532d2c1-bin-win-vulkan-x64.zip",30312081,"3e66222c87ca27074e1fd8ce79706eef17a8aaf39949906aa1bee7e060f22ecc")]),ri("cpu","win32","x64",[za("sd-master-532d2c1-bin-win-cpu-x64.zip",18358541,"abef332cfca7861cc567910e79bedb70bfb2920bb4eedac97fcbb6db477f1596")]),ri("cuda","linux","x64",[Sx("sd-cpp-master-1106-532d2c1-linux-x64-cuda.tar.gz",164510710,"63c94c099eb0b6ef0c17a329c144bcd3080ebf903f966b01f25895213cc6b845")],{minNvidiaDriver:"570.26"}),ri("cpu","linux","x64",[Sx("sd-cpp-master-1106-532d2c1-linux-x64-cpu.tar.gz",25169126,"0af250d002d62af8463405d08693fe5e030564f1ee25b01595d5bdb2053c11f4")]),ri("metal","darwin","arm64",[za("sd-master-532d2c1-bin-Darwin-macOS-26.7.2-arm64.zip",38331254,"8146d6ffc75f8ff8f64b62a80fffee8fb714ab65e368e202084135fa07cc6f36")])]},tX]}var eX=(e)=>`https://github.com/leejet/stable-diffusion.cpp/releases/download/master-1106-532d2c1/${e}`,za=(e,t,r)=>({name:e,url:eX(e),size:t,sha256:r}),Sx=(e,t,r)=>({name:e,url:`https://github.com/hatchlight/hatchlight/releases/download/engines-master-1106-532d2c1-b12034/${e}`,size:t,sha256:r}),ri=(e,t,r,n,s={})=>({id:`sd-cpp-${t}-${r}-${e}`,engine:"sd-cpp",version:"master-1106-532d2c1",backend:e,os:t,arch:r,files:n,executable:t==="win32"?"sd-cli.exe":"sd-cli",...s}),tX;var G4=b(()=>{tX={id:"llama-cpp",name:"llama.cpp",homepage:"https://github.com/ggml-org/llama.cpp",license:"MIT",builds:[{id:"llama-cpp-win32-x64-cpu",engine:"llama-cpp",version:"b12034",backend:"cpu",os:"win32",arch:"x64",files:[{name:"llama-b12034-bin-win-cpu-x64.zip",url:"https://github.com/ggml-org/llama.cpp/releases/download/b12034/llama-b12034-bin-win-cpu-x64.zip",size:24582890,sha256:"16c38cd9ff7487bf118a37808784245a2d639d844110f21fe9b373aaa40ff511"}],executable:"llama-server.exe"},{id:"llama-cpp-linux-x64-cpu",engine:"llama-cpp",version:"b12034",backend:"cpu",os:"linux",arch:"x64",files:[Sx("llama-cpp-b12034-linux-x64-cpu.tar.gz",14461625,"bb514e30740c88c85944f26e773d1a984e66f7549d8cb74b5086fd67b5dafa01")],executable:"llama-server"}]}});var Ne=(e,t,r)=>`https://huggingface.co/${e}/resolve/${t}/${r}`,F=1e9,N=([e,t],r,n,s,o)=>({name:r.split("/").at(-1),url:Ne(e,t,r),size:n,sha256:s,role:o}),je,Re,Em,nu=(e,t)=>({license:e,licenseUrl:t,commercial:{kind:"allowed"}}),bo,Q,Ma="\u8272\u8C03\u8273\u4E3D\uFF0C\u8FC7\u66DD\uFF0C\u9759\u6001\uFF0C\u7EC6\u8282\u6A21\u7CCA\u4E0D\u6E05\uFF0C\u5B57\u5E55\uFF0C\u98CE\u683C\uFF0C\u4F5C\u54C1\uFF0C\u753B\u4F5C\uFF0C\u753B\u9762\uFF0C\u9759\u6B62\uFF0C\u6574\u4F53\u53D1\u7070\uFF0C\u6700\u5DEE\u8D28\u91CF\uFF0C\u4F4E\u8D28\u91CF\uFF0CJPEG\u538B\u7F29\u6B8B\u7559\uFF0C\u4E11\u964B\u7684\uFF0C\u6B8B\u7F3A\u7684\uFF0C\u591A\u4F59\u7684\u624B\u6307\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u624B\u90E8\uFF0C\u753B\u5F97\u4E0D\u597D\u7684\u8138\u90E8\uFF0C\u7578\u5F62\u7684\uFF0C\u6BC1\u5BB9\u7684\uFF0C\u5F62\u6001\u7578\u5F62\u7684\u80A2\u4F53\uFF0C\u624B\u6307\u878D\u5408\uFF0C\u9759\u6B62\u4E0D\u52A8\u7684\u753B\u9762\uFF0C\u6742\u4E71\u7684\u80CC\u666F\uFF0C\u4E09\u6761\u817F\uFF0C\u80CC\u666F\u4EBA\u5F88\u591A\uFF0C\u5012\u7740\u8D70";var Hn=b(()=>{je=["1:1","4:3","3:4","3:2","2:3","16:9","9:16"],Re={license:"Apache 2.0",licenseUrl:"https://www.apache.org/licenses/LICENSE-2.0",commercial:{kind:"allowed"}},Em={license:"MIT",licenseUrl:"https://opensource.org/license/mit",commercial:{kind:"allowed"}},bo={comfyZImage:["Comfy-Org/Z-Image-Turbo","6fc90a3b1b653e935a0d175e260736de25b84df5"],fluxEncoders:["comfyanonymous/flux_text_encoders","6af2a98e3f615bdfa612fbd85da93d1ed5f69ef5"],qwen3Instruct:["unsloth/Qwen3-4B-Instruct-2507-GGUF","a06e946bb6b655725eafa393f4a9745d460374c9"],comfyWan:["Comfy-Org/Wan-2.1","123acf1cc74bccbb9bfff8ac1ee72edc08c2341d"],umt5Gguf:["city96/umt5-xxl-encoder-gguf","b535255bee98c2b0a59ea7c0ae2dcd0c6657b3b7"]},Q={fluxVae:N(bo.comfyZImage,"split_files/vae/ae.safetensors",335304388,"afc8e28272cd15db3919bacdb6918ce9c1ed22e96cb12c4d5ed0fba823529e38","vae"),fluxT5:N(bo.fluxEncoders,"t5xxl_fp8_e4m3fn.safetensors",4893934904,"7d330da4816157540d6bb7838bf63a0f02f573fc48ca4d8de34bb0cbfd514f09","t5xxl"),fluxClip:N(bo.fluxEncoders,"clip_l.safetensors",246144152,"660c6f5b1abae9dc498ac2d21e1347d2abdb0cf6c0c0c8576cd796491d9a6cdd","clip_l"),qwen3InstructBf16:N(bo.comfyZImage,"split_files/text_encoders/qwen_3_4b.safetensors",8044982048,"6c671498573ac2f7a5501502ccce8d2b08ea6ca2f661c458e708f36b36edfc5a","llm"),qwen3InstructQ8:N(bo.qwen3Instruct,"Qwen3-4B-Instruct-2507-Q8_0.gguf",4280405600,"391c1e410fd9f4cf2de2b510273b56a84c19ce18f4fa3bfb3774031dac4ef068","llm"),qwen3InstructQ4:N(bo.qwen3Instruct,"Qwen3-4B-Instruct-2507-Q4_K_M.gguf",2497281120,"3605803b982cb64aead44f6c1b2ae36e3acdb41d8e46c8a94c6533bc4c67e597","llm"),umt5Q8:N(bo.umt5Gguf,"umt5-xxl-encoder-Q8_0.gguf",6043068256,"2521d4de0bf9e1cc6549866463ceae85e4ec3239bc6063f7488810be39033bbc","t5xxl"),wan21Vae:N(bo.comfyWan,"split_files/vae/wan_2.1_vae.safetensors",253815318,"2fc39d31359a4b0a64f55876d8ff7fa8d780956ae2cb13463b0223e15148976b","vae")}});function K4(){return[{id:"sd-1.5",englishPrompts:!0,profile:{family:"sd-1.5",name:"Stable Diffusion 1.5",author:"Stability AI",speed:3,quality:1,text:!1,bestFor:["speed","drafts"]},name:"Stable Diffusion 1.5",author:"Runway, Stability AI and CompVis",media:"image",tasks:["text-to-image"],summary:"The small 512px model that started local image generation. It runs on weak graphics cards and even on the processor alone.",...nu("CreativeML OpenRAIL-M","https://huggingface.co/spaces/CompVis/stable-diffusion-license"),homepage:"https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5",variants:[{id:"fp16",label:"16-bit",engine:"sd-cpp",memoryBytes:5*F,files:[N(yn.sd15Gguf,"stable-diffusion-v1-5-pruned-emaonly-f16.gguf",2132586944,"da017009aa86a3f46468857d95833435fe55e4a2856afab76ba7722ef8ee4d8b","model")]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:4*F,files:[N(yn.sd15Gguf,"stable-diffusion-v1-5-pruned-emaonly-Q4_0.gguf",1566768416,"b8944e9fe0b69b36ae1b5bb0185b3a7b8ef14347fe0fa9af6c64c4829022261f","model")]}],defaults:{size:512,aspectRatios:je,steps:20,cfgScale:7},demos:[]},{id:"pixart-sigma",englishPrompts:!0,profile:{family:"pixart-sigma",name:"PixArt-\u03A3",author:"PixArt-alpha",speed:3,quality:2,text:!1,bestFor:["illustration","drafts"]},name:"PixArt-\u03A3",author:"PixArt-alpha (Huawei Noah's Ark Lab)",media:"image",tasks:["text-to-image","image-to-image"],summary:"A small transformer that makes 1024px images in twenty steps, following long prompts through its T5 text encoder.",...nu("CreativeML Open RAIL++-M","https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md"),homepage:"https://huggingface.co/PixArt-alpha/PixArt-Sigma-XL-2-1024-MS",variants:[{id:"fp32",label:"32-bit",engine:"sd-cpp",memoryBytes:5*F,files:[N(yn.pixartSigma,"transformer/diffusion_pytorch_model.safetensors",2443492488,"2fa4dee9229c02b03163f57bdb8e80c7a5ee364b7161796abe9c05e8dd13f239","diffusion_model"),{...N(yn.pixartSigma,"vae/diffusion_pytorch_model.safetensors",334643238,"1b909373b28f2137098b0fd9dbc6f97f8410854f31f84ddc9fa04b077b0ace2c","vae"),name:"pixart_sigma_vae.safetensors"},Q.fluxT5]}],defaults:{references:{as:"init",max:1},size:1024,aspectRatios:je,steps:20,cfgScale:4.5},demos:[{url:Ne(...yn.pixartSigma,"asset/4K_image.jpg"),media:"image",caption:"Samples from the model card"}]},{id:"iris-3b",profile:{family:"iris-3b",name:"Iris-3B",author:"Sperid Labs",speed:1,quality:2,text:!1,bestFor:["photo","detail"]},name:"Iris-3B",author:"Sperid Labs",media:"image",tasks:["text-to-image"],summary:"A 3B model that draws 1024px images directly in pixels, without an image decoder. Detailed portraits and photographs, at a hundred steps.",...Re,homepage:"https://huggingface.co/speridlabs/iris-3b",variants:[{id:"fp32",label:"32-bit",engine:"sd-cpp",memoryBytes:14*F,files:[N(yn.iris,"model.safetensors",11950112680,"a90e1f4c197bac8491f82078def68884b6a3527ea7fc97a693e3e367372aa80f","diffusion_model"),N(yn.qwen3VlGguf,"Qwen3VL-4B-Instruct-Q8_0.gguf",4280406144,"054721f478bc5fa6beffb7f38eae575d45298f88cbb8d2f83ef675a727863eb1","llm")]}],defaults:{size:1024,aspectRatios:je,steps:100,cfgScale:3},demos:[{url:Ne(...yn.iris,"assets/gallery/0005.jpg"),media:"image",caption:"A sample from the model card"},{url:Ne(...yn.iris,"assets/gallery/0020.jpg"),media:"image",caption:"A portrait from the model card"}]},{id:"minit2i-b-16",englishPrompts:!0,profile:{family:"minit2i",name:"MiniT2I",author:"MiniT2I",speed:3,quality:1,text:!1,bestFor:["drafts"]},name:"MiniT2I B/16",author:"MiniT2I",media:"image",tasks:["text-to-image"],summary:"A minimalist research model that makes square 512px images in pixels. Small enough for modest graphics cards.",...Em,homepage:"https://huggingface.co/MiniT2I/MiniT2I",variants:[{id:"fp32",label:"32-bit",engine:"sd-cpp",memoryBytes:4*F,files:[N(yn.miniT2i,"minit2i-b-16/transformer/diffusion_pytorch_model.safetensors",1032534472,"5114de36379acd45f810001d9da82d48f96559ce4428cde7a79b1e724983ced1","diffusion_model"),N(yn.flanT5,"model.safetensors",3132668804,"a9dd06ce490f139af36e9eb77dd3758b4fd07a08a73d5a1abe5ff2591e2d388e","t5xxl")]}],defaults:{size:512,aspectRatios:["1:1"],steps:100,cfgScale:6,sampler:"euler"},demos:[]}]}var yn;var W4=b(()=>{Hn();yn={sd15Gguf:["second-state/stable-diffusion-v1-5-GGUF","031b5f5df991f511b3f5fa8fed6d99048ababb69"],pixartSigma:["PixArt-alpha/PixArt-Sigma-XL-2-1024-MS","e102b3591cc82e97071b8b4cb90d834d0c487207"],iris:["speridlabs/iris-3b","adc05b909fb05d4276d26aae5a52b36406b2ef26"],qwen3VlGguf:["Qwen/Qwen3-VL-4B-Instruct-GGUF","1cd86afb9a95c410a6038ab3b40d8b578c892266"],miniT2i:["MiniT2I/MiniT2I","5b4da2870d1554992670d1005567e9d55b1b37bb"],flanT5:["google/flan-t5-large","0613663d0d48ea86ba8cb3d7a44f0f65dc596a2a"]}});function X4(){return[{id:"flux-2-klein-4b",profile:{family:"flux-2-klein-4b",name:"FLUX.2 klein 4B",author:"Black Forest Labs",speed:3,quality:2,text:!0,bestFor:["speed","editing","photo"]},name:"FLUX.2 klein 4B",author:"Black Forest Labs",media:"image",tasks:["text-to-image","image-edit"],summary:"A small, step-distilled FLUX.2 that makes 1024px images in four steps and edits pictures from one or more references.",...Re,homepage:"https://huggingface.co/black-forest-labs/FLUX.2-klein-4B",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:17*F,files:[N(Bt.klein,"flux-2-klein-4b.safetensors",7751105712,"ec3d4e733a771f61c052fb4856c48b336c55eaf2c65487c2a1faeb9bbda7a343","diffusion_model"),Q.qwen3InstructBf16,Na]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:11*F,files:[N(Bt.kleinGguf,"flux-2-klein-4b-Q8_0.gguf",4300629440,"0bba6951258ec8f92d51114a8fa13e66828297bfff58a738f52729b3ef66fa28","diffusion_model"),J4,Na]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:7*F,files:[N(Bt.kleinGguf,"flux-2-klein-4b-Q4_0.gguf",2460378560,"d1023499ef3f2f82ff7c50e6778495195c1b6cc34835741778868428111f9ff4","diffusion_model"),Q4,Na]}],defaults:{size:1024,aspectRatios:je,steps:4,cfgScale:1,sampler:"euler",references:{as:"ref",max:4},engineArgs:["--flash-attn","off,diffusion=on"],previewsWhileFollowing:!1},demos:[{url:Ne(...Bt.klein,"realism.jpg"),media:"image",caption:"Photorealistic samples from the model card"},{url:Ne(...Bt.klein,"editing.jpg"),media:"image",caption:"Editing samples from the model card"}]},{id:"flux-2-klein-base-4b",profile:{family:"flux-2-klein-base-4b",name:"FLUX.2 klein Base 4B",author:"Black Forest Labs",speed:1,quality:2,text:!0,bestFor:["detail","editing"]},name:"FLUX.2 klein Base 4B",author:"Black Forest Labs",media:"image",tasks:["text-to-image","image-edit"],summary:"The undistilled FLUX.2 klein 4B: slower, with more varied results, and the one to pair with fine-tunes and LoRAs.",...Re,homepage:"https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4B",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:17*F,files:[N(Bt.kleinBase,"flux-2-klein-base-4b.safetensors",7751105712,"9c5fed22b76baea749d88fc2abe3ad53245e7b21a0d353a762665eea00043b92","diffusion_model"),Q.qwen3InstructBf16,Na]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:11*F,files:[N(Bt.kleinBaseGguf,"flux-2-klein-base-4b-Q8_0.gguf",4300629440,"197fbc64147d4f0a0ddf4c9e667b05a3790a73ed12f92d391f0f4d286ee30fe8","diffusion_model"),J4,Na]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:7*F,files:[N(Bt.kleinBaseGguf,"flux-2-klein-base-4b-Q4_0.gguf",2460378560,"c3a2854510677b7aa37dd7547d908c54889a76c6d6aa3ffe902fcaa092d1328b","diffusion_model"),Q4,Na]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:4,references:{as:"ref",max:4},engineArgs:["--flash-attn","off,diffusion=on"],previewsWhileFollowing:!1},demos:[{url:Ne(...Bt.kleinBase,"realism.jpg"),media:"image",caption:"Samples of the FLUX.2 klein family from the model card"}]},{id:"chroma1-hd",englishPrompts:!0,profile:{family:"chroma1-hd",name:"Chroma1-HD",author:"lodestones",speed:1,quality:2,text:!0,bestFor:["illustration","photo"]},name:"Chroma1-HD",author:"lodestones",media:"image",tasks:["text-to-image"],summary:"An 8.9B model rebuilt from FLUX.1 schnell, with a wide range of styles and real negative prompts. Made as a base for fine-tuning.",...Re,homepage:"https://huggingface.co/lodestones/Chroma1-HD",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:21*F,files:[N(Bt.chromaHd,"Chroma1-HD.safetensors",17800038288,"d446d9695d08276f61e53653e025289dd96f7a489c27982a1fa54ecabc06642a","diffusion_model"),Im,Q.fluxVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:13*F,files:[N(Bt.chromaHdGguf,"Chroma1-HD-Q8_0.gguf",9735409824,"8c8d66177bfc584573dd21584399ebc1f00bde60acbbc48ac3cc8f58f10c6094","diffusion_model"),Im,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:8*F,files:[N(Bt.chromaHdGguf,"Chroma1-HD-Q4_K_M.gguf",5566533792,"086f561e371d442b82b2c3689149da75046754c62a35293932cda397fc2bf9d2","diffusion_model"),Im,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:40,cfgScale:4,sampler:"euler",negativePrompt:rX,engineArgs:["--model-args","chroma_use_dit_mask=false"]},demos:[{url:Ne(...Bt.chromaHd,"ComfyUI_Chroma1-HD_T2I-sample.png"),media:"image",caption:"A sample from the model card"}]},{id:"chroma1-radiance",englishPrompts:!0,profile:{family:"chroma1-radiance",name:"Chroma1-Radiance",author:"lodestones",speed:1,quality:2,text:!1,bestFor:["detail","photo"]},name:"Chroma1-Radiance",author:"lodestones",media:"image",tasks:["text-to-image"],summary:"A Chroma that draws pixels directly instead of going through an image decoder, which keeps fine detail. Still in training; this is its v0.4 release.",...Re,homepage:"https://huggingface.co/lodestones/Chroma1-Radiance",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:14*F,files:[N(Bt.radianceGguf,"Chroma1-Radiance-v0.4/Chroma1-Radiance-v0.4-Q8_0.gguf",10386601952,"a92bb87e5241cbc876d8e40052cd78b5f7bc851c8a45a66c8fe06ab2082cb0b1","diffusion_model"),Im]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:4,sampler:"euler"},demos:[]}]}var Bt,Na,J4,Q4,Im,rX="low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors";var Y4=b(()=>{Hn();Bt={klein:["black-forest-labs/FLUX.2-klein-4B","e7b7dc27f91deacad38e78976d1f2b499d76a294"],kleinBase:["black-forest-labs/FLUX.2-klein-base-4B","a3b4f4849157f664bdbc776fd7453c2783562f4d"],kleinGguf:["leejet/FLUX.2-klein-4B-GGUF","3b1f5a9dc3abb32238b053aeb3d823c30afdacbd"],kleinBaseGguf:["leejet/FLUX.2-klein-base-4B-GGUF","d12671125306ca6b5f6db1b33ed4c80c8511a53f"],comfyKlein:["Comfy-Org/Flux-2-Klein-4B","5b3abca5c0dc1ecd4eaf3340868d09063fc1c965"],qwen3Gguf:["unsloth/Qwen3-4B-GGUF","22c9fc8a8c7700b76a1789366280a6a5a1ad1120"],fluxEncoders:["comfyanonymous/flux_text_encoders","6af2a98e3f615bdfa612fbd85da93d1ed5f69ef5"],chromaHd:["lodestones/Chroma1-HD","0e0c60ece1e82b17cb7f77342d765ba5024c40c0"],chromaHdGguf:["silveroxides/Chroma1-HD-GGUF","d3b77bf4eb5b84c0b50e9a1e83f6e8074ed85f82"],radianceGguf:["silveroxides/Chroma1-Radiance-GGUF","a36b30f072739f69615ef6a36a7ef046ad0f9f9b"]},Na=N(Bt.comfyKlein,"split_files/vae/flux2-vae.safetensors",336211292,"868fe7b343cc8f3a19dbcfcafbc3d5f888802be3f89bd81b65b3621a066ce8f3","vae"),J4=N(Bt.qwen3Gguf,"Qwen3-4B-Q8_0.gguf",4280405792,"eed555233267a33c7e8ee31682762cc7751b3f6d224039086e0e846f05fffa5d","llm"),Q4=N(Bt.qwen3Gguf,"Qwen3-4B-Q4_K_M.gguf",2497281312,"f6f851777709861056efcdad3af01da38b31223a3ba26e61a4f8bf3a2195813a","llm"),Im=N(Bt.fluxEncoders,"t5xxl_fp16.safetensors",9787841024,"6e480b09fae049a72d2a8c5fbccb8d3e92febeb233bbe9dfe7256958a9167635","t5xxl")});function eL(){return[{id:"hidream-o1-image-dev",profile:{family:"hidream-o1-image",name:"HiDream-O1-Image",author:"HiDream.ai",speed:1,quality:3,text:!0,bestFor:["detail","text","instructions"]},name:"HiDream-O1-Image Dev",author:"HiDream.ai",media:"image",tasks:["text-to-image"],summary:"An 8B model that works on pixels directly, with no separate text encoder or decoder. Strong at long text and layouts, and slow on most cards.",...Em,homepage:"https://huggingface.co/HiDream-ai/HiDream-O1-Image-Dev",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:19*F,files:[N(Mt.comfyHiDream,"checkpoints/hidream_o1_image_dev_bf16.safetensors",16365209824,"cede93912730dd046fd39a20af008344a7dce75dafabd16e419a222c3e504051","model")]}],defaults:{size:1024,aspectRatios:je,steps:28,cfgScale:1},demos:[{url:Ne(...Mt.hiDreamDev,"assets/general.webp"),media:"image",caption:"Samples from the model card"},{url:Ne(...Mt.hiDreamDev,"assets/text-layout.webp"),media:"image",caption:"Long text and layout samples from the model card"}]},{id:"llada-image-turbo",profile:{family:"llada-image",name:"LLaDA-Image",author:"inclusionAI (Ant Group)",speed:2,quality:2,text:!0,bestFor:["editing","instructions"]},name:"LLaDA-Image Turbo",author:"inclusionAI (Ant Group)",media:"image",tasks:["text-to-image","image-edit"],summary:"A 6B model that makes images and edits them by instruction in four steps. Its text encoder is large, about 10 to 18 GB.",...Re,homepage:"https://huggingface.co/inclusionAI/LLaDA-Image-Turbo",variants:[{id:"f16",label:"16-bit",engine:"sd-cpp",memoryBytes:17*F,files:[N(Mt.lladaTurboGguf,"llada-image-turbo-f16.gguf",13080491424,"113ea8596fa62c5aedd9c39c5bce305c1f708df55f510be092ed69c2c521a31d","diffusion_model"),N(Mt.lladaTurboGguf,"llada-image-turbo-text_encoder-q8_0.gguf",17676202624,"dc95123508eeb92593c2e63c5f0dbd7e678e3694766fcbbaa792da3e740ca6f0","llm"),_s.lladaTokenizer,_s.lladaTurboConnectors,_s.lladaVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:11*F,files:[N(Mt.lladaTurboGguf,"llada-image-turbo-q8_0.gguf",6951851424,"101d85567805858b12583a1b9647568c163aa843140cee68c31c2d4d893a434f","diffusion_model"),N(Mt.lladaTurboGguf,"llada-image-turbo-text_encoder-q4_K.gguf",9692566528,"3efd1f42856ab18f2e2d4a0ac277943801336e5641b21905c2131a04e96b8a40","llm"),_s.lladaTokenizer,_s.lladaTurboConnectors,_s.lladaVae]}],defaults:{size:1024,aspectRatios:je,steps:4,cfgScale:1,references:{as:"ref",max:1}},demos:[{url:Ne(...Mt.lladaTurbo,"assets/demo.jpg"),media:"image",caption:"Samples from the model card"},{url:Ne(...Mt.lladaTurbo,"assets/edit_demo.jpg"),media:"image",caption:"Edits from the model card"}]},{id:"boogu-image-turbo",profile:{family:"boogu-image",name:"Boogu-Image",author:"Boogu",speed:2,quality:3,text:!0,bestFor:["photo","text"]},name:"Boogu-Image Turbo",author:"Boogu",media:"image",tasks:["text-to-image"],summary:"A 10B model distilled to four steps, for photorealistic 1024px images with text in English and Chinese.",...Re,homepage:"https://huggingface.co/Boogu/Boogu-Image-0.1-Turbo",variants:[{id:"int8",label:"8-bit",engine:"sd-cpp",memoryBytes:14*F,files:[N(Mt.comfyBoogu,"diffusion_models/boogu_image_turbo_hotfix_int8_convrot.safetensors",11370550632,"ba2e6d956e5e97fccfcfa95eddccc33056306b5d68db37e8ad3ffff575261865","diffusion_model"),_s.qwen3Vl8bQ8,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:4,cfgScale:1},demos:[{url:Ne(...Mt.booguTurbo,"assets/photography_triptych.png"),media:"image",caption:"Photographic samples from the model card"},{url:Ne(...Mt.booguTurbo,"assets/text_rendering_triptych.png"),media:"image",caption:"Text rendering samples from the model card"}]},{id:"boogu-image-edit-turbo",profile:{family:"boogu-image-edit",name:"Boogu-Image Edit",author:"Boogu",speed:2,quality:3,text:!0,bestFor:["editing","instructions"]},name:"Boogu-Image Edit Turbo",author:"Boogu",media:"image",tasks:["image-edit"],summary:"Edits a single picture by written instruction in four steps: adding, removing or replacing things, restyling and changing text.",...Re,homepage:"https://huggingface.co/Boogu/Boogu-Image-0.1-Edit-Turbo",variants:[{id:"int8",label:"8-bit",engine:"sd-cpp",memoryBytes:14*F,files:[N(Mt.comfyBoogu,"diffusion_models/boogu_image_edit_turbo_hotfix_1k_20260708_int8_convrot.safetensors",10326755028,"b0bdd36eb559d62e8169e16a1e8b4438f8be17fc092ca9d43a2d8460c1d79e6a","diffusion_model"),_s.qwen3Vl8bQ8,_s.qwen3Vl8bVision,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:4,cfgScale:1,references:{as:"ref",max:1}},demos:[{url:Ne(...Mt.booguEditTurbo,"assets/edit_cases_combined.png"),media:"image",caption:"Edits from the model card"}]}]}var Mt,_s;var tL=b(()=>{Hn();Mt={comfyHiDream:["Comfy-Org/HiDream-O1-Image","7b75f4cd7e757d55d9bd1d30fb40375fb446f38c"],hiDreamDev:["HiDream-ai/HiDream-O1-Image-Dev","c0bada0e15c54a9f96a6d1ecc35575b32bc21544"],lladaTurboGguf:["fszontagh/LLaDA-Image-Turbo-GGUF","73e2e2adecb76bcf1f89fc37a636912c551349a9"],lladaTurbo:["inclusionAI/LLaDA-Image-Turbo","f4afc52d925bbac4e22a1c947111fc1f127e37e5"],comfyBoogu:["Comfy-Org/Boogu-Image","8606e7df2f5389282617b8b534db290e1f5d7811"],qwen3Vl8b:["unsloth/Qwen3-VL-8B-Instruct-GGUF","b93a7ee713758252c555be4210c00540df954dc2"],booguTurbo:["Boogu/Boogu-Image-0.1-Turbo","53ad54522023f64d049f7f38e4d679359ef3fb92"],booguEditTurbo:["Boogu/Boogu-Image-0.1-Edit-Turbo","132a0ab9051b42c1d9be4919a68873d1f132c0c8"]},_s={qwen3Vl8bQ8:N(Mt.qwen3Vl8b,"Qwen3-VL-8B-Instruct-Q8_0.gguf",8709520224,"cb8616bf6ed228982d9e47d7b72b42195342efa26044b0ee1873e61d9e78d3d7","llm"),qwen3Vl8bVision:N(Mt.qwen3Vl8b,"mmproj-F16.gguf",1159030336,"d406d03ebabefdef86a2c86bf0c1b65f9e046f7a81c218f25de4931b46a07fc4","llm_vision"),lladaTokenizer:N(Mt.lladaTurbo,"tokenizer/tokenizer.json",15297062,"2197aeddaf09785316673451ca6fb86dcfcfdb108972a3145d106b8fa4c927e6","tokenizer"),lladaVae:N(Mt.lladaTurbo,"vae/diffusion_pytorch_model.safetensors",168120872,"19874383f29bd4a716be716520647261e38aeaa50dcc29559e5f8d8186cf8f43","vae"),lladaTurboConnectors:N(Mt.lladaTurboGguf,"llada-image-turbo-connectors-edit.safetensors",3348225976,"e0e88841b1a9eb7b11f813f3f139507438b541a585fc6aa4a7bf842e732304ca","embeddings-connectors")}});function rL(){return[{id:"qwen-image",profile:{family:"qwen-image",name:"Qwen-Image",author:"Qwen (Alibaba)",speed:1,quality:3,text:!0,bestFor:["text","detail","instructions"]},name:"Qwen-Image",author:"Qwen (Alibaba)",media:"image",tasks:["text-to-image"],summary:"A large 20B model that follows long prompts closely and writes long passages of text in English and Chinese. It needs a lot of memory.",...Re,homepage:"https://huggingface.co/Qwen/Qwen-Image",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:25*F,files:[N(bt.qwenImageGguf,"Qwen_Image-Q8_0.gguf",21761817120,"43142b32778dc0568c27395abc6f8291ac53f1de0b98eed919712cf161f248de","diffusion_model"),At.q8,Am]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:16*F,files:[N(bt.qwenImageGguf,"Qwen_Image-Q4_K_M.gguf",13065746976,"645473886d7dbb0103f84c563c798f7b0867293d919752d4d6be6a432b0bc988","diffusion_model"),At.q4,Am]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:2.5,sampler:"euler",flowShift:3},demos:[]},{id:"qwen-image-edit-2511",profile:{family:"qwen-image-edit",name:"Qwen-Image-Edit",author:"Qwen (Alibaba)",speed:1,quality:3,text:!0,bestFor:["editing","instructions","text"]},name:"Qwen-Image-Edit 2511",author:"Qwen (Alibaba)",media:"image",tasks:["image-edit"],summary:"Changes pictures from written instructions, keeping people and objects consistent, and can combine up to three pictures. It can also edit the text inside a picture.",...Re,homepage:"https://huggingface.co/Qwen/Qwen-Image-Edit-2511",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:25*F,files:[N(bt.qwenImageEditGguf,"qwen-image-edit-2511-Q8_0.gguf",22354590304,"0bf71797bf27dac40e3d8c1dc344309cb53f2a08beed6a96120dd77164b3806f","diffusion_model"),At.q8,At.vision,Am]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:16*F,files:[N(bt.qwenImageEditGguf,"qwen-image-edit-2511-Q4_K_M.gguf",12842830432,"07951f61941a81e236cbd4a9b6f250d49626b3ba518f260135bf2e01a87cf1c8","diffusion_model"),At.q4,At.vision,Am]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:2.5,sampler:"euler",flowShift:3,references:{as:"ref",max:3},engineArgs:["--model-args","qwen_image_zero_cond_t=true"]},demos:[]},{id:"longcat-image",profile:{family:"longcat-image",name:"LongCat-Image",author:"Meituan",speed:2,quality:2,text:!0,bestFor:["photo","text"]},name:"LongCat-Image",author:"Meituan",media:"image",tasks:["text-to-image"],summary:"A 6B model for photorealistic images that writes the words you put in quotes, in English and Chinese.",...Re,homepage:"https://huggingface.co/meituan-longcat/LongCat-Image",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(bt.comfyLongCat,"split_files/diffusion_models/longcat_image_bf16.safetensors",12541383144,"7c83c314a3d879d43e5700072033256000f46a56900ae48b209a77ac1921488b","diffusion_model"),At.q8,Q.fluxVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:10*F,files:[N(bt.longCatGguf,"comfy/LongCat-Image-Q8_0.gguf",6705361120,"e45928b01712af742ccec57ac515d54c97ba276e6f86b825022e866ae4f329a5","diffusion_model"),At.q8,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:6*F,files:[N(bt.longCatGguf,"comfy/LongCat-Image-Q4_K_M.gguf",3661869280,"8231f4f177bcb5422cd76028ce740183eda5541fc1b09f5aa6e95bd4fba6992c","diffusion_model"),At.q4,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:5,sampler:"euler",flowShift:3},demos:[{url:Ne(...bt.longCat,"assets/gallery.jpeg"),media:"image",caption:"Samples from the model card"}]},{id:"longcat-image-edit",profile:{family:"longcat-image-edit",name:"LongCat-Image-Edit",author:"Meituan",speed:2,quality:2,text:!0,bestFor:["editing","instructions"]},name:"LongCat-Image-Edit",author:"Meituan",media:"image",tasks:["image-edit"],summary:"Changes a picture from written instructions in English or Chinese, leaving the parts you did not mention as they were.",...Re,homepage:"https://huggingface.co/meituan-longcat/LongCat-Image-Edit",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(bt.comfyLongCat,"split_files/diffusion_models/longcat_image_edit_bf16.safetensors",12541383144,"8e65ba6ab2f6b323c1619347cd681e4ff78a017b608c82c7bf30f1d125925fab","diffusion_model"),At.q8,At.vision,Q.fluxVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:10*F,files:[N(bt.longCatEditGguf,"LongCat-Image-Edit-Q8_0.gguf",6725439840,"a998d17d51943ab15bf3ba3ca1a509be3792987395c3bcb8d6bcbfafa7030a42","diffusion_model"),At.q8,At.vision,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:7*F,files:[N(bt.longCatEditGguf,"LongCat-Image-Edit-Q4_K_M.gguf",3867152736,"104cd11e357a43c5fab60e16e8c8517f8e6b7df596004042b507556145fd4f63","diffusion_model"),At.q4,At.vision,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:4.5,sampler:"euler",flowShift:3,references:{as:"ref",max:1}},demos:[{url:Ne(...bt.longCatEdit,"assets/image_edit_gallery.jpg"),media:"image",caption:"Edits from the model card"}]},{id:"longcat-image-edit-turbo",profile:{family:"longcat-image-edit-turbo",name:"LongCat-Image-Edit Turbo",author:"Meituan",speed:3,quality:2,text:!0,bestFor:["editing","speed"]},name:"LongCat-Image-Edit Turbo",author:"Meituan",media:"image",tasks:["image-edit"],summary:"A distilled LongCat-Image-Edit that changes a picture from written instructions in eight steps.",...Re,homepage:"https://huggingface.co/meituan-longcat/LongCat-Image-Edit-Turbo",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(bt.comfyLongCat,"split_files/diffusion_models/longcat_image_edit_turbo_bf16.safetensors",12541383144,"985119e16854831d1f75d9d141ab4e5af4a643b35abc396593a95654e0b4cd3d","diffusion_model"),At.q8,At.vision,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:8,cfgScale:1,sampler:"euler",flowShift:3,references:{as:"ref",max:1}},demos:[{url:Ne(...bt.longCatEditTurbo,"assets/image_edit_gallery.jpg"),media:"image",caption:"Edits from the model card"}]},{id:"ovis-image-7b",profile:{family:"ovis-image",name:"Ovis-Image",author:"AIDC-AI (Alibaba)",speed:2,quality:2,text:!0,bestFor:["text","illustration"]},name:"Ovis-Image 7B",author:"AIDC-AI (Alibaba)",media:"image",tasks:["text-to-image"],summary:"A 7B model made to write text inside pictures, such as posters, banners and logos, while staying small enough for one graphics card.",...Re,homepage:"https://huggingface.co/AIDC-AI/Ovis-Image-7B",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:18*F,files:[N(bt.comfyOvis,"split_files/diffusion_models/ovis_image_bf16.safetensors",14740943536,"eb3d9e1b201412b3b527472cf82a2c5add6b5a40a37e94d99f11c381f18a9e2b","diffusion_model"),kx,Q.fluxVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:11*F,files:[N(bt.ovisGguf,"ovis_image-Q8_0.gguf",7866528480,"df9eb46ba49c392c6acd2b5762d11b508506a8f378ea8c231d3aec65a8b9c678","diffusion_model"),kx,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:7*F,files:[N(bt.ovisGguf,"ovis_image-Q4_0.gguf",4200182496,"59832ca60a34671579fdc95b48dd772c6014b793b497b4bdadf1f3017d1a0125","diffusion_model"),kx,Q.fluxVae]}],defaults:{size:1024,aspectRatios:je,steps:20,cfgScale:5},demos:[]}]}var bt,At,Am,kx;var Tx=b(()=>{Hn();bt={comfyQwenImage:["Comfy-Org/Qwen-Image","1f12b17be14c89b026c51a91d67c32f84bb047bc"],qwenImageGguf:["QuantStack/Qwen-Image-GGUF","257f261fa92593bed760aa6fa3f7921a49fea00f"],qwenImageEditGguf:["unsloth/Qwen-Image-Edit-2511-GGUF","52838251db242ddd8e8d0118de36c71006d7c397"],qwenVlGguf:["mradermacher/Qwen2.5-VL-7B-Instruct-GGUF","cfa2baa09946b211c107e6e104948987a64dd2c1"],comfyLongCat:["Comfy-Org/LongCat-Image","d49457a376940fa670ac73f4e21763c56638f19c"],longCatGguf:["vantagewithai/LongCat-Image-GGUF","22f38d64150ed3a99454e5e3a3bbfcf639969b05"],longCatEditGguf:["vantagewithai/LongCat-Image-Edit-GGUF","8bfeb76dd77f783aecbe99bcc32f22ee1a45e222"],longCat:["meituan-longcat/LongCat-Image","d2ea50b79a930074c37b9b97ce45e3b2ea8cf4d8"],longCatEdit:["meituan-longcat/LongCat-Image-Edit","7b54ef423aa7854be7861600024be5c56ab7875a"],longCatEditTurbo:["meituan-longcat/LongCat-Image-Edit-Turbo","6a7262de5549f0bf0ec54c08ef7d283ef41f3214"],comfyOvis:["Comfy-Org/Ovis-Image","b7d0cb855e82448c28936c9907a143bf319c80a0"],ovisGguf:["leejet/Ovis-Image-7B-GGUF","0e0e56e1d63bf3c57282cf11846211e683f68871"]},At={q8:N(bt.qwenVlGguf,"Qwen2.5-VL-7B-Instruct.Q8_0.gguf",8098524160,"577bfb3e41f93f00414e594c56a38bbe91207b3b636ab7faf343e34a20aa73ca","llm"),q4:N(bt.qwenVlGguf,"Qwen2.5-VL-7B-Instruct.Q4_K_M.gguf",4683072512,"0f00a930ba3108b6861ddadf74d8ebbd82e257c63eba728e62c3e8970f5eed94","llm"),vision:N(bt.qwenVlGguf,"Qwen2.5-VL-7B-Instruct.mmproj-Q8_0.gguf",853119712,"2185ca0adf339f96845318c7b666f5d242f86bbace5657a89cb834785d0cea57","llm_vision")},Am=N(bt.comfyQwenImage,"split_files/vae/qwen_image_vae.safetensors",253806246,"a70580f0213e67967ee9c95f05bb400e8fb08307e017a924bf3441223e023d1f","vae"),kx=N(bt.comfyOvis,"split_files/text_encoders/ovis_2.5.safetensors",5140950080,"f453ee5e7a25cb23cf2adf7aae3e5b405f22097cb67f2cfcca029688cb3f740d","llm")});function nL(){return[{id:"sdxl-turbo",englishPrompts:!0,profile:Te.sdxlTurbo,name:"SDXL Turbo",author:"Stability AI",media:"image",tasks:["text-to-image","image-to-image"],summary:"A distilled SDXL that makes a 512px image in a single step. The quickest way to try ideas.",license:"Stability AI Community License",licenseUrl:"https://huggingface.co/stabilityai/sdxl-turbo/blob/main/LICENSE.md",commercial:{kind:"limited",revenueUsd:1e6},homepage:"https://huggingface.co/stabilityai/sdxl-turbo",variants:[{id:"fp16",label:"16-bit",engine:"sd-cpp",memoryBytes:8*F,files:[N(tn.sdxlTurbo,"sd_xl_turbo_1.0_fp16.safetensors",6938081905,"e869ac7d6942cb327d68d5ed83a40447aadf20e0c3358d98b2cc9e270db0da26","model")]}],defaults:{references:{as:"init",max:1},size:512,aspectRatios:je,steps:1,cfgScale:1},demos:[{url:Ne(...tn.sdxlTurbo,"output_tile.jpg"),media:"image",caption:"Single-step samples from the model card"}]},{id:"sdxl-base",englishPrompts:!0,loraBase:"sdxl",profile:Te.sdxl,name:"Stable Diffusion XL",author:"Stability AI",media:"image",tasks:["text-to-image","image-to-image"],summary:"The 1024px general-purpose model with the largest ecosystem of fine-tunes and LoRAs.",...nu("CreativeML Open RAIL++-M","https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/LICENSE.md"),homepage:"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0",variants:[{id:"fp16",label:"16-bit",engine:"sd-cpp",memoryBytes:9*F,files:[N(tn.sdxl,"sd_xl_base_1.0.safetensors",6938078334,"31e35c80fc4829d14f90153f4c74cd59c90b779f6afe05a74cd6120b893f7e5b","model")]}],defaults:{references:{as:"init",max:1},size:1024,aspectRatios:je,steps:30,cfgScale:7},demos:[{url:Ne(...tn.sdxl,"01.png"),media:"image",caption:"Samples from the model card"}]},{id:"flux-schnell",englishPrompts:!0,profile:Te.fluxSchnell,name:"FLUX.1 schnell",author:"Black Forest Labs",media:"image",tasks:["text-to-image","image-to-image"],summary:"Detailed 1024px images in four steps, with strong prompt following.",...Re,homepage:"https://huggingface.co/black-forest-labs/FLUX.1-schnell",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(tn.fluxGguf,"flux1-schnell-Q8_0.gguf",12687821728,"f6694941193b10148dbf1f0f498d4ccd3e9875c127fc53946213b68580c66f10","diffusion_model"),Q.fluxT5,Q.fluxClip,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:9*F,files:[N(tn.fluxGguf,"flux1-schnell-Q4_K_S.gguf",6783943712,"4fd16477b3a5296d0cf722c4b92a9fd7f30d09ac7495826e4465d8de9c9fd973","diffusion_model"),Q.fluxT5,Q.fluxClip,Q.fluxVae]}],defaults:{references:{as:"init",max:1},size:1024,aspectRatios:je,steps:4,cfgScale:1,sampler:"euler"},demos:[{url:"https://raw.githubusercontent.com/Comfy-Org/workflow_templates/f8610f7cd567f4b4e9d76320e8774c8fda061723/templates/flux_schnell-1.webp",media:"image",caption:"A sample from ComfyUI's FLUX.1 schnell template"}]},{id:"z-image-turbo",profile:Te.zImage,name:"Z-Image Turbo",author:"Tongyi-MAI (Alibaba)",media:"image",tasks:["text-to-image","image-to-image"],summary:"Photorealistic images in eight steps, and legible text in English and Chinese.",...Re,homepage:"https://huggingface.co/Tongyi-MAI/Z-Image-Turbo",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(tn.comfyZImage,"split_files/diffusion_models/z_image_turbo_bf16.safetensors",12309866400,"2407613050b809ffdff18a4ac99af83ea6b95443ecebdf80e064a79c825574a6","diffusion_model"),Q.qwen3InstructBf16,Q.fluxVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:9*F,files:[N(tn.zImageGguf,"z_image_turbo-Q8_0.gguf",6577440704,"df1c5baa86d1398c979495a6072dbcee79444fdb884a2445582ba0769c44e9a1","diffusion_model"),Q.qwen3InstructQ8,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:6*F,files:[N(tn.zImageGguf,"z_image_turbo-Q4_K.gguf",3864250304,"14b375ab4f226bc5378f68f37e899ef3c2242b8541e61e2bc1aff40976086fbd","diffusion_model"),Q.qwen3InstructQ4,Q.fluxVae]}],defaults:{references:{as:"init",max:1},size:1024,aspectRatios:je,steps:8,cfgScale:1},demos:[{url:Ne(...tn.zImage,"assets/showcase_realistic.png"),media:"image",caption:"Photorealistic samples from the model card"},{url:Ne(...tn.zImage,"assets/showcase_rendering.png"),media:"image",caption:"Text rendering samples from the model card"}]},{id:"wan-2.1-t2v-1.3b",profile:Te.wanLocal,name:"Wan 2.1 T2V 1.3B",author:"Wan-AI (Alibaba)",media:"video",tasks:["text-to-video"],summary:"Short 480p clips from text. The small Wan model, made to run on consumer graphics cards.",...Re,homepage:"https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B",variants:[{id:"fp16",label:"16-bit",engine:"sd-cpp",memoryBytes:7*F,files:[N(tn.comfyWan,"split_files/diffusion_models/wan2.1_t2v_1.3B_fp16.safetensors",2838303560,"be531024cd9018cb5b48c40cfbb6a6191645b1c792eb8bf4f8c1c6e10f924dc5","diffusion_model"),Q.umt5Q8,Q.wan21Vae]}],defaults:{size:832,aspectRatios:["16:9","9:16"],steps:30,cfgScale:6,sampler:"euler",flowShift:3,fps:16,durations:[2,3,5],negativePrompt:Ma},demos:[{url:"https://cloud.video.taobao.com/vod/Jth64Y7wNoPcJki_Bo1ZJTDBvNjsgjlVKsNs05Fqfps.mp4",media:"video",caption:"The Wan 2.1 demo reel from the model card"}]}]}var tn;var sL=b(()=>{_m();Hn();tn={sdxlTurbo:["stabilityai/sdxl-turbo","71153311d3dbb46851df1931d3ca6e939de83304"],sdxl:["stabilityai/stable-diffusion-xl-base-1.0","462165984030d82259a11f4367a4eed129e94a7b"],fluxGguf:["city96/FLUX.1-schnell-gguf","f495746ed9c5efcf4661f53ef05401dceadc17d2"],comfyZImage:["Comfy-Org/Z-Image-Turbo","6fc90a3b1b653e935a0d175e260736de25b84df5"],zImageGguf:["leejet/Z-Image-Turbo-GGUF","c61c0e422dc8b541b7548cf33a4ef8302b0f8085"],zImage:["Tongyi-MAI/Z-Image-Turbo","f332072aa78be7aecdf3ee76d5c247082da564a6"],comfyWan:["Comfy-Org/Wan-2.1","123acf1cc74bccbb9bfff8ac1ee72edc08c2341d"]}});function iL(){return[{id:"qwen3-4b-instruct",name:"Qwen3 4B Instruct",author:"Qwen (Alibaba)",media:"text",tasks:["prompt-translation"],summary:"A language model that puts prompts into English, for the models that read only English. It runs on the processor, in a few seconds per prompt, and is the same file Z-Image reads prompts with: with Z-Image installed, nothing more is downloaded.",...Re,homepage:"https://huggingface.co/Qwen/Qwen3-4B-Instruct-2507",variants:[{id:"q8",label:"8-bit",engine:"llama-cpp",memoryBytes:6*F,files:[oL(Q.qwen3InstructQ8)]},{id:"q4",label:"4-bit",engine:"llama-cpp",memoryBytes:4*F,files:[oL(Q.qwen3InstructQ4)]}],defaults:{size:0,aspectRatios:[],steps:0,cfgScale:0},demos:[]},{id:"qwen2.5-vl-7b",name:"Qwen2.5-VL 7B Instruct",author:"Qwen (Alibaba)",media:"text",tasks:["picture-description"],summary:"A language model that looks at pictures, so the assistant on this computer can tell whether what it made matches what was asked. It runs on the processor, about half a minute per picture. Qwen-Image and LongCat-Image read prompts with the same file.",...Re,homepage:"https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct",variants:[{id:"q4",label:"4-bit",engine:"llama-cpp",memoryBytes:7*F,files:[{...At.q4,role:"model"},{...At.vision,role:"llm_vision"}]}],defaults:{size:0,aspectRatios:[],steps:0,cfgScale:0},demos:[]}]}var oL=(e)=>({...e,role:"model"});var aL=b(()=>{Tx();Hn()});function cL(){return[{id:"real-esrgan-x4plus",profile:{family:"real-esrgan",name:"Real-ESRGAN",author:"Tencent ARC",speed:3,quality:2,text:!1,bestFor:["detail"]},name:"Real-ESRGAN \xD74",author:"Xintao Wang et al. (Tencent ARC)",media:"image",tasks:["upscale"],summary:"Makes a picture four times larger and sharper, keeping it as it is. Small and fast: a 1024px picture comes out at 4096px in seconds.",license:"BSD 3-Clause",licenseUrl:"https://github.com/xinntao/Real-ESRGAN/blob/master/LICENSE",commercial:{kind:"allowed"},homepage:"https://github.com/xinntao/Real-ESRGAN",variants:[{id:"x4plus",label:"\xD74",engine:"sd-cpp",memoryBytes:1.5*F,files:[{name:"RealESRGAN_x4plus.pth",url:Ne(...nX,"RealESRGAN_x4plus.pth"),size:67040989,sha256:"4fa0d38905f75ac06eb49a7951b426670021be3018265fd191d2125df9d682f1",role:"upscale_model"}]}],defaults:{size:1024,aspectRatios:[],steps:1,cfgScale:1,references:{as:"init",max:1},upscale:4},demos:[]}]}var nX;var lL=b(()=>{Hn();nX=["lllyasviel/Annotators","982e7edaec38759d914a963c48c4726685de7d96"]});function mL(){return[{id:"wan-2.2-ti2v-5b",profile:{family:"wan-2.2-ti2v-5b",name:"Wan 2.2 5B",author:"Alibaba",speed:2,quality:2,text:!1,bestFor:["motion","detail"]},name:"Wan 2.2 TI2V 5B",author:"Wan-AI (Alibaba)",media:"video",tasks:["text-to-video","image-to-video"],summary:"720p clips at 24 frames per second, from text or from a starting picture. The Wan 2.2 model sized for a single consumer graphics card.",...Re,homepage:"https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B",variants:[{id:"fp16",label:"16-bit",engine:"sd-cpp",memoryBytes:17*F,files:[N(Kt.comfyWan22,"split_files/diffusion_models/wan2.2_ti2v_5B_fp16.safetensors",9999658848,"456f901338bd9eadbded3828b819109a9b68e8a525ca5cf8d0049a69fcfeca1e","diffusion_model"),Q.umt5Q8,Px]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:12*F,files:[N(Kt.ti2v5bGguf,"Wan2.2-TI2V-5B-Q8_0.gguf",5400179040,"57bece983817ab2f957546683bb670f13be7d99022d45674840cd999a050ea8f","diffusion_model"),Q.umt5Q8,Px]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:10*F,files:[N(Kt.ti2v5bGguf,"Wan2.2-TI2V-5B-Q4_K_M.gguf",3433116000,"95b19697b7f98e65b0a543640e9ca7b4dfec32e2a6e3731e8e10708be52655e2","diffusion_model"),Q.umt5Q8,Px]}],defaults:{size:1280,aspectRatios:["16:9","9:16"],steps:30,cfgScale:6,sampler:"euler",flowShift:3,fps:24,durations:[2,3,5],negativePrompt:Ma,references:{as:"init",max:1}},demos:[{url:Ex,media:"video",caption:"The Wan 2.2 demo reel from the model card"}]},{id:"wan-2.2-t2v-a14b",profile:{family:"wan-2.2-t2v-a14b",name:"Wan 2.2 14B",author:"Alibaba",speed:1,quality:3,text:!1,bestFor:["motion","cinema"]},name:"Wan 2.2 T2V A14B",author:"Wan-AI (Alibaba)",media:"video",tasks:["text-to-video"],summary:"The largest open Wan model for clips from text, with two experts, one for the overall layout and one for detail. Strong at cinematic lighting and complex motion, but slow on consumer cards.",...Re,homepage:"https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:36*F,files:[N(Kt.t2vA14bGguf,"LowNoise/Wan2.2-T2V-A14B-LowNoise-Q8_0.gguf",15404970496,"71574f62260f3ba305c31085c922a2b1b6672dbfdbe07717c066688ea56966fc","diffusion_model"),N(Kt.t2vA14bGguf,"HighNoise/Wan2.2-T2V-A14B-HighNoise-Q8_0.gguf",15404970496,"e15fecd4ce8f7effe1c4d9ab2c51d37b071bf3dd8b7f1b73e9fc27ac28f6820a","high-noise-diffusion-model"),Q.umt5Q8,Q.wan21Vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:24*F,files:[N(Kt.t2vA14bGguf,"LowNoise/Wan2.2-T2V-A14B-LowNoise-Q4_K_M.gguf",9650090496,"091a5bae02e14aa016bc9b10a7892efda4c629346b81c5dcebbe30ea2ac8923a","diffusion_model"),N(Kt.t2vA14bGguf,"HighNoise/Wan2.2-T2V-A14B-HighNoise-Q4_K_M.gguf",9650090496,"e0c490c6e316fd91ff52034e4ca66b825717e33ff11624585c0ccfcb5d410c59","high-noise-diffusion-model"),Q.umt5Q8,Q.wan21Vae]}],defaults:fL,demos:[{url:Ex,media:"video",caption:"The Wan 2.2 demo reel from the model card"}]},{id:"wan-2.2-i2v-a14b",profile:{family:"wan-2.2-i2v-a14b",name:"Wan 2.2 14B Image to Video",author:"Alibaba",speed:1,quality:3,text:!1,bestFor:["motion","cinema"]},name:"Wan 2.2 I2V A14B",author:"Wan-AI (Alibaba)",media:"video",tasks:["image-to-video"],summary:"Brings a picture to life: the largest open Wan model, making a clip that starts from the given frame and follows the prompt.",...Re,homepage:"https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:36*F,files:[N(Kt.i2vA14bGguf,"LowNoise/Wan2.2-I2V-A14B-LowNoise-Q8_0.gguf",15406608896,"029c7adc74de4f7804905c5e4fb9335d0862cd2fc37191df526aeac13b64425e","diffusion_model"),N(Kt.i2vA14bGguf,"HighNoise/Wan2.2-I2V-A14B-HighNoise-Q8_0.gguf",15406608896,"619a66032c28e1b27882dfccc0bf93e51edb1491e8d4e4c6f291726abe4de8aa","high-noise-diffusion-model"),Q.umt5Q8,Q.wan21Vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:24*F,files:[N(Kt.i2vA14bGguf,"LowNoise/Wan2.2-I2V-A14B-LowNoise-Q4_K_M.gguf",9651728896,"e2f98d834af009d035c6b0918268f2eba0aa8a63025ce942277e2384d40b0866","diffusion_model"),N(Kt.i2vA14bGguf,"HighNoise/Wan2.2-I2V-A14B-HighNoise-Q4_K_M.gguf",9651728896,"836250abfaa3411694e2c9cf3a0cc18265329d5156d81aa116d5366b0f8f02e7","high-noise-diffusion-model"),Q.umt5Q8,Q.wan21Vae]}],defaults:{...fL,references:{as:"init",max:1}},demos:[{url:Ex,media:"video",caption:"The Wan 2.2 demo reel from the model card"}]},{id:"wan-2.1-t2v-14b",profile:{family:"wan-2.1-t2v-14b",name:"Wan 2.1 14B",author:"Alibaba",speed:1,quality:2,text:!1,bestFor:["motion"]},name:"Wan 2.1 T2V 14B",author:"Wan-AI (Alibaba)",media:"video",tasks:["text-to-video"],summary:"Clips from text with more detail and steadier motion than the small Wan 2.1, at the cost of speed and memory.",...Re,homepage:"https://huggingface.co/Wan-AI/Wan2.1-T2V-14B",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:21*F,files:[N(Kt.t2v14bGguf,"wan2.1-t2v-14b-Q8_0.gguf",15879461504,"cd4f1cc5cd4b63f25898340e997d6299984114e8755be5407bc585a1e0ec9f38","diffusion_model"),Q.umt5Q8,Q.wan21Vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(Kt.t2v14bGguf,"wan2.1-t2v-14b-Q4_K_M.gguf",10124581504,"c9a64d612831debbac77af93744d4b5196b840bf65e9f9f5b958d03fc3baddf2","diffusion_model"),Q.umt5Q8,Q.wan21Vae]}],defaults:pL,demos:[{url:dL,media:"video",caption:"The Wan 2.1 demo reel from the model card"}]},{id:"wan-2.1-i2v-14b-480p",profile:{family:"wan-2.1-i2v-14b",name:"Wan 2.1 14B Image to Video",author:"Alibaba",speed:1,quality:2,text:!1,bestFor:["motion"]},name:"Wan 2.1 I2V 14B 480P",author:"Wan-AI (Alibaba)",media:"video",tasks:["image-to-video"],summary:"Animates a picture into a 480p clip that starts from it and follows the prompt.",...Re,homepage:"https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-480P",variants:[{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:23*F,files:[N(Kt.i2v14bGguf,"wan2.1-i2v-14b-480p-Q8_0.gguf",18144640384,"db961e33570a3a7902614ea52b6e77a33d284dfc85743a05e880a02da1164b45","diffusion_model"),Q.umt5Q8,uL,Q.wan21Vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:16*F,files:[N(Kt.i2v14bGguf,"wan2.1-i2v-14b-480p-Q4_K_M.gguf",11341184384,"d91f7139acadb42ea05cdf97b311e5099f714f11fbe4d90916500e2f53cbba82","diffusion_model"),Q.umt5Q8,uL,Q.wan21Vae]}],defaults:{...pL,references:{as:"init",max:1}},demos:[{url:dL,media:"video",caption:"The Wan 2.1 demo reel from the model card"}]}]}var Kt,Px,uL,dL="https://cloud.video.taobao.com/vod/Jth64Y7wNoPcJki_Bo1ZJTDBvNjsgjlVKsNs05Fqfps.mp4",Ex="https://cloud.video.taobao.com/vod/4szTT1B0LqXvJzmuEURfGRA-nllnqN_G2AT0ZWkQXoQ.mp4",pL,fL;var hL=b(()=>{Hn();Kt={comfyWan21:["Comfy-Org/Wan-2.1","123acf1cc74bccbb9bfff8ac1ee72edc08c2341d"],comfyWan22:["Comfy-Org/Wan-2.2","ee6f4a40737a995bf5818954cfce6d59443b0f04"],ti2v5bGguf:["QuantStack/Wan2.2-TI2V-5B-GGUF","57437632ddd08bdcbd1508c866aa22e126ed51d2"],t2vA14bGguf:["QuantStack/Wan2.2-T2V-A14B-GGUF","73eafba53a1a8f29254e4c77f92e74ea27d7cd6f"],i2vA14bGguf:["QuantStack/Wan2.2-I2V-A14B-GGUF","6c6717459277b9cd1f72579d78a0fd62a79e57dc"],t2v14bGguf:["city96/Wan2.1-T2V-14B-gguf","511cbce9f475a6ca0269be901d23b125f44f5c0d"],i2v14bGguf:["city96/Wan2.1-I2V-14B-480P-gguf","b4b6b3b3f0f64975fb33b1d5d1a46ca24e065f03"]},Px=N(Kt.comfyWan22,"split_files/vae/wan2.2_vae.safetensors",1409400960,"e40321bd36b9709991dae2530eb4ac303dd168276980d3e9bc4b6e2b75fed156","vae"),uL=N(Kt.comfyWan21,"split_files/clip_vision/clip_vision_h.safetensors",1264219396,"64a7ef761bfccbadbaa3da77366aac4185a6c58fa5de5f589b42a65bcc21f161","clip_vision"),pL={size:832,aspectRatios:["16:9","9:16"],steps:30,cfgScale:6,sampler:"euler",flowShift:3,fps:16,durations:[2,3,5],negativePrompt:Ma},fL={size:832,aspectRatios:["16:9","9:16"],steps:10,cfgScale:3.5,sampler:"euler",flowShift:3,fps:16,durations:[2,3,5],negativePrompt:Ma,engineArgs:["--high-noise-steps","8","--high-noise-cfg-scale","3.5","--high-noise-sampling-method","euler"]}});function gL(){return[{id:"z-image",profile:{family:"z-image",name:"Z-Image",author:"Tongyi-MAI",speed:1,quality:3,text:!0,bestFor:["photo","detail"]},name:"Z-Image",author:"Tongyi-MAI (Alibaba)",media:"image",tasks:["text-to-image","image-to-image"],summary:"The undistilled base model behind Z-Image Turbo: slower, but more varied, and it follows negative prompts. A good base for fine-tunes and LoRAs.",...Re,homepage:"https://huggingface.co/Tongyi-MAI/Z-Image",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:15*F,files:[N(ot.comfyZImage,"split_files/diffusion_models/z_image_bf16.safetensors",12309866400,"996a67d3ff666946b1c25cbc16d1b1918b6cc0ac166309e23fe3b3d830263dee","diffusion_model"),Q.qwen3InstructBf16,Q.fluxVae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:10*F,files:[N(ot.zImageGguf,"z-image-Q8_0.gguf",7224707136,"a51d4e36f84caa972e0eff65e8bd2961add14374d8a7038a51eefea2fe45f2c9","diffusion_model"),Q.qwen3InstructQ8,Q.fluxVae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:7*F,files:[N(ot.zImageGguf,"z-image-Q4_K_M.gguf",3850115136,"e7fe0cd70917d8f266df936672210b5397bca8092a22608cf2c1fdc266f78a8c","diffusion_model"),Q.qwen3InstructQ4,Q.fluxVae]}],defaults:{references:{as:"init",max:1},size:1024,aspectRatios:je,steps:28,cfgScale:5},demos:[{url:Ne(...ot.zImage,"teaser.jpg"),media:"image",caption:"Samples from the model card"}]},{id:"z-image-l2p",profile:{family:"z-image-l2p",name:"Z-Image L2P",author:"NJU PCALab",speed:1,quality:2,text:!1,bestFor:["detail"]},name:"Z-Image L2P",author:"NJU PCALab",media:"image",tasks:["text-to-image"],summary:"Z-Image Turbo moved to pixel space: it draws pixels directly, with no image decoder. A research model that comes close to the original's prompt following.",...Re,homepage:"https://huggingface.co/zhen-nan/L2P",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:14*F,files:[N(ot.l2p,"model-1k-merge.safetensors",19569401798,"e785acf53a336bb2c10640a640116fd0bb770ffc7e84d2440b8ad6e7b420c666","diffusion_model"),Q.qwen3InstructBf16]}],defaults:{size:1024,aspectRatios:je,steps:30,cfgScale:2,sampler:"euler",engineArgs:["--type","bf16"]},demos:[]},{id:"ernie-image-turbo",profile:{family:"ernie-image-turbo",name:"ERNIE-Image Turbo",author:"Baidu",speed:2,quality:3,text:!0,bestFor:["text","illustration"]},name:"ERNIE-Image Turbo",author:"Baidu",media:"image",tasks:["text-to-image"],summary:"Images in eight steps that follow detailed instructions and render text well, suited to posters, comics and multi-panel layouts.",...Re,homepage:"https://huggingface.co/baidu/ERNIE-Image-Turbo",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:19*F,files:[N(ot.comfyErnie,"diffusion_models/ernie-image-turbo.safetensors",16067025480,"741a4cc0467d4b9f04490d7faa9a5869ff4aa97eb2914927a1df9abb070e8e52","diffusion_model"),rn.llmBf16,rn.vae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:12*F,files:[N(ot.ernieTurboGguf,"ernie-image-turbo-Q8_0.gguf",8694907584,"c90af9c9a2cf6f7d0404c3fb17e84391c59b240362284f702168f8d71cfeba5d","diffusion_model"),rn.llmQ8,rn.vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:9*F,files:[N(ot.ernieTurboGguf,"ernie-image-turbo-UD-Q4_K_M.gguf",5778817728,"b55c6a0104d7635097665527267bbd934d5fa43c00722ef6c42dd1e6470d64c4","diffusion_model"),rn.llmQ4,rn.vae]}],defaults:{size:1024,aspectRatios:je,steps:8,cfgScale:1,vramBudget:!0},demos:[]},{id:"ernie-image",profile:{family:"ernie-image",name:"ERNIE-Image",author:"Baidu",speed:1,quality:3,text:!0,bestFor:["text","instructions"]},name:"ERNIE-Image",author:"Baidu",media:"image",tasks:["text-to-image"],summary:"The full ERNIE-Image model: slower than Turbo, with stronger instruction following and text rendering for posters, comics and structured layouts.",...Re,homepage:"https://huggingface.co/baidu/ERNIE-Image",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:19*F,files:[N(ot.comfyErnie,"diffusion_models/ernie-image.safetensors",16067025480,"94a35abaa0899cccc34d2e37310abf74a0a714256526117bba782c7eb4eb91c7","diffusion_model"),rn.llmBf16,rn.vae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:12*F,files:[N(ot.ernieGguf,"ernie-image-Q8_0.gguf",8694907584,"dc6ed503a2b66e01a86edbda7c557141a95ad4c262a5ee6cad90c41559e0a499","diffusion_model"),rn.llmQ8,rn.vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:9*F,files:[N(ot.ernieGguf,"ernie-image-UD-Q4_K_M.gguf",5774754496,"62c7ab59ad9dfcf4333a5a6bf4bfe7304bb184b8be347bae90ecb626dd419a1c","diffusion_model"),rn.llmQ4,rn.vae]}],defaults:{size:1024,aspectRatios:je,steps:50,cfgScale:5,vramBudget:!0},demos:[]},{id:"moss-image",profile:{family:"moss-image",name:"MOSS-Image",author:"OpenMOSS",speed:1,quality:2,text:!0,bestFor:["text","instructions"]},name:"MOSS-Image",author:"OpenMOSS",media:"image",tasks:["text-to-image"],summary:"A 5B model, fine-tuned for clean layouts and legible text. It reads plain prompts, tag lists and JSON layouts that place text and objects.",...Re,homepage:"https://huggingface.co/OpenMOSS-Team/MOSS-Image-SFT",variants:[{id:"bf16",label:"16-bit",engine:"sd-cpp",memoryBytes:13*F,files:[N(ot.comfyMoss,"diffusion_models/moss_image_sft_bf16.safetensors",10164655808,"f96738d8116d78b7316b57c663d8c98591ddafab7488f48e3099b7655e34ab6f","diffusion_model"),xs.llmQ8,xs.tokenizer,xs.vae]},{id:"q8",label:"8-bit",engine:"sd-cpp",memoryBytes:9*F,files:[N(ot.mossSftGguf,"MOSS-Image-SFT-Q8_0.gguf",5705571168,"740040af6492ae5f951d5b7a8cb56927c1a02e64696f4bd4bd124bb798ce5635","diffusion_model"),xs.llmQ8,xs.tokenizer,xs.vae]},{id:"q4",label:"4-bit",engine:"sd-cpp",memoryBytes:6*F,files:[N(ot.mossSftGguf,"MOSS-Image-SFT-Q4_K.gguf",3327400800,"902dbb0364d8b313cd91792b3cfe7c87b987386f0c5414986f3f1027b82b2225","diffusion_model"),xs.llmQ4,xs.tokenizer,xs.vae]}],defaults:{size:1024,aspectRatios:je,steps:50,cfgScale:3},demos:[{url:Ne(...ot.mossSft,"assets/teaser.webp"),media:"image",caption:"Samples from the model card"},{url:Ne(...ot.mossSft,"assets/showcase/text-rendering.webp"),media:"image",caption:"Text rendering samples from the model card"}]}]}var ot,rn,xs;var yL=b(()=>{Hn();ot={zImage:["Tongyi-MAI/Z-Image","04cc4abb7c5069926f75c9bfde9ef43d49423021"],comfyZImage:["Comfy-Org/Z-Image","94d47a468ec820d29a5dc09d4642539d76d49542"],zImageGguf:["unsloth/Z-Image-GGUF","a84a5f4e7dcff6bc446c0a54a477a4a21aa800b0"],l2p:["zhen-nan/L2P","df14648875b75b880a639ba715e9b3ea2aaf2b4f"],comfyErnie:["Comfy-Org/ERNIE-Image","50509a88bc4fb9e89583a98605f4c81dc221eb8c"],ernieGguf:["unsloth/ERNIE-Image-GGUF","7b6dfaae7389b463d7fb4669e33c560d36ad108c"],ernieTurboGguf:["unsloth/ERNIE-Image-Turbo-GGUF","a38270280633a5d318a9f51c18ef95eefb07c423"],ministralGguf:["unsloth/Ministral-3-3B-Instruct-2512-GGUF","7564922f37fa5bbb62b87f09a55c12f1f91d7a6a"],mossSft:["OpenMOSS-Team/MOSS-Image-SFT","f972bd4b4b9e3852133cc5da954d87bc32cd8fb9"],comfyMoss:["Comfy-Org/MOSS-Image","2929efe3cdd506c0a430bcfca70a9a8d805cc095"],mossSftGguf:["leejet/MOSS-Image-SFT-GGUF","2df0cb525ccf55467c6f8a9ee52fa8310db23b34"],qwen35Gguf:["unsloth/Qwen3.5-9B-GGUF","3885219b6810b007914f3a7950a8d1b469d598a5"]},rn={vae:N(ot.comfyErnie,"vae/flux2-vae.safetensors",336213556,"d64f3a68e1cc4f9f4e29b6e0da38a0204fe9a49f2d4053f0ec1fa1ca02f9c4b5","vae"),llmBf16:N(ot.comfyErnie,"text_encoders/ministral-3-3b.safetensors",7717637511,"49a750a128863854eac7d85e1a277a7b44bf6ec3646405b84686dfeeca3708ca","llm"),llmQ8:N(ot.ministralGguf,"Ministral-3-3B-Instruct-2512-Q8_0.gguf",3651679520,"920163471715241a9d99367d507e2ad94d1ebc34d0d169d25e5d97a49ec72556","llm"),llmQ4:N(ot.ministralGguf,"Ministral-3-3B-Instruct-2512-Q4_K_M.gguf",2146497824,"fd46fc371ff0509bfa8657ac956b7de8534d7d9baaa4947975c0648c3aa397f4","llm")},xs={vae:N(ot.comfyMoss,"vae/flux2-vae.safetensors",336211292,"868fe7b343cc8f3a19dbcfcafbc3d5f888802be3f89bd81b65b3621a066ce8f3","vae"),tokenizer:N(ot.mossSft,"tokenizer/tokenizer.json",19989325,"06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523","tokenizer"),llmQ8:N(ot.qwen35Gguf,"Qwen3.5-9B-Q8_0.gguf",9527502048,"809626574d0cb43d4becfa56169980da2bb448f2299270f7be443cb89d0a6ae4","llm"),llmQ4:N(ot.qwen35Gguf,"Qwen3.5-9B-Q4_K_M.gguf",5680522464,"03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8","llm")}});function Ix(){return[...nL(),...gL(),...X4(),...rL(),...eL(),...K4(),...mL(),...cL(),...iL()]}var wL=b(()=>{W4();Y4();tL();Tx();sL();aL();lL();hL();yL()});class Cm{service;apiKey;fetch;model=0;constructor(e,t,r=(n,s)=>globalThis.fetch(n,s)){this.service=e;this.apiKey=t;this.fetch=r}toEnglish(e,t){return this.reply(Md,e,t)}async reply(e,t,r,n){let s=sX[this.service];for(let o=this.model;o<s.length;o++){let i=await this.ask(s[o],e,t,r);if(i.status===404)continue;if(!i.ok)throw await ur(i,Rm[this.service]);this.model=o;let a=await this.read(i);if(!a)throw Error("No answer came back");return a}throw new le(`${Rm[this.service]} has none of the models Hatchlight writes with`)}ask(e,t,r,n){if(this.service==="google")return tr(this.fetch,`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,{method:"POST",headers:{"x-goog-api-key":this.apiKey,"content-type":"application/json"},body:JSON.stringify({systemInstruction:{parts:[{text:t}]},contents:[{role:"user",parts:[{text:r}]}]}),signal:n},Rm.google);let s=this.service==="openai"?"https://api.openai.com/v1/chat/completions":"https://openrouter.ai/api/v1/chat/completions";return tr(this.fetch,s,{method:"POST",headers:{authorization:`Bearer ${this.apiKey}`,"content-type":"application/json"},body:JSON.stringify({model:e,messages:[{role:"system",content:t},{role:"user",content:r}]}),signal:n},Rm[this.service])}async read(e){if(this.service==="google")return(await e.json()).candidates?.[0]?.content?.parts?.map((n)=>n.text??"").join("").trim();return(await e.json()).choices?.[0]?.message?.content?.trim()}}var sX,Rm;var bL=b(()=>{Pt();wo();sX={openai:["gpt-5-nano","gpt-4.1-nano","gpt-4o-mini"],google:["gemini-3.5-flash-lite","gemini-2.5-flash-lite","gemini-2.5-flash"],openrouter:["google/gemini-3.5-flash-lite","google/gemini-2.5-flash-lite","openai/gpt-5-nano","openai/gpt-4o-mini"]},Rm={openai:"OpenAI",google:"Google Gemini",openrouter:"OpenRouter"}});function vL(){return[new ym,new bm,new wm,new km,new vm].map(vx)}var _L=b(()=>{gx();yx();wx();bx();_m();xx();H4();G4();gx();yx();wL();wx();bx();_m();xx();bL()});import{existsSync as Ax,readFileSync as su,rmSync as Rx,statSync as oX,writeFileSync as iX}from"fs";import{chmod as TL,mkdir as aX,open as cX}from"fs/promises";import{hostname as Cx,uptime as lX}from"os";import{join as vo,resolve as xL}from"path";function uX(e,t){return{models:async()=>e.listModels(),providers:()=>e.listProviders(t),session:(r)=>e.getSession(t,r),createTurn:(r)=>e.createTurn(t,r),upload:(r)=>e.uploadAsset(t,r),gallery:({query:r,limit:n})=>e.listGallery(t,{query:r,limit:n??20}),async asset(r){let{asset:n,blob:s}=await e.getAssetFile(t,r);return{data:new Uint8Array(await s.arrayBuffer()),mime:n.mime}},sessionUrl:(r)=>`#/s/${encodeURIComponent(r)}`}}class PL{vision=!1;async chat(e,t){await Bun.sleep(600);let r=t.at(-1);if(r?.role==="user"){let n=r.content.map((s)=>s.type==="text"?s.text:"").join(" ");return{text:"",toolCalls:[{id:`call_${t.length}`,name:"generate",arguments:{prompt:n,models:["fake/alpha"]}}]}}return{text:"Done: here it is. (A fake assistant.)",toolCalls:[]}}}function Ox(e,t={}){let{seesEveryProcess:r=pX(),...n}=t,s="hatchlight.lock",o=xL(e,"hatchlight.lock");if(ni.has(o))throw new wn(`Hatchlight is already running on this data directory (process ${process.pid})`);let i=$L(o),a=null;if(i&&!i.heartbeat){let u=RL(o,i,null,r);if(!u.stale)throw u.error;Rx(o,{force:!0}),a=i}let c=Mi(o,{owner:JSON.stringify({...dX(),heartbeat:!0,token:crypto.randomUUID()}),...n});if(!c){let u=$L(o);throw EL(u??{pid:Number.NaN})}ni.add(o),a??=i;let l=xL(e,Vc("hatchlight.lock"));try{mX(l,String(process.pid),a,r)}catch(u){throw ni.delete(o),c(),u}return()=>{hX(l),ni.delete(o),c()}}function $L(e){try{let t=su(e,"utf8"),r=AL(t);try{let n=JSON.parse(t);return{...r,heartbeat:n?.heartbeat===!0}}catch{return r}}catch{return null}}function EL(e){let t=e.host&&e.host!==Cx()?` on ${e.host}`:"",r=Number.isFinite(e.pid)?` (process ${e.pid}${t})`:"";return new wn(`Hatchlight is already running on this data directory${r}. If it stopped, start again in 30 seconds`)}function dX(){return{pid:process.pid,host:Cx(),bootId:IL(),startedAt:new Date().toISOString()}}function IL(){try{return su("/proc/sys/kernel/random/boot_id","utf8").trim()||void 0}catch{return}}function AL(e){try{let t=JSON.parse(e);if(typeof t?.pid==="number")return{pid:t.pid,host:typeof t.host==="string"?t.host:void 0,bootId:typeof t.bootId==="string"?t.bootId:void 0}}catch{}return{pid:Number(e)}}function RL(e,t,r,n){if(r&&t.host===void 0&&t.pid===r.pid)return{stale:!0};if(t.host!==void 0){if(t.host!==Cx())return{stale:!1,error:new wn(`Another Hatchlight (process ${t.pid} on ${t.host}) holds this data directory. Stop that container or server; if it is gone, delete ${e}`)};let s=IL();if(t.pid===process.pid||t.bootId&&s&&t.bootId!==s||!kL(t.pid))return{stale:!0};return{stale:!1,error:EL(t)}}if(fX(e))return{stale:!0};if(n&&t.pid!==process.pid&&!kL(t.pid))return{stale:!0};return{stale:!1,error:new wn(`An older Hatchlight (process ${t.pid}) holds this data directory. If no other Hatchlight uses it, delete ${e}`)}}function pX(){if(process.platform!=="linux")return!0;if(["/.dockerenv","/run/.containerenv","/.flatpak-info"].some((e)=>Ax(e))||process.env.container||process.env.KUBERNETES_SERVICE_HOST)return!1;try{if(/microsoft/i.test(su("/proc/version","utf8")))return!1;let e=su("/proc/1/comm","utf8").trim();return e==="systemd"||e==="init"}catch{return!1}}function fX(e){try{return oX(e).mtimeMs<Date.now()-lX()*1000}catch{return!1}}function mX(e,t,r,n){if(ni.has(e))throw new wn(`Hatchlight is already running on this data directory (process ${process.pid})`);let s=null;for(let o=0;o<2;o++)try{return iX(e,t,{flag:"wx"}),ni.add(e),s}catch(i){if(i.code!=="EEXIST")throw i;let a=AL(su(e,"utf8")),c=RL(e,a,r,n);if(!c.stale)throw c.error;s=a,Rx(e,{force:!0})}throw new wn("Could not lock the data directory")}function hX(e){ni.delete(e),Rx(e,{force:!0})}function kL(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function La(e){let r=vo(e,"hatchlight.sqlite"),n=vo(e,Vc("hatchlight.sqlite"));return!Ax(r)&&Ax(n)?n:r}async function gX(e,t=process.platform){if(await aX(e,{recursive:!0,mode:448}),t!=="win32")await TL(e,448)}async function yX(e,t=process.platform){if(await(await cX(e,"a",384)).close(),t==="win32")return;for(let r of[e,`${e}-wal`,`${e}-shm`])await TL(r,384).catch((n)=>{if(n.code!=="ENOENT")throw n})}async function CL(e){let t=e.providers??vL(),r=lt(process.env,"FAKE")==="1";if(r){let B=new sp;B.delayMs=1500;let ce=new sp("fake-paid",["gamma"]);ce.requiresKey=!0,ce.delayMs=1500,t.push(B,ce)}let n=e.localModels??Ix(),s=new Yb({root:e.modelsDir??vo(e.dataDir,"models"),catalog:n,engines:e.engines??$x(),fetch:e.fetch,hardware:e.hardware,checkEngine:e.checkEngine,locationFile:e.modelsLocationFile,enginesDir:lt(process.env,"ENGINES_DIR")}),o=new nv({dir:e.trainerDir??vo(e.dataDir,"trainer"),gpu:s.gpu,loras:s.loras,baseModel:async()=>{let B=await s.runtime("sdxl-base").catch(()=>null),ce=B?.files.model;if(!B||!ce)throw new O("Install Stable Diffusion XL in Models first: LoRAs are trained on it","trainingNeedsBase");return{file:ce,scratch:B.scratch}},letGo:async()=>{await i.unloadIdle(),await P.stopAndWait()},...e.trainerOptions}),i=new Sb({store:s,catalog:n});await i.load();let a=new sv;for(let B of[...t,i])a.register(B);i.onChange=()=>a.refresh(i.id),await gX(e.dataDir);let c=Ox(e.dataDir);await yX(La(e.dataDir));let l=new Bc(La(e.dataDir),e.migrationsDir),u=l.accounts(),d=new Xy(vo(e.dataDir,"assets"),(B,ce)=>u.addAssetBytes(B,ce)),p=null,f=await(async()=>{try{let B=new nb(vo(e.dataDir,"auth.json"),s1(e.dataDir));return p=await B.prepare(),B}catch(B){throw l.close(),c(),B}})();if(p)console.warn(`The saved API keys could not be read with this secret, so Hatchlight starts without them. They are kept in ${p.file}: to use them again, stop Hatchlight, put back the secret they were saved with (HATCHLIGHT_SECRET_FILE, or secret.key in the data directory) and move that file back to auth.json. Otherwise, enter the keys again.`);let m=new Set,h=new lv(vo(e.dataDir,"settings.json")),g=new $c(u,{hasher:e.passwordHasher,assetQuotaBytes:e.server?e.assetQuotaBytes:null,adoptLocal:async(B)=>{await h.moveUser(As.userId,B),await d.moveUser(As.userId,B),await f.moveUser(As.userId,rs.userId)}});if(e.server)await g.resumeAdoption();let w=({userId:B,tokenId:ce},Pe)=>{let ut=g.getUser(B);if(!ut||ut.disabledAt!=null||!wi(ut))return"paidNotAllowed";if(ce){let Je=g.liveToken(ce);if(!Je||Je.userId!==B||!Je.scopes.includes("paid"))return"tokenNotPaid";if(Je.spendLimitUsd!=null&&g.spentByToken(ce)>=Je.spendLimitUsd)return"tokenLimitReached"}return Pe==="server"&&ut.monthlyLimitUsd!=null&&g.spentThisMonth(B)>=ut.monthlyLimitUsd?"monthlyLimitReached":null},v=e.server?w:void 0,_=(B)=>v?.({userId:B},"personal")!=="paidNotAllowed",C=e.server?new sb(f,_):f,k=n.find((B)=>B.tasks.includes("prompt-translation")),P=new kb({store:s,model:k?.id??""}),y=k?await P.ready():!1,x=0;s.subscribe((B)=>{if(B.type!=="models.changed")return;let ce=++x;P.ready().then((Pe)=>{if(ce!==x)return;if(y=Pe,!Pe)P.stop()})}),s.onLetGo(()=>i.unloadIdle()),s.onLetGo(()=>P.stopAndWait());let T=new Map,I=async(B,ce)=>{let Pe=a.adapter(ce),ut=Pe?.keyEnv?process.env[Pe.keyEnv]:void 0,Je=await C.find(B,ce)??(ut?{key:ut,source:"server"}:void 0);if(!Je||v?.(B,Je.source))return;return Je},j=async(B,ce,Pe)=>{if(!v)return Pe();let ut=v(B,ce);if(ut)throw Ai(ut);let Je=Ft("spd");await l.addSpending({id:Je,userId:B.userId,tokenId:B.tokenId??null,kind:"language",keySource:ce,jobId:null,costUsd:SL,pending:!0,createdAt:Date.now()});try{let nn=await Pe();return await l.settleSpending(Je,SL),nn}catch(nn){throw await l.releaseSpending(Je),nn}},se=async(B,ce)=>{let Pe=await I(B,ce);if(!Pe)return null;let ut=`${ce}:${Pe.key}`,Je=T.get(ut);if(!Je)Je=new Cm(ce,Pe.key,e.fetch),T.set(ut,Je);let nn=Je;return{toEnglish:(bn,Za)=>j(B,Pe.source,()=>nn.toEnglish(bn,Za)),reply:(bn,Za,qm,Fm)=>j(B,Pe.source,()=>nn.reply(bn,Za,qm,Fm))}},we=async(B)=>{let{translateWith:ce}=await h.get(B);if(ce==="off")return null;if(ce==="local")return y?P:null;return se(B,ce)},de=async(B)=>{let ce=await Ye(B),Pe=YE(await h.get(B),y,(ut)=>ce.has(ut));if(Pe==="local")return P;return Pe?se(B,Pe):null},qe=["openai","google","openrouter"],Ye=async(B)=>{let ce=new Set;for(let Pe of qe)if(await I(B,Pe))ce.add(Pe);return ce},Fe=async(B)=>{let ce=await Ye(B);return e1(await h.get(B),y,(Pe)=>ce.has(Pe))},Wt=new Map,di=async(B)=>{let ce=await Fe(B);if(ce==="local")return P;if(!ce)return null;let Pe=await I(B,ce);if(!Pe)return null;let ut=`${ce}:${Pe.key}`,Je=Wt.get(ut);if(!Je)Je=new Pm(ce,Pe.key,e.fetch),Wt.set(ut,Je);let nn=Je;return{vision:nn.vision,chat:(bn,Za,qm,Fm)=>j(B,Pe.source,()=>nn.chat(bn,Za,qm,Fm))}},Fa=new tb({repo:l,assets:d,registry:a,keys:C,paidRefusal:v,translator:we}),pi=new av({repo:l,assets:d,registry:a,keys:C,engine:Fa,storageRefusal:e.server?(B)=>g.storageRefusal(B):void 0}),Va=n.find((B)=>B.tasks.includes("picture-description")),uu=Va?new Pb({store:s,model:Va.id}):null,eS=new Av({store:{add:(B,ce)=>l.addEntry(ce,B.userId),update:(B,ce,Pe)=>l.updateEntry(B,ce,Pe),list:(B,ce)=>l.listEntries(B,ce)},reel:(B)=>uX(pi,B),eyes:async()=>uu&&await uu.ready()?uu:null,brain:async(B)=>e.assistantModel??await di(B)??(r?new PL:null),startSession:(B,ce)=>pi.startSession(B,ce)});return{service:pi,accounts:g,deviceKey:e.server?S4(vo(e.dataDir,"device.key")):void 0,paidRefusal:v,keysLost:({userId:B,owner:ce})=>{let Pe=p;if(!Pe||m.has(B))return!1;return Pe.owners.includes(B)||ce&&Pe.owners.includes(rs.userId)},dismissKeysLost:(B)=>{m.add(B)},engine:Fa,models:s,trainer:o,captioner:uu??void 0,settings:h,assistant:eS,assistantBrain:async(B)=>await Fe(B)??(e.assistantModel||r?"local":null),translatorReady:()=>y,improvePrompt:async(B,ce,Pe)=>{let ut=await de(B);if(!ut)throw new O("No language model to write with: install the one for this computer or add a key","noLanguageModel");let Je=new Map(pi.listModels().map((bn)=>[bn.id,bn])),nn=ce.modelIds.flatMap((bn)=>Je.get(bn)??[]);return XE(ut,ce.prompt,QE(nn,ce.editing,ce.language),Pe)},moveModels:(B)=>s.relocate(B),start:()=>Fa.start(),close:()=>{eS.close(),o.cancelTraining(),o.cancelInstall(),s.close(),i.close(),P.stop(),l.close(),c()}}}var SL,wn,ni;var OL=b(()=>{Pt();_L();Fo();dx();SL=eb;wn=class wn extends Error{};ni=new Set});import{join as zL,normalize as wX,sep as bX}from"path";function ML(e,t){e.get("*",async(r)=>{let n;try{n=decodeURIComponent(r.req.path)}catch{return r.notFound()}let s=wX(zL(t,n));if(s!==t&&!s.startsWith(t+bX))return r.notFound();let o=Bun.file(s);if(r.req.path!=="/"&&await o.exists()){let i=r.req.path.startsWith("/assets/");return new Response(o,{headers:{"cache-control":i?"public, max-age=31536000, immutable":"no-cache"}})}return new Response(Bun.file(zL(t,"index.html")),{headers:{"cache-control":"no-cache"}})})}var NL=()=>{};var Om=b(()=>{E0();dN();C4();OL();gm();NL()});import{parseArgs as vX}from"util";function Ss(e){let t=e[0]?.map((r,n)=>Math.max(...e.map((s)=>s[n]?.length??0)));return e.map((r)=>r.map((n,s)=>s===r.length-1?n:n.padEnd(t?.[s]??0)).join(" ").trimEnd())}function xt(e){let t=["B","KB","MB","GB","TB"],r=e,n=0;while(r>=1000&&n<t.length-1)r/=1000,n++;let s=n===0||r>=100?0:1;return`${r.toFixed(s)} ${t[n]}`}function Mx(e){let t=Math.max(0,Math.round(e)),r=Math.floor(t/3600),n=Math.floor(t%3600/60),s=t%60;if(r>0)return`${r}h ${String(n).padStart(2,"0")}m`;if(n>0)return`${n}m ${String(s).padStart(2,"0")}s`;return`${s}s`}function si(e,t,r,n=Number.MAX_SAFE_INTEGER){let s=e[t];if(s==null)return;let o=Number(s);if(!Number.isInteger(o)||o<r||o>n)throw new ie(`--${t} takes a whole number from ${r}${n<Number.MAX_SAFE_INTEGER?` to ${n}`:" up"}.`);return o}function Gn(e,t,r){if(!e)throw new ie(`Give ${r}.`);if(!t.test(e))throw new ie(`Not ${r}: ${e}`);return e}function oi(e,t){if(t.aborted)return Promise.resolve();return new Promise((r)=>{let n=()=>{clearTimeout(s),t.removeEventListener("abort",n),r()},s=setTimeout(n,e);t.addEventListener("abort",n,{once:!0})})}function Nx(e,t){try{let{values:r,positionals:n}=vX({args:t,options:{...zx,...e.options},allowPositionals:!0}),s=r;if(s["no-wait"])s.wait=!1;return{values:s,positionals:n}}catch(r){throw new ie(r.message)}}var ie,G,zx,vt=` --json Print the result as JSON, for scripts
|
|
140
|
+
--data-dir <p> The data directory (default: the app's)
|
|
141
|
+
-h, --help Show this help`,_t=(e,t)=>e.out(JSON.stringify(t,null,2)),ou=(e,t)=>e.out(JSON.stringify(t));var ii=b(()=>{ie=class ie extends Error{};G={ok:0,failed:1,usage:2,interrupted:130},zx={json:{type:"boolean",default:!1},"data-dir":{type:"string"},resources:{type:"string"},help:{type:"boolean",short:"h",default:!1}}});import{mkdir as LL,readFile as BL,stat as _X,writeFile as xX}from"fs/promises";import{extname as SX,join as $X,resolve as Da}from"path";function kX(e){if(Gr(e))return"free";if(e.pricing?.usdPerOutput!=null)return`$${e.pricing.usdPerOutput}/${e.media}`;if(e.pricing?.usdPerSecond!=null)return`$${e.pricing.usdPerSecond}/s`;return"paid"}function qL(e){return TX[e]??`.${e.split("/")[1]?.split(/[;+]/)[0]??"bin"}`}async function PX(e){return(await _X(e).catch(()=>null))?.isDirectory()??!1}async function iu(e){return!e.endsWith("/")&&!e.endsWith("\\")&&SX(e)!==""&&!await PX(e)}async function zm(e,t,r,n){let s=!await iu(r);if(!s&&t.length>1)throw Dx(r);if(s)await LL(r,{recursive:!0}).catch((i)=>{if(i.code!=="EEXIST")throw i;throw new ie(`${r} is a file, not a folder.`)});let o=[];for(let i of t){let{data:a,mime:c}=await e.asset(i),l=s?$X(r,`${i}${qL(c)}`):r;if(!s)await LL(Da(l,".."),{recursive:!0});try{await xX(l,a,{flag:n?"w":"wx"})}catch(u){if(u.code!=="EEXIST")throw u;throw new ie(`${l} exists; pass --force to replace it.`)}o.push(l)}return o}async function EX(e,t,r){let n=[];for(let s of r){if(In.test(s)){n.push(s);continue}let o=Da(t.cwd,s),i=await BL(o).catch(()=>{throw new ie(`Cannot read ${s}: not a picture id or a file.`)});n.push((await e.upload(new Uint8Array(i))).id)}return n}function AX(e,t){let r=t.find((o)=>o.id===e.modelId)?.name??e.modelId,n=e.status==="failed"&&e.error?`failed: ${e.error}`:e.status==="succeeded"?`done ${IX(e)}`.trim():e.status,s=e.costUsd?Nr(e.costUsd):"";return[` ${e.id}`,r,n,s,e.assets.map((o)=>o.id).join(" ")]}function FL(e,t){return[`Turn ${e.id}: "${e.prompt}"`,...Ss(e.jobs.map((r)=>AX(r,t)))]}function CX(e,t){if(e.status==="succeeded")return"done";if(e.status!=="queued"&&e.status!=="running")return e.status;if(!t)return e.status==="queued"?"in line":"running";if(t.stage==="queued"&&t.position!=null)return`in line (position ${t.position})`;if(t.step!=null&&t.steps!=null)return`step ${t.step} of ${t.steps}`;if(t.fraction!=null&&t.stage!=="queued")return`${Math.round(t.fraction*100)}%`;return t.stage?RX[t.stage]:"running"}async function Lx(e,t,r,{api:n,io:s,startedServer:o,pollMs:i=500}){let a=r.wait!==!1;if(!a&&o)throw new ie("--no-wait needs Hatchlight running already: a server started for this command stops with it. Start it with `hatchlight`.");let l=e.modelIds.map((h)=>t.find((g)=>g.id===h)).reduce((h,g)=>h+(ml(g,e.count??1,e.durationSeconds)??0),0),u=typeof r.output==="string"?Da(s.cwd,r.output):null;if(u&&e.modelIds.length*(e.count??1)>1&&await iu(u))throw Dx(u);if(l>0)s.err(`This may cost about ${Nr(l)}.`);let d=await EX(n,s,e.references),p=new AbortController,f=new Map,m=()=>p.abort();if(s.signal.addEventListener("abort",m),a)(async()=>{try{for await(let h of n.events(p.signal))if(h.type==="job.progress")f.set(h.jobId,h)}catch{}})();try{let{session:h,turn:g}=await n.createTurn({prompt:e.prompt,modelIds:e.modelIds,referenceAssetIds:d,...e.sessionId&&{sessionId:e.sessionId},...e.aspectRatio&&{aspectRatio:e.aspectRatio},...e.count!=null&&{count:e.count},...e.seed!=null&&{seed:e.seed},...e.durationSeconds!=null&&{durationSeconds:e.durationSeconds},...e.strength!=null&&{strength:e.strength}}),w=g.jobs,v=(T)=>t.find((I)=>I.id===T.modelId)?.name??T.modelId,_=Date.now(),C=new Promise((T)=>s.signal.addEventListener("abort",()=>T(),{once:!0}));while(a&&!dn(w)&&!s.signal.aborted){let T=Math.round((Date.now()-_)/1000);if(s.status(`${w.map((j)=>`${v(j)}: ${CX(j,f.get(j.id))}`).join(" \xB7 ")} \xB7 ${T}s`),await Promise.race([Bun.sleep(i),C]),s.signal.aborted)break;let I=(await n.session(h.id)).turns.find((j)=>j.id===g.id);if(I)w=I.jobs}s.status(null);let k=new Map,P=w.flatMap((T)=>T.assets.map((I)=>I.id)),y=null;if(u&&P.length>0)try{let T=await zm(n,P,u,r.force===!0);for(let[I,j]of P.entries())k.set(j,T[I])}catch(T){y=T.message}let x=o?null:n.sessionUrl(h.id);if(r.json)(r.batch==null?_t:ou)(s,{sessionId:h.id,turnId:g.id,url:x,done:dn(w),jobs:w.map((T)=>({id:T.id,modelId:T.modelId,status:T.status,error:T.error,costUsd:T.costUsd,assets:T.assets.map((I)=>({id:I.id,mime:I.mime,...k.has(I.id)&&{path:k.get(I.id)}}))}))});else{s.out(x?`Session ${h.id} \xB7 ${x}`:`Session ${h.id}`);for(let T of FL({...g,jobs:w},t).slice(1))s.out(T);for(let[T,I]of k)s.out(`Saved ${T} to ${I}`)}if(y)return s.err(`Not saved: ${y} Save it with \`hatchlight get\`.`),G.failed;if(s.signal.aborted)return s.err(o?"Stopped. The server started for this command stops too, and what was not done with it.":`Stopped waiting; it goes on. See how it stands with: hatchlight status ${h.id}`),G.interrupted;if(!a){if(!r.json)s.err(`Started. See how it stands with: hatchlight status ${h.id}`);return G.ok}return w.every((T)=>T.status==="succeeded")?G.ok:G.failed}finally{s.signal.removeEventListener("abort",m),p.abort()}}async function OX(e,t,r){let n=t.join(" ").trim();if(e.batch==null){if(!n)throw new ie("Say what to make.");return[n]}if(n)throw new ie("Give a prompt or --batch, not both.");let s=e.batch,i=(s==="-"?await r.readAll():await BL(Da(r.cwd,s),"utf8").catch(()=>{throw new ie(`Cannot read ${s}.`)})).split(/\r?\n/).map((a)=>a.trim()).filter((a)=>a&&!a.startsWith("#"));if(i.length===0)throw new ie(`${s} has no prompts.`);return i}var TX,Dx=(e)=>new ie(`More than one result cannot go in ${e}; give a folder to --output.`),IX=(e)=>e.startedAt&&e.finishedAt?`${((e.finishedAt-e.startedAt)/1000).toFixed(1)} s`:"",RX,DL=" --allow-paid Also use paid cloud models, on your own API keys",jL=` -o, --output <p> Save what is made: to a folder, or a file for one result
|
|
142
|
+
--force Replace files that exist
|
|
143
|
+
--no-wait Return at once; follow it with \`hatchlight status\`
|
|
144
|
+
(needs Hatchlight running already)
|
|
145
|
+
--session <id> Add to an existing session`,UL,VL;var Mm=b(()=>{Fo();ii();TX={"image/jpeg":".jpg","image/png":".png","image/webp":".webp","image/gif":".gif","image/bmp":".bmp","video/mp4":".mp4","video/webm":".webm"};RX={queued:"in line",retrying:"trying again",translating:"translating the prompt",waitingGpu:"waiting for the graphics card",starting:"starting",loading:"loading the model",lowMemory:"low on graphics memory",generating:"generating"};UL={output:{type:"string",short:"o"},force:{type:"boolean",default:!1},wait:{type:"boolean",default:!0},"no-wait":{type:"boolean",default:!1},session:{type:"string"},"allow-paid":{type:"boolean",default:!1}},VL={models:{summary:"List the models that can be used now",usage:`Usage: hatchlight models [options]
|
|
146
|
+
|
|
147
|
+
Lists installed local models, and cloud models that have an API key. Local
|
|
148
|
+
models are free and run on this computer.
|
|
149
|
+
|
|
150
|
+
--media <m> Only models that make image or video
|
|
151
|
+
${vt}`,options:{media:{type:"string"}},async run(e,t,{api:r,io:n}){let s=e.media;if(s!=null&&s!=="image"&&s!=="video")throw new ie("--media is image or video.");let o=(await Qi(r,!0)).filter((i)=>s==null||i.media===s);if(e.json)return _t(n,o),G.ok;if(o.length===0)return n.err("No model can be used yet. Install a local model with `hatchlight install`, or add an API key with `hatchlight keys set`."),G.ok;for(let i of Ss(o.map((a)=>[a.id,a.name,a.media,kX(a)])))n.out(i);return G.ok}},generate:{summary:"Make pictures or videos from a prompt",usage:`Usage: hatchlight generate <prompt> [options]
|
|
152
|
+
hatchlight generate --batch <file> [options]
|
|
153
|
+
|
|
154
|
+
Makes pictures or videos, waits for them, and prints their ids. Without
|
|
155
|
+
--model, the best free local model that fits is used.
|
|
156
|
+
|
|
157
|
+
--batch <file> One prompt per line, made one after another with the
|
|
158
|
+
same options; "-" reads them from standard input. Empty
|
|
159
|
+
lines and lines starting with # are skipped. With
|
|
160
|
+
--json, one line of JSON per prompt.
|
|
161
|
+
-m, --model <id> A model from \`hatchlight models\`; repeat to compare
|
|
162
|
+
-r, --ref <p> A picture to start from: an id (ast_\u2026) or a file; repeat
|
|
163
|
+
-n, --count <n> How many to make with each model (1 to 8)
|
|
164
|
+
--ratio <r> Aspect ratio, such as 16:9
|
|
165
|
+
--seed <n> A seed, to make the same again
|
|
166
|
+
--strength <s> How much a given picture changes, 0.05 to 1
|
|
167
|
+
--duration <s> Video length in seconds
|
|
168
|
+
${jL}
|
|
169
|
+
${DL}
|
|
170
|
+
${vt}`,options:{model:{type:"string",short:"m",multiple:!0},ref:{type:"string",short:"r",multiple:!0},count:{type:"string",short:"n"},ratio:{type:"string"},seed:{type:"string"},strength:{type:"string"},duration:{type:"string"},batch:{type:"string"},...UL},interruptible:"once",async run(e,t,r){let n=await OX(e,t,r.io),s=e.ref??[],o=si(e,"count",1,8),i=si(e,"seed",0),a=si(e,"duration",1),c=e.strength==null?void 0:Number(e.strength);if(c!=null&&!(Number.isFinite(c)&&c>=0.05&&c<=1))throw new ie("--strength takes a number from 0.05 to 1.");let l=e.session==null?void 0:Gn(e.session,Kr,"a session id"),u=e["allow-paid"]===!0,d=await Qi(r.api,u),p=e.model??[];if(p.length===0){let w=Rp(d,s.length);if(!w)throw new ie(s.length>0?"No installed local model can start from a picture. Name one with --model, or install one with `hatchlight install`.":"No local model is installed. See `hatchlight catalog`, then `hatchlight install <id>`.");p=[w.id]}let f=p.filter((w)=>!d.some((v)=>v.id===w));if(f.length>0){let w=(await Qi(r.api,!0)).filter((v)=>f.includes(v.id));throw new ie(w.length===f.length&&!u?`${f.join(", ")} costs money; pass --allow-paid to use it.`:`Cannot use ${f.join(", ")}: not installed or without an API key. See \`hatchlight models\`.`)}let m={modelIds:p,references:s,sessionId:l,aspectRatio:e.ratio,count:o,seed:i,durationSeconds:a,strength:c};if(e.batch==null)return Lx({...m,prompt:n[0]},d,e,r);let h=typeof e.output==="string"?Da(r.io.cwd,e.output):null;if(h&&n.length>1&&await iu(h))throw Dx(h);let g=G.ok;for(let[w,v]of n.entries()){if(!e.json)r.io.err(`[${w+1}/${n.length}] ${v}`);let _=await Lx({...m,prompt:v},d,e,r);if(_===G.interrupted)return _;g=Math.max(g,_)}return g}},upscale:{summary:"Make a picture larger and sharper",usage:`Usage: hatchlight upscale <picture> [options]
|
|
171
|
+
|
|
172
|
+
Upscales a picture, given by id (ast_\u2026) or as a file, with an installed
|
|
173
|
+
upscaler: a free local one when there is.
|
|
174
|
+
|
|
175
|
+
${jL}
|
|
176
|
+
${DL}
|
|
177
|
+
${vt}`,options:UL,interruptible:"once",async run(e,t,r){let[n,...s]=t;if(!n||s.length>0)throw new ie("Give one picture: an id (ast_\u2026) or a file.");let o=await Qi(r.api,e["allow-paid"]===!0),i=o.filter((l)=>l.capabilities.upscale!=null),a=i.find(Gr)??i[0];if(!a)throw new ie("No upscaler is installed. Install it with `hatchlight install real-esrgan-x4plus`.");let c=e.session==null?void 0:Gn(e.session,Kr,"a session id");return Lx({prompt:`Upscale \xD7${a.capabilities.upscale}`,modelIds:[a.id],references:[n],sessionId:c},o,e,r)}},status:{summary:"Show how a session's generations stand",usage:`Usage: hatchlight status <session> [options]
|
|
178
|
+
|
|
179
|
+
Shows a session's latest turn, and any turn still running.
|
|
180
|
+
|
|
181
|
+
${vt}`,options:{},async run(e,[t],{api:r,io:n}){let s=Gn(t,Kr,"a session id"),[o,i]=await Promise.all([r.session(s),r.models()]),a=o.turns.at(-1),c=o.turns.filter((l)=>l===a||!dn(l.jobs));if(e.json)return _t(n,{...o,turns:c}),G.ok;if(!a)return n.err("The session has nothing in it yet."),G.ok;for(let l of c)for(let u of FL(l,i))n.out(u);return G.ok}},gallery:{summary:"Find pictures and videos made before",usage:`Usage: hatchlight gallery [words] [options]
|
|
182
|
+
|
|
183
|
+
Lists what was made before, newest first, by words in the prompt.
|
|
184
|
+
|
|
185
|
+
-l, --limit <n> How many to list (default 20)
|
|
186
|
+
${vt}`,options:{limit:{type:"string",short:"l"}},async run(e,t,{api:r,io:n}){let s=si(e,"limit",1,500)??20,o=t.join(" ").trim()||void 0,i=await r.gallery({query:o,limit:s});if(e.json)return _t(n,i),G.ok;if(i.length===0)return n.err("Nothing found."),G.ok;for(let a of Ss(i.map((c)=>[c.id,new Date(c.createdAt).toISOString().slice(0,16).replace("T"," "),c.modelId??"uploaded",c.prompt?`"${c.prompt}"`:""])))n.out(a);return G.ok}},get:{summary:"Save pictures or videos to files",usage:`Usage: hatchlight get <id>... [options]
|
|
187
|
+
|
|
188
|
+
Saves pictures or videos, at full size. Without --output they go to the
|
|
189
|
+
current folder, named by id.
|
|
190
|
+
|
|
191
|
+
-o, --output <p> A folder, or a file for one picture
|
|
192
|
+
--force Replace files that exist
|
|
193
|
+
${vt}`,options:{output:{type:"string",short:"o"},force:{type:"boolean",default:!1}},async run(e,t,{api:r,io:n}){if(t.length===0)throw new ie("Give the id of a picture or video (ast_\u2026).");let s=t.map((a)=>Gn(a,In,"a picture id")),o=typeof e.output==="string"?Da(n.cwd,e.output):`${n.cwd}/`,i=await zm(r,s,o,e.force===!0);if(e.json)_t(n,s.map((a,c)=>({id:a,path:i[c]})));else for(let a of i)n.out(a);return G.ok}},cancel:{summary:"Stop a job",usage:`Usage: hatchlight cancel <job> [options]
|
|
194
|
+
|
|
195
|
+
Stops a job that is in line or running. Job ids are in \`hatchlight status\`.
|
|
196
|
+
|
|
197
|
+
${vt}`,options:{},async run(e,[t],{api:r,io:n}){let s=Gn(t,Kr,"a job id");if(await r.cancelJob(s),e.json)_t(n,{id:s,canceled:!0});else n.err(`Canceled ${s}.`);return G.ok}},retry:{summary:"Run a failed or stopped job again",usage:`Usage: hatchlight retry <job> [options]
|
|
198
|
+
|
|
199
|
+
Runs a job that failed or was stopped again. Job ids are in
|
|
200
|
+
\`hatchlight status\`.
|
|
201
|
+
|
|
202
|
+
${vt}`,options:{},async run(e,[t],{api:r,io:n,startedServer:s}){let o=Gn(t,Kr,"a job id");if(s)throw new ie("retry needs Hatchlight running already: a server started for this command would stop the job with it. Start it with `hatchlight`.");if(await r.retryJob(o),e.json)_t(n,{id:o,retried:!0});else n.err(`Running ${o} again.`);return G.ok}},open:{summary:"Open the app, or a session in it",usage:`Usage: hatchlight open [session] [options]
|
|
203
|
+
|
|
204
|
+
Opens the running Hatchlight in the browser, at a session if given.
|
|
205
|
+
|
|
206
|
+
${vt}`,options:{},local:!0,async run(e,[t],{api:r,io:n,url:s}){let o=t==null?s:r.sessionUrl(Gn(t,Kr,"a session id"));if(e.json)_t(n,{url:o});else n.out(o);return n.open(o),G.ok}}}});import{resolve as ZL}from"path";function zX(e){let t=JSON.stringify(e);return t.length>120?`${t.slice(0,117)}...`:t}async function MX(e,t,r,n){let{api:s,io:o,pollMs:i=500}=n,a=typeof r.output==="string"?ZL(o.cwd,r.output):null,c=new Set,l=new Set((await s.conversation(e)).entries.flatMap((f)=>t.has(f.id)&&f.turnId?[f.turnId]:[])),u=o.nextInterrupt(),d=!1,p=!1;for(;;){let f=await s.conversation(e);for(let g of f.entries){if(!t.has(g.id))t.add(g.id),p=DX(g,r,o)||p;if(g.turnId&&!l.has(g.turnId)&&await LX(g.turnId,e,a,r,n))l.add(g.turnId);if(g.confirm?.state==="asked"&&!c.has(g.id)){c.add(g.id);let w=await NX(g,r,o);await s.answerAssistant(e,g.id,w)}}let m=f.entries.some((g)=>g.confirm?.state==="asked"),h=f.entries.some((g)=>g.turnId&&!l.has(g.turnId));if(!f.busy&&!m&&!h)return o.status(null),p?G.failed:d?G.interrupted:G.ok;if(o.status(f.turnId?"Making pictures\u2026":"Thinking\u2026"),await oi(i,u),u.aborted){if(o.status(null),d)return G.interrupted;d=!0,o.err("Stopping the assistant\u2026 (Ctrl+C again to leave now)"),await s.stopAssistant(e).catch(()=>{}),u=o.nextInterrupt()}}}async function NX(e,t,r){let n=e.confirm;if(!n)return!1;let s=`Spend about ${Nr(n.usd)} on ${n.modelNames.join(", ")}?`;if(t.yes)return r.err(`${s} Yes (--yes).`),!0;if(!r.interactive)return r.err(`${s} No: answer at a terminal, or pass --yes.`),!1;let o=await r.readLine(`${s} [y/N] `);return/^y(es)?$/i.test(o?.trim()??"")}async function LX(e,t,r,n,{api:s,io:o}){let i=(await s.session(t)).turns.find((c)=>c.id===e);if(!i)return!0;if(!dn(i.jobs))return!1;let a=i.jobs.flatMap((c)=>c.assets.map((l)=>l.id));if(a.length===0)return!0;if(n.json)ou(o,{turnId:e,made:a});else o.out(` made ${a.join(" ")}`);if(r)try{for(let c of await zm(s,a,r,!1))o.err(` saved ${c}`)}catch(c){o.err(`! Not saved: ${c.message}`)}return!0}function DX(e,t,r){let n=e.message;if(t.json)ou(r,e);else if(n.role==="assistant"){if(r.status(null),n.text.trim())r.out(n.text.trim());for(let s of n.toolCalls)r.err(`\u2192 ${s.name} ${zX(s.arguments)}`)}else if(n.role==="tool"&&!e.turnId){let s=n.content.flatMap((o)=>o.type==="text"?[o.text]:[]).join(" ").split(`
|
|
207
|
+
`)[0];if(s)r.err(` ${s}`)}if(e.error)return r.err(`! ${e.error.message}`),!0;if(e.note==="tooManySteps")r.err("! The assistant took too many steps and stopped.");return!1}var HL;var GL=b(()=>{Fo();ii();Mm();HL={chat:{summary:"Talk with the assistant, which makes pictures for you",usage:`Usage: hatchlight chat [message] [options]
|
|
208
|
+
|
|
209
|
+
Asks the assistant for something, such as "a poster of a lighthouse, then
|
|
210
|
+
make it warmer". It chooses models, makes pictures, looks at them and tries
|
|
211
|
+
again. With a message it answers once; without one, it is a conversation,
|
|
212
|
+
until Ctrl+D. Ctrl+C stops what the assistant is doing.
|
|
213
|
+
|
|
214
|
+
Paid models cost money only after you say yes to each.
|
|
215
|
+
|
|
216
|
+
--session <id> Go on with a conversation
|
|
217
|
+
-o, --output <p> Save the pictures it makes to a folder
|
|
218
|
+
--yes Say yes to paid generations without asking
|
|
219
|
+
${vt}`,options:{session:{type:"string"},output:{type:"string",short:"o"},yes:{type:"boolean",default:!1}},interruptible:"repeat",async run(e,t,r){let{api:n,io:s}=r;if(typeof e.output==="string"&&await iu(ZL(s.cwd,e.output)))throw new ie("--output is a folder for chat: it makes many pictures.");if(!await n.assistantBrain())throw new ie("The assistant has nothing to think with. Install the local text model (`hatchlight catalog`), or set a key for OpenAI, Google or OpenRouter with `hatchlight keys set`.");let o=e.session==null?void 0:Gn(e.session,Kr,"a session id"),i=new Set;if(o)for(let l of(await n.conversation(o)).entries)i.add(l.id);let a=async(l)=>({sessionId:o}=await n.tellAssistant(l,o),MX(o,i,e,r)),c=t.join(" ").trim();if(c||!s.interactive){let l=c||(await s.readAll()).trim();if(!l)throw new ie("Say what you would like.");let u=await a(l);if(o&&!e.json)s.err(`Go on with: hatchlight chat --session ${o}`);return u}s.err("Ask for pictures; Ctrl+C stops the assistant, Ctrl+D leaves.");for(;;){let l=await s.readLine("> ");if(l==null)break;if(!l.trim())continue;await a(l.trim())}if(o)s.err(`Go on later with: hatchlight chat --session ${o}`);return G.ok}}}});function UX(e){let t=(r)=>Object.entries(r).filter(([n])=>n!=="wait"&&n!=="resources").map(([n,s])=>({name:n,short:s.short,value:s.type==="string",many:s.multiple===!0}));return[...Object.entries(e).map(([r,n])=>({name:r,summary:n.summary,options:t({...zx,...n.options})})),...Object.entries(jX).map(([r,n])=>({name:r,summary:n,options:[]}))]}function qX(e){let t=e.map((r)=>{let n=r.options.flatMap((s)=>[`--${s.name}`,...s.short?[`-${s.short}`]:[]]);return` ${r.name}) opts=${_o(n.join(" "))} ;;`}).join(`
|
|
220
|
+
`);return`# hatchlight completions for bash. Add to ~/.bashrc:
|
|
221
|
+
# eval "$(hatchlight completions bash)"
|
|
222
|
+
_hatchlight() {
|
|
223
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}" opts=""
|
|
224
|
+
if [ "$COMP_CWORD" -eq 1 ]; then
|
|
225
|
+
COMPREPLY=($(compgen -W ${_o(e.map((r)=>r.name).join(" "))} -- "$cur"))
|
|
226
|
+
return
|
|
227
|
+
fi
|
|
228
|
+
case "\${COMP_WORDS[1]}" in
|
|
229
|
+
${t}
|
|
230
|
+
esac
|
|
231
|
+
if [[ "$cur" == -* ]]; then
|
|
232
|
+
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
|
|
233
|
+
fi
|
|
234
|
+
}
|
|
235
|
+
complete -o default -F _hatchlight hatchlight
|
|
236
|
+
`}function FX(e){let t=e.map((n)=>` ${_o(`${n.name}:${n.summary}`)}`).join(`
|
|
237
|
+
`),r=e.map((n)=>{let s=n.options.flatMap((o)=>{let i=o.many?"*":"",a=!o.value?"":BX.has(o.name)?`:${o.name}:_files`:`:${o.name}:`;return[_o(`${i}--${o.name}[]${a}`),...o.short?[_o(`${i}-${o.short}[]${a}`)]:[]]});return` ${n.name}) _arguments ${[...s,_o("*:file:_files")].join(" ")} ;;`}).join(`
|
|
238
|
+
`);return`#compdef hatchlight
|
|
239
|
+
# hatchlight completions for zsh. Add to ~/.zshrc, after compinit:
|
|
240
|
+
# source <(hatchlight completions zsh)
|
|
241
|
+
_hatchlight() {
|
|
242
|
+
local -a commands
|
|
243
|
+
commands=(
|
|
244
|
+
${t}
|
|
245
|
+
)
|
|
246
|
+
if (( CURRENT == 2 )); then
|
|
247
|
+
_describe 'command' commands
|
|
248
|
+
return
|
|
249
|
+
fi
|
|
250
|
+
shift words
|
|
251
|
+
(( CURRENT-- ))
|
|
252
|
+
case $words[1] in
|
|
253
|
+
${r}
|
|
254
|
+
esac
|
|
255
|
+
}
|
|
256
|
+
compdef _hatchlight hatchlight
|
|
257
|
+
`}function VX(e){let t=["# hatchlight completions for fish. Save them with:","# hatchlight completions fish > ~/.config/fish/completions/hatchlight.fish"];for(let r of e){t.push(`complete -c hatchlight -n __fish_use_subcommand -f -a ${r.name} -d ${_o(r.summary)}`);for(let n of r.options)t.push(`complete -c hatchlight -n ${_o(`__fish_seen_subcommand_from ${r.name}`)} -l ${n.name}${n.short?` -s ${n.short}`:""}${n.value?" -r":""}`)}return`${t.join(`
|
|
258
|
+
`)}
|
|
259
|
+
`}function KL(e){return{summary:"Print shell completions (bash, zsh or fish)",usage:`Usage: hatchlight completions <bash|zsh|fish>
|
|
260
|
+
|
|
261
|
+
Prints a script that completes hatchlight's commands and options as you
|
|
262
|
+
type. To have it in every terminal:
|
|
263
|
+
|
|
264
|
+
bash add to ~/.bashrc: eval "$(hatchlight completions bash)"
|
|
265
|
+
zsh add to ~/.zshrc: source <(hatchlight completions zsh)
|
|
266
|
+
fish hatchlight completions fish > ~/.config/fish/completions/hatchlight.fish
|
|
267
|
+
|
|
268
|
+
-h, --help Show this help`,options:{},offline:!0,async run(t,[r,...n],{io:s}){let o=ZX[r];if(!o||n.length>0)throw new ie("Name a shell: bash, zsh or fish.");return s.out(o(UX(e())).trimEnd()),G.ok}}}var jX,BX,_o=(e)=>`'${e.replaceAll("'","'\\''")}'`,ZX;var WL=b(()=>{ii();jX={serve:"Start the app",mcp:"Connect an AI agent"};BX=new Set(["output","data-dir","batch","samples","ref"]);ZX={bash:qX,zsh:FX,fish:VX}});import{readFile as HX}from"fs/promises";import{basename as GX,resolve as KX}from"path";function QL(e){if(e.kind==="allowed")return"any use";if(e.kind==="limited")return`paid work below $${e.revenueUsd.toLocaleString("en-US")} a year`;return"personal use only"}function QX(e){if(e.state==="installed")return e.ready?"installed":"installed, engine missing";if(e.state==="downloading"&&e.size>0)return`downloading ${Math.floor(e.receivedBytes/e.size*100)}%`;if(e.error)return"failed";return e.state}async function YL(e,t){let r=await e.localModels(),n=JX(t),s=r.models.find((o)=>o.id===n);if(!s)throw new ie(`No model ${t} in the catalog. See \`hatchlight catalog\`.`);return s}async function XX(e,{api:t,io:r,startedServer:n,pollMs:s=500}){let o=new AbortController,i="";(async()=>{try{for await(let a of t.events(o.signal)){if(a.type!=="model.progress"||a.id!==e.id)continue;let c=a.bytesPerSecond>0?` \xB7 ${xt(a.bytesPerSecond)}/s`:"";i=a.state==="downloading"?`${xt(a.receivedBytes)} of ${xt(a.size)}${c}`:a.state}}catch{}})();try{for(;;){if(r.status(`${e.name}: ${i||"starting"}`),await oi(Math.max(s,1000),r.signal),r.signal.aborted){if(r.status(null),n)await t.cancelInstall(e.id).catch(()=>{}),r.err(`Stopped. What was downloaded is kept: \`hatchlight install ${e.id}\` goes on from there.`);else r.err(`Stopped waiting; the download goes on in Hatchlight. Stop it with: hatchlight install --cancel ${e.id}`);return G.interrupted}let a=(await t.localModels()).models.find((c)=>c.id===e.id);if(!a)throw Error(`${e.id} left the catalog`);if(a.state==="installed")return r.status(null),G.ok;if(a.state==="available")return r.status(null),r.err(`${e.name} was not installed: ${a.error??"stopped"}`),G.failed}}finally{o.abort()}}async function YX(e,t){let n=(e.interactive?await e.readSecret(`Key for ${t} (not shown): `):await e.readAll())?.trim();if(!n)throw new ie("No key was given.");return n}var JL,WX,JX=(e)=>e.replace(/^local\//,""),XL=(e)=>e.variants.find((t)=>t.id===e.variant),e6;var t6=b(()=>{ii();JL={gpu:"fits the GPU",offload:"slower: part in system memory",cpu:"very slow: on the CPU",none:"does not run here"},WX={gpu:"It fits the GPU.",offload:"It runs slower, with part of it in system memory.",cpu:"It runs on the CPU, very slowly.",none:"It does not run here."};e6={keys:{summary:"Show, set or remove API keys for cloud models",usage:`Usage: hatchlight keys
|
|
269
|
+
hatchlight keys set <provider>
|
|
270
|
+
hatchlight keys remove <provider>
|
|
271
|
+
|
|
272
|
+
Cloud models run on your own keys. \`set\` asks for the key without showing
|
|
273
|
+
it, or reads it from standard input: echo "$FAL_KEY" | hatchlight keys set fal
|
|
274
|
+
A key in the environment (FAL_KEY, OPENAI_API_KEY, ...) also works.
|
|
275
|
+
|
|
276
|
+
${vt}`,options:{},async run(e,[t,r,...n],{api:s,io:o}){let i=await s.providers();if(t==null){let c=i.filter((l)=>l.requiresKey);if(e.json)return _t(o,c),G.ok;for(let l of Ss(c.map((u)=>[u.id,u.name,u.hasKey?"set":"not set"])))o.out(l);return G.ok}if(t!=="set"&&t!=="remove"||n.length>0)throw new ie("Use `keys`, `keys set <provider>` or `keys remove <provider>`.");let a=i.find((c)=>c.id===r);if(!a?.requiresKey){let c=i.filter((l)=>l.requiresKey).map((l)=>l.id).join(", ");throw new ie(`${r?`No cloud provider ${r}`:"Name a provider"}. They are: ${c}.`)}if(t==="set")await s.setKey(a.id,await YX(o,a.name)),o.err(`The key for ${a.name} is set.`);else await s.removeKey(a.id),o.err(`The key for ${a.name} is removed.`);if(e.json)_t(o,{provider:a.id,action:t});return G.ok}},catalog:{summary:"List the models that can be installed on this computer",usage:`Usage: hatchlight catalog [words] [options]
|
|
277
|
+
|
|
278
|
+
Lists the models Hatchlight can download and run on this computer, with
|
|
279
|
+
what each takes on disk, how it fits this machine and what its license
|
|
280
|
+
allows. Words narrow the list.
|
|
281
|
+
|
|
282
|
+
--all Also models that do not run on this machine
|
|
283
|
+
${vt}`,options:{all:{type:"boolean",default:!1}},async run(e,t,{api:r,io:n}){let s=await r.localModels(),o=t.map((a)=>a.toLowerCase()),i=s.models.filter((a)=>a.media!=="text"&&(e.all||a.variant!=null)&&o.every((c)=>`${a.id} ${a.name} ${a.summary}`.toLowerCase().includes(c)));if(e.json)return _t(n,i),G.ok;if(i.length===0)return n.err("No model matches."),G.ok;for(let a of Ss(i.map((c)=>{let l=XL(c);return[c.id,c.name,c.media,QX(c),l?`${xt(c.size)} ${l.label}`:"",l?JL[l.fit]:JL.none,QL(c.commercial)]})))n.out(a);return n.err(`Models are kept in ${s.disk.path} (${xt(s.disk.freeBytes)} free). Install one with: hatchlight install <id>`),G.ok}},install:{summary:"Download a model to run on this computer",usage:`Usage: hatchlight install <model> [options]
|
|
284
|
+
hatchlight install --cancel <model>
|
|
285
|
+
|
|
286
|
+
Downloads a model from \`hatchlight catalog\`, with the engine that runs
|
|
287
|
+
it, and waits until it is ready. The variant that fits this machine best
|
|
288
|
+
is chosen unless --variant names another.
|
|
289
|
+
|
|
290
|
+
--variant <id> A variant from \`hatchlight catalog <model> --json\`
|
|
291
|
+
--cancel Stop an install that is going on
|
|
292
|
+
${vt}`,options:{variant:{type:"string"},cancel:{type:"boolean",default:!1}},interruptible:"once",async run(e,t,r){let{api:n,io:s}=r,[o,...i]=t;if(!o||i.length>0)throw new ie("Name one model, such as sdxl-turbo.");let a=await YL(n,o);if(e.cancel)return await n.cancelInstall(a.id),s.err(`Stopped installing ${a.name}.`),G.ok;let c=e.variant;if(a.state==="installed"&&a.ready){if(c&&c!==a.variant)throw new ie(`${a.name} is installed as ${a.variant}. To change it, uninstall it first.`);return s.err(`${a.name} is already installed.`),G.ok}let l=c?a.variants.find((p)=>p.id===c):XL(a);if(!l)throw new ie(c?`${a.name} has no variant ${c}; it has ${a.variants.map((p)=>p.id).join(", ")}.`:`${a.name} does not run on this machine.`);if(l.fit==="none")throw new ie(`${a.name} (${l.label}) does not fit this machine's memory.`);let u=c?l.files.filter((p)=>!p.present).reduce((p,f)=>p+f.size,0):a.size-a.receivedBytes;if(s.err(`Installing ${a.name}, ${l.label}: about ${xt(u)} to download. ${WX[l.fit]} License ${a.license}: ${QL(a.commercial)}.`),r.startedServer)s.err("Hatchlight was started for this command: Ctrl+C stops the download, and installing again goes on from where it stopped.");await n.install(a.id,c);let d=await XX(a,r);if(d===G.ok){if(e.json)_t(s,{id:a.id,variant:l.id});s.err(`${a.name} is installed. Use it with: -m local/${a.id}`)}return d}},uninstall:{summary:"Delete a model from this computer",usage:`Usage: hatchlight uninstall <model>
|
|
293
|
+
|
|
294
|
+
Deletes an installed model's files. Files other installed models use stay.
|
|
295
|
+
|
|
296
|
+
${vt}`,options:{},async run(e,[t,...r],{api:n,io:s}){if(!t||r.length>0)throw new ie("Name one installed model.");let o=await YL(n,t);if(o.state!=="installed")throw new ie(`${o.name} is not installed.`);if(await n.uninstall(o.id),e.json)_t(s,{id:o.id,freedBytes:o.reclaimableBytes});return s.err(`Deleted ${o.name}; ${xt(o.reclaimableBytes)} freed.`),G.ok}},loras:{summary:"List, add or remove LoRAs",usage:`Usage: hatchlight loras
|
|
297
|
+
hatchlight loras add <file.safetensors>
|
|
298
|
+
hatchlight loras remove <id>
|
|
299
|
+
|
|
300
|
+
A LoRA teaches a model a style, a person or a thing. Use one by putting
|
|
301
|
+
<lora:id:1> in a prompt, with its trigger word if it has one, on a model of
|
|
302
|
+
its family (sd1, sdxl, flux, ...). Train your own with \`hatchlight train\`.
|
|
303
|
+
|
|
304
|
+
${vt}`,options:{},async run(e,[t,r,...n],{api:s,io:o}){if(t==null){let i=await s.loras();if(e.json)return _t(o,i),G.ok;if(i.length===0)return o.err("No LoRA yet. Add one with: hatchlight loras add <file>"),G.ok;for(let a of Ss(i.map((c)=>[c.id,c.name,c.base,c.trigger?`trigger: ${c.trigger}`:"",xt(c.size)])))o.out(a);return G.ok}if(!r||n.length>0)throw new ie(t==="add"?"Give one .safetensors file.":"Give the id of one LoRA.");if(t==="add"){let i=KX(o.cwd,r),a=await HX(i).catch(()=>{throw new ie(`Cannot read ${r}.`)}),c=await s.addLora(GX(i),new Uint8Array(a));if(e.json)_t(o,c);return o.err(`Added ${c.name} (${c.base}). Use it with <lora:${c.id}:1> in a prompt${c.trigger?`, and the word ${c.trigger}`:""}.`),G.ok}if(t==="remove"){if(await s.removeLora(r),e.json)_t(o,{id:r,removed:!0});return o.err(`Removed ${r}.`),G.ok}throw new ie("Use `loras`, `loras add <file>` or `loras remove <id>`.")}},doctor:{summary:"Check this computer, the models and what is set up",usage:`Usage: hatchlight doctor
|
|
305
|
+
|
|
306
|
+
Says what Hatchlight sees: the graphics card, memory and disk, the engines
|
|
307
|
+
and models installed, the keys set, and whether the assistant, the picture
|
|
308
|
+
describer and the LoRA trainer are ready, with what to do when something is
|
|
309
|
+
missing.
|
|
310
|
+
|
|
311
|
+
${vt}`,options:{},async run(e,t,{api:r,io:n,url:s,dataDir:o,startedServer:i}){let[a,c,l,u,d]=await Promise.all([r.localModels(),r.providers(),r.trainer().catch(()=>null),r.captionerReady().catch(()=>!1),r.assistantBrain().catch(()=>null)]),{hardware:p,disk:f}=a,m=a.models.filter((k)=>k.state==="installed"),h=c.filter((k)=>k.requiresKey),g=[];if(p.gpus.length===0)g.push("No graphics card was found: local models run on the CPU, very slowly.");if(f.freeBytes<10000000000)g.push(`Only ${xt(f.freeBytes)} free where models are kept; models take 2 to 30 GB each.`);if(m.length===0&&!h.some((k)=>k.hasKey))g.push("Nothing can make pictures yet: `hatchlight catalog` lists models to install, or set a key with `hatchlight keys set`.");let w=d==="local"&&a.engines.some((k)=>k.installed&&k.throughWindows&&/llama/i.test(k.name));if(w)g.push("The assistant's model on this computer runs only in the Windows app, not under WSL: `hatchlight chat` here needs a key for OpenAI, Google or OpenRouter.");let v=m.filter((k)=>!k.ready);if(v.length>0)g.push(`Installed without their engine: ${v.map((k)=>k.id).join(", ")}. Install them again.`);if(e.json)return _t(n,{url:i?null:s,dataDir:o,hardware:p,disk:f,engines:a.engines,installed:m.map((k)=>k.id),keys:Object.fromEntries(h.map((k)=>[k.id,k.hasKey])),assistant:d,captions:u,trainer:l?.state??null,problems:g}),G.ok;let _={linux:"Linux",darwin:"macOS",win32:"Windows",other:"Another system"}[p.os],C=[["Hatchlight",i?"not running; started for this check":`running at ${s}`],["Data",o],["System",`${_} ${p.arch}${p.wsl?" (WSL)":""}, ${xt(p.memoryBytes)} memory`],...p.gpus.map((k)=>["GPU",`${k.name}, ${k.freeBytes!=null?`${xt(k.freeBytes)} free of ${xt(k.memoryBytes)}`:xt(k.memoryBytes)}${k.driver?`, driver ${k.driver}`:""}`]),["Models",`${f.path}: ${xt(f.usedBytes)} used, ${xt(f.freeBytes)} free`],...a.engines.filter((k)=>k.installed).map((k)=>["Engine",`${k.name} ${k.version} (${k.backend}${k.throughWindows?", through Windows":""})`]),["Installed",m.length>0?m.map((k)=>k.id).join(", "):"nothing yet"],["Keys",h.map((k)=>`${k.id} ${k.hasKey?"set":"-"}`).join(", ")],["Assistant",w?"only in the Windows app (see below)":d?`thinks with ${d}`:"nothing to think with: install a local text model or set a key"],["Captions",u?"ready":"not installed (a picture-reading model, for training)"],["Trainer",l==null?"not here":l.state==="ready"?"ready":l.state==="installing"?"installing":`not installed: hatchlight trainer install (${xt(l.downloadBytes)})`]];for(let k of Ss(C))n.out(k);for(let k of g)n.err(`! ${k}`);return G.ok}}}});import{mkdir as eY,readdir as tY,readFile as s6,stat as rY,writeFile as nY}from"fs/promises";import{basename as sY,extname as oY,join as Ux,resolve as Bx}from"path";function o6(e){if(e.stage!=="training")return aY[e.stage];let t=e.secondsLeft!=null?` \xB7 ${Mx(e.secondsLeft)} left`:"";return`step ${e.step} of ${e.steps}${t}`}function jx(e){if(e.state==="missing")return`not installed (about ${xt(e.downloadBytes)}): hatchlight trainer install`;if(e.state==="installing"){let t=e.install,r=t?.receivedBytes!=null&&t.totalBytes?` \xB7 ${xt(t.receivedBytes)} of ${xt(t.totalBytes)}`:"";return`installing: ${t?iY[t.step]:"starting"}${r}`}return"ready"}async function cY(e,t){let r=[];for(let n of t){if(In.test(n)){r.push(n);continue}let s=Bx(e.cwd,n),o=await rY(s).catch(()=>null);if(!o)throw new ie(`Cannot read ${n}.`);if(o.isDirectory()){let i=(await tY(s)).filter((a)=>r6.test(a)).sort();r.push(...i.map((a)=>Ux(s,a)))}else if(r6.test(s))r.push(s);else throw new ie(`${n} is not a PNG, JPEG or WebP picture.`)}return r}async function lY(e){return(await s6(Ux(Bx(e,".."),`${sY(e,oY(e))}.txt`),"utf8").catch(()=>null))?.trim()||void 0}async function uY(e,t,{api:r,io:n,startedServer:s,pollMs:o=500}){let i=new Set;if(t)await eY(t,{recursive:!0});let a=Date.now();for(;;){let c=(await r.trainer()).training;if(!c||c.id!==e)throw Error("The training is gone");for(let l of t?c.samples:[]){if(i.has(l))continue;i.add(l);let u=Ux(t,`step-${String(l).padStart(5,"0")}.png`);try{await nY(u,await r.trainingSample(e,l)),n.err(`Sample at step ${l}: ${u}`)}catch(d){n.err(`! No sample at step ${l}: ${d.message}`)}}if(c.state!=="running")return n.status(null),c;if(n.status(`${c.name}: ${o6(c)} \xB7 ${Mx((Date.now()-a)/1000)}`),await oi(Math.max(o,1000),n.signal),n.signal.aborted)return n.status(null),n.err(s?"Stopped. The training stops too, with the Hatchlight started for this command.":"Stopped waiting; it goes on in Hatchlight. `hatchlight trainer finish` keeps what it learned so far, `hatchlight trainer stop` drops it."),"interrupted"}}var r6,n6=800,iY,aY,i6;var a6=b(()=>{Pt();Fo();ii();r6=/\.(png|jpe?g|webp)$/i,iY={uv:"getting the Python installer",scripts:"getting the training scripts",python:"getting Python",packages:"getting the packages",checking:"checking it works"},aY={waitingGpu:"waiting for the graphics card",loading:"loading Stable Diffusion XL",caching:"preparing the pictures",training:"training",saving:"saving the LoRA"};i6={trainer:{summary:"Install the LoRA trainer, or stop a training",usage:`Usage: hatchlight trainer How the trainer stands
|
|
312
|
+
hatchlight trainer install Download it (Python and its packages)
|
|
313
|
+
hatchlight trainer remove Delete it
|
|
314
|
+
hatchlight trainer stop Stop a training and drop it
|
|
315
|
+
hatchlight trainer finish Stop a training and keep the LoRA
|
|
316
|
+
saved at its latest step
|
|
317
|
+
|
|
318
|
+
${vt}`,options:{},interruptible:"once",async run(e,[t,...r],{api:n,io:s,startedServer:o,pollMs:i=500}){if(r.length>0)throw new ie("One action at a time.");if(t==null){let c=await n.trainer();if(e.json)return _t(s,c),G.ok;if(s.out(`Trainer: ${jx(c)}`),c.error)s.out(`Last install failed: ${c.error.message}`);let l=c.training;if(l){let u=l.state==="running"?o6(l):l.state;if(s.out(`Training ${l.name} (${l.trigger}): ${u}`),l.loraId)s.out(`LoRA: ${l.loraId}`)}return G.ok}if(t==="remove")return await n.removeTrainer(),s.err("The trainer is deleted."),G.ok;if(t==="stop")return await n.stopTraining(),s.err("The training is stopped."),G.ok;if(t==="finish")return await n.finishTraining(),s.err("The training stops at its latest saved step, and the LoRA is kept."),G.ok;if(t!=="install")throw new ie("Use install, remove, stop or finish.");let a=await n.trainer();if(a.state==="ready")return s.err("The trainer is already installed."),G.ok;if(a.state==="missing")s.err(`Installing the trainer: about ${xt(a.downloadBytes)}.`),await n.installTrainer();for(;;){let c=await n.trainer();if(c.state==="ready")return s.status(null),s.err("The trainer is ready. Train a LoRA with: hatchlight train"),G.ok;if(c.state==="missing")return s.status(null),s.err(`The trainer was not installed: ${c.error?.message??"stopped"}`),G.failed;if(s.status(`Trainer: ${jx(c)}`),await oi(Math.max(i,1000),s.signal),s.signal.aborted){if(s.status(null),a.state==="missing"||o)await n.cancelTrainerInstall().catch(()=>{}),s.err("Stopped installing the trainer.");else s.err("Stopped waiting; the install goes on in Hatchlight.");return G.interrupted}}}},train:{summary:"Teach a model a person, a thing or a style (a LoRA)",usage:`Usage: hatchlight train <pictures>... --name <name> --trigger <word> --consent
|
|
319
|
+
|
|
320
|
+
Trains a LoRA for Stable Diffusion XL from ${jo} to ${Uo} pictures: files, folders of
|
|
321
|
+
them, or picture ids (ast_\u2026). A picture's words come from a .txt file of the
|
|
322
|
+
same name beside it ("dog1.png" and "dog1.txt"), or from --describe.
|
|
323
|
+
|
|
324
|
+
--name <name> What to call the LoRA
|
|
325
|
+
--trigger <word> A word that calls it up in prompts, such as "qzxdog"
|
|
326
|
+
--steps <n> How long to train, ${qi} to ${Fi} (default ${n6})
|
|
327
|
+
--describe Describe pictures without words with the model that
|
|
328
|
+
looks at pictures (install it in the app)
|
|
329
|
+
--samples <dir> Save the pictures it makes along the way, to see it learn
|
|
330
|
+
--consent The pictures are yours to use, and anyone in them agreed
|
|
331
|
+
${vt}`,options:{name:{type:"string"},trigger:{type:"string"},steps:{type:"string"},describe:{type:"boolean",default:!1},samples:{type:"string"},consent:{type:"boolean",default:!1}},interruptible:"once",async run(e,t,r){let{api:n,io:s}=r,o=e.name?.trim(),i=e.trigger?.trim();if(!o)throw new ie("Give the LoRA a --name.");if(!i)throw new ie("Give a --trigger word.");let a=si(e,"steps",qi,Fi)??n6;if(e.consent!==!0)throw new ie("Training needs --consent: say the pictures are yours to use, and that anyone in them agreed.");let c=await cY(s,t);if(c.length<jo||c.length>Uo)throw new ie(`Training needs ${jo} to ${Uo} pictures; ${c.length} were given.`);let l=await n.trainer();if(l.state!=="ready")throw new ie(`The trainer is ${jx(l)}`);if(l.training?.state==="running")throw new ie(`${l.training.name} is training now. Wait for it, or stop it with \`hatchlight trainer stop\`.`);let u=e.describe===!0;if(u&&!await n.captionerReady())throw new ie("--describe needs the model that looks at pictures (Qwen2.5-VL); install it in the app.");let d=[];for(let[g,w]of c.entries()){if(s.status(`Reading pictures: ${g+1} of ${c.length}`),In.test(w)){d.push({assetId:w});continue}let v=await n.upload(new Uint8Array(await s6(w)));d.push({assetId:v.id,caption:await lY(w)})}if(u){let g=d.filter((w)=>!w.caption);for(let[w,v]of g.entries())s.status(`Describing pictures: ${w+1} of ${g.length}`),v.caption=await n.caption(v.assetId)}s.status(null);let p=d.filter((g)=>g.caption).length;if(s.err(`Training ${o} on ${d.length} pictures (${p} with words), ${a} steps.`),r.startedServer)s.err("Hatchlight was started for this command: keep this terminal open until the training ends.");let f=await n.train({name:o,trigger:i,steps:a,pictures:d,consent:!0}),m=typeof e.samples==="string"?Bx(s.cwd,e.samples):null,h=await uY(f.id,m,r);if(h==="interrupted")return G.interrupted;if(e.json)_t(s,h);if(h.state==="done"&&h.loraId)return s.err(`The LoRA is ready${h.keptStep!=null?` (kept at step ${h.keptStep})`:""}. Use it on an SDXL model with: <lora:${h.loraId}:1> ${h.trigger}`),G.ok;return s.err(h.state==="canceled"?"The training was stopped.":`The training failed: ${h.error?.message??"no reason given"}`),G.failed}}}});function c6(){let e=Math.max(...Object.keys(ai).map((t)=>t.length));return Object.entries(ai).map(([t,r])=>` ${t.padEnd(e)} ${r.summary}`).join(`
|
|
332
|
+
`)}var ai;var qx=b(()=>{GL();WL();t6();Mm();a6();ii();Mm();ai={...VL,...HL,...e6,...i6,completions:KL(()=>ai)}});function Nm(){return/\$bunfs|~BUN/.test(Bun.main)?[process.execPath]:[process.execPath,Bun.main]}function Lm(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"explorer":"xdg-open";try{Bun.spawn([t,e],{stdio:["ignore","ignore","ignore"]})}catch{}}function Dm(e){return[...e["data-dir"]?["--data-dir",e["data-dir"]]:[],...e.resources?["--resources",e.resources]:[]]}import{existsSync as l6}from"fs";import{join as Fx}from"path";function jm(e){if(e)return Jc(e);let t=Fx(import.meta.dir,"..","resources");return l6(Fx(t,"drizzle"))&&l6(Fx(t,"web","index.html"))?t:void 0}var Vx=b(()=>{Pt()});import{parseArgs as dY}from"util";async function u6(e){let{values:t}=dY({args:e,options:{"data-dir":{type:"string"},url:{type:"string"},token:{type:"string"},insecure:{type:"boolean",default:!1},"allow-paid":{type:"boolean",default:!1},"spend-limit":{type:"string"},resources:{type:"string"},help:{type:"boolean",short:"h",default:!1}}});if(t.help){console.log(pY);return}let r=t["spend-limit"]==null?null:Number(t["spend-limit"]);if(r!=null&&!(Number.isFinite(r)&&r>=0))console.error(`Invalid spending limit: ${t["spend-limit"]}`),process.exit(1);if(r!=null&&!t["allow-paid"])console.error("--spend-limit only applies with --allow-paid"),process.exit(1);let n=t.url??process.env.HATCHLIGHT_URL,s=t.token??process.env.HATCHLIGHT_TOKEN;if(n||s){if(!n||!s)console.error("A server elsewhere needs both its address and a token: --url and --token, or HATCHLIGHT_URL and HATCHLIGHT_TOKEN"),process.exit(1);try{await tN({url:n,token:s,insecure:t.insecure,allowPaid:t["allow-paid"],spendLimitUsd:r})}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}return}await eN({dataDir:t["data-dir"]??Qt(),launcher:Nm(),serverArgs:Dm(t),allowPaid:t["allow-paid"],spendLimitUsd:r})}var pY;var d6=b(()=>{Pt();Wl();pY=`hatchlight mcp \u2014 lets an AI agent make pictures and videos with Hatchlight
|
|
333
|
+
|
|
334
|
+
It speaks the Model Context Protocol on standard input and output. Add it to
|
|
335
|
+
an agent, e.g. Claude Code: claude mcp add hatchlight -- hatchlight mcp
|
|
336
|
+
|
|
337
|
+
It uses the Hatchlight already running on the data directory, or starts one
|
|
338
|
+
that stops with it. Agents cannot install models; the user does, in the app.
|
|
339
|
+
|
|
340
|
+
With --url, it uses a Hatchlight server elsewhere instead, as the person an
|
|
341
|
+
API token belongs to (Settings > Use with AI agents). The token's own scopes
|
|
342
|
+
and spending limit apply; --allow-paid and --spend-limit add to them here.
|
|
343
|
+
|
|
344
|
+
Options:
|
|
345
|
+
--data-dir <p> The data directory (default ${Qt()})
|
|
346
|
+
--url <origin> A Hatchlight server's address (or HATCHLIGHT_URL)
|
|
347
|
+
--token <t> Its API token (or HATCHLIGHT_TOKEN, which other
|
|
348
|
+
programs on this computer cannot read in a process list)
|
|
349
|
+
--insecure Allow plain http to a server not on this computer
|
|
350
|
+
--allow-paid Also use paid cloud models, on the user's own keys
|
|
351
|
+
--spend-limit <usd> With --allow-paid: the most this connection may spend
|
|
352
|
+
--resources <p> For a packaged app: where its UI and migrations are
|
|
353
|
+
-h, --help Show this help
|
|
354
|
+
`});import{join as fY}from"path";import{parseArgs as mY}from"util";async function p6(e){let{values:t,positionals:r}=mY({args:e,allowPositionals:!0,options:{"data-dir":{type:"string"},resources:{type:"string"},help:{type:"boolean",short:"h",default:!1}}}),[n,s]=r;if(t.help||!n)return console.log(hY),t.help?0:1;let o=t["data-dir"]??Qt(),i=jm(t.resources),a=i?fY(i,"drizzle"):void 0,c=new Bc(La(o),a);try{let l=new $c(c.accounts());if(n==="list"){let u=l.users();if(u.length===0)return console.log("No accounts yet: the server is waiting to be set up."),0;for(let d of u){let p=[d.role,d.disabled?"disabled":null,d.totp?"two-step":null].filter(Boolean);console.log(`${d.username} ${p.join(", ")}`)}return 0}if(n==="reset-password"){if(!s)return console.error("Name the account: hatchlight users reset-password <username>"),1;let u=l.findUser(s);if(!u)return console.error(`No account named ${s}.`),1;let d=await l.resetPasswordFromConsole(u.id);return console.log(`One-time password for ${u.username}: ${d}`),console.log("It must be changed at the next sign-in."),console.log("Two-step sign-in is turned off; it can be set up again in Settings."),console.log("Every sign-in and API token of the account has ended."),0}return console.error(`Unknown command: ${n}. See hatchlight users --help.`),1}finally{c.close()}}var hY;var f6=b(()=>{Pt();Om();Vx();hY=`hatchlight users \u2014 the people of a Hatchlight server
|
|
355
|
+
|
|
356
|
+
Usage: hatchlight users list [options]
|
|
357
|
+
hatchlight users reset-password <username> [options]
|
|
358
|
+
|
|
359
|
+
reset-password prints a one-time password, which must be changed at the
|
|
360
|
+
next sign-in, turns two-step sign-in off, and ends every sign-in and API
|
|
361
|
+
token of the account. Use it when an owner is
|
|
362
|
+
locked out, for instance through docker exec. It works while the server runs.
|
|
363
|
+
|
|
364
|
+
Options:
|
|
365
|
+
--data-dir <p> The data directory (default ${Qt()})
|
|
366
|
+
--resources <p> For a packaged app: where its migrations are
|
|
367
|
+
-h, --help Show this help
|
|
368
|
+
`});import{Database as gY}from"bun:sqlite";import{existsSync as Zx}from"fs";import{mkdir as Hx,mkdtemp as yY,readdir as g6,rename as m6,rm as y6,writeFile as wY}from"fs/promises";import{dirname as h6,join as Ir,resolve as Um}from"path";import{parseArgs as w6}from"util";async function b6(e,t){let r=[];for(let n of await g6(e,{withFileTypes:!0}).catch(()=>[])){let s=Ir(e,n.name),o=`${t}/${n.name}`;if(n.isDirectory())r.push(...await b6(s,o));else if(n.isFile())r.push({name:o,source:s})}return r}async function v6(e){let{values:t,positionals:r}=w6({args:e,allowPositionals:!0,options:{"data-dir":{type:"string"},help:{type:"boolean",short:"h",default:!1}}}),[n]=r;if(t.help||!n)return console.log(vY),t.help?0:1;let s=Um(t["data-dir"]??Qt()),o=La(s);if(!Zx(o))return console.error(`No Hatchlight database in ${s}.`),1;let i=Um(Jc(n));await Hx(h6(i),{recursive:!0});let a=await yY(Ir(h6(i),".hatchlight-backup-"));try{let c=Ir(a,ci),l=new gY(o,{readonly:!0});try{l.run("VACUUM INTO ?",[c])}finally{l.close()}let u=Ir(a,ja);await wY(u,`${JSON.stringify({format:1,createdAt:new Date().toISOString()},null,2)}
|
|
369
|
+
`);let d=[{name:ja,source:u},{name:ci,source:c},...Gx.filter((p)=>Zx(Ir(s,p))).map((p)=>({name:p,source:Ir(s,p)})),...await b6(Ir(s,xo),xo)];if(await nI(i,d,{mode:384}),console.log(`Saved ${d.length-1} files to ${i}.`),lt(process.env,"SECRET_FILE"))console.log("The secret for API keys is in HATCHLIGHT_SECRET_FILE, outside the data directory: back it up too.");return 0}finally{await y6(a,{recursive:!0,force:!0})}}function xY(e){let t=new Set(e.map((s)=>s.name));if(!t.has(ja))return"it is not a Hatchlight backup";if(!t.has(ci))return"it holds no database";let r=new Set([ja,ci,xo,...Gx]),n=e.find((s)=>s.type==="link"||!(r.has(s.name)||s.name.startsWith(`${xo}/`)));return n?`it holds something unexpected: ${n.name}`:null}async function _6(e){let{values:t,positionals:r}=w6({args:e,allowPositionals:!0,options:{"data-dir":{type:"string"},"dry-run":{type:"boolean",default:!1},help:{type:"boolean",short:"h",default:!1}}}),[n]=r;if(t.help||!n)return console.log(_Y),t.help?0:1;let s=Um(t["data-dir"]??Qt()),o=Um(Jc(n)),i;try{i=await Y1(o)}catch(p){return console.error(`Cannot read ${o}: ${p instanceof Error?p.message:p}.`),1}let a=xY(i);if(a)return console.error(`Cannot restore ${o}: ${a}.`),1;let c=i.filter((p)=>p.name.startsWith(`${xo}/`)),l=bY.filter((p)=>Zx(Ir(s,p)));if(t["dry-run"]){console.log(`${o} holds:`);for(let f of i){if(f.name===ja||f.name.startsWith(`${xo}/`))continue;console.log(` ${f.name} ${Do(f.size)}`)}let p=c.reduce((f,m)=>f+m.size,0);return console.log(` ${xo}/ ${c.length} files, ${Do(p)}`),console.log(l.length>0?`Restoring would move aside, in ${s}: ${l.join(", ")}.`:`Restoring would fill ${s}, which holds no data yet.`),console.log("Nothing was changed."),0}await Hx(s,{recursive:!0,mode:448});let u;try{u=Ox(s)}catch(p){if(!(p instanceof wn))throw p;return console.error(`${p.message}. Stop the server before restoring a backup.`),1}let d=Ir(s,`.restore-${crypto.randomUUID()}`);try{await ep(o,d);let p=Ir(s,`before-restore-${new Date().toISOString().replaceAll(":","-")}`);if(l.length>0)await Hx(p,{mode:448});for(let f of l)await m6(Ir(s,f),Ir(p,f));for(let f of await g6(d)){if(f===ja)continue;await m6(Ir(d,f),Ir(s,f))}if(console.log(`Restored ${i.length-1} files into ${s}.`),l.length>0)console.log(`What was there is in ${p}.`);return 0}finally{await y6(d,{recursive:!0,force:!0}),u()}}var ja="hatchlight-backup.json",ci="hatchlight.sqlite",Gx,xo="assets",bY,vY,_Y;var x6=b(()=>{Pt();Om();Gx=["settings.json","auth.json","secret.key","device.key"],bY=[ci,`${ci}-wal`,`${ci}-shm`,"open-reel.sqlite","open-reel.sqlite-wal","open-reel.sqlite-shm",xo,...Gx],vY=`hatchlight backup \u2014 save a server's data in one file
|
|
370
|
+
|
|
371
|
+
Usage: hatchlight backup <file.tar.gz> [options]
|
|
372
|
+
|
|
373
|
+
Saves a consistent copy of the database, the pictures and videos (assets),
|
|
374
|
+
settings.json, auth.json (saved API keys), and secret.key and device.key
|
|
375
|
+
when they are there. It works while the server runs. Models are not saved:
|
|
376
|
+
they download again. The file holds API keys and the secret that opens
|
|
377
|
+
them: keep it as safe as the server.
|
|
378
|
+
|
|
379
|
+
Options:
|
|
380
|
+
--data-dir <p> The data directory (default ${Qt()})
|
|
381
|
+
-h, --help Show this help
|
|
382
|
+
`,_Y=`hatchlight restore \u2014 put a backup back
|
|
383
|
+
|
|
384
|
+
Usage: hatchlight restore <file.tar.gz> [options]
|
|
385
|
+
|
|
386
|
+
Replaces the database, assets and settings of the data directory with the
|
|
387
|
+
backup's. What was there is moved to before-restore-<time>/ in the data
|
|
388
|
+
directory, not deleted. The server must be stopped first.
|
|
389
|
+
|
|
390
|
+
Options:
|
|
391
|
+
--data-dir <p> The data directory (default ${Qt()})
|
|
392
|
+
--dry-run Only say what the backup holds and what would change
|
|
393
|
+
-h, --help Show this help
|
|
394
|
+
`});var Kx;var S6=b(()=>{Wl();Kx=class Kx extends cs{send=(e,t,r)=>this.request(t,{method:e,...r!==void 0&&{headers:{"content-type":"application/json"},body:JSON.stringify(r)}});setKey=(e,t)=>this.send("PUT",`/api/providers/${encodeURIComponent(e)}/key`,{key:t});removeKey=(e)=>this.send("DELETE",`/api/providers/${encodeURIComponent(e)}/key`);localModels=()=>this.request("/api/local-models");install=(e,t)=>this.send("POST",`/api/local-models/${encodeURIComponent(e)}/install`,t?{variant:t}:{});cancelInstall=(e)=>this.send("POST",`/api/local-models/${encodeURIComponent(e)}/cancel`);uninstall=(e)=>this.send("DELETE",`/api/local-models/${encodeURIComponent(e)}`);loras=()=>this.request("/api/loras");addLora=(e,t)=>this.request(`/api/loras?${new URLSearchParams({name:e})}`,{method:"POST",body:t});removeLora=(e)=>this.send("DELETE",`/api/loras/${encodeURIComponent(e)}`);checkpoints=()=>this.request("/api/checkpoints");trainer=()=>this.request("/api/trainer");installTrainer=()=>this.send("POST","/api/trainer/install");cancelTrainerInstall=()=>this.send("POST","/api/trainer/install/cancel");removeTrainer=()=>this.send("DELETE","/api/trainer");train=(e)=>this.send("POST","/api/trainings",e);stopTraining=()=>this.send("POST","/api/trainings/cancel");finishTraining=()=>this.send("POST","/api/trainings/finish");async trainingSample(e,t){let r=await this.fetch(`${this.baseUrl}/api/trainings/${encodeURIComponent(e)}/samples/${t}`);if(!r.ok)throw Error(`No sample at step ${t}`);return new Uint8Array(await r.arrayBuffer())}captionerReady=async()=>(await this.request("/api/captioner")).ready;caption=async(e)=>(await this.send("POST","/api/captions",{assetId:e})).caption;assistantBrain=async()=>(await this.request("/api/assistant")).brain;tellAssistant=(e,t)=>this.send("POST","/api/assistant/messages",{text:e,...t&&{sessionId:t}});conversation=(e)=>this.request(`/api/sessions/${encodeURIComponent(e)}/assistant`);answerAssistant=(e,t,r)=>this.send("POST",`/api/sessions/${encodeURIComponent(e)}/assistant/answers`,{entryId:t,approve:r});stopAssistant=(e)=>this.send("POST",`/api/sessions/${encodeURIComponent(e)}/assistant/stop`)}});import{createInterface as SY}from"readline";import{Writable as $Y}from"stream";function $6(e,t){return new Promise((r)=>{if(!t)process.stderr.write(e);let n=SY({input:process.stdin,output:t?process.stderr:new $Y({write:(o,i,a)=>a()}),terminal:!0}),s=null;n.on("SIGINT",()=>n.close()),n.on("close",()=>{if(!t)process.stderr.write(`
|
|
395
|
+
`);r(s)}),n.question(t?e:"",(o)=>{s=o,n.close()})})}class k6{first=new AbortController;waiting=null;mode=null;next(){return this.waiting=new AbortController,this.waiting.signal}take(){if(this.mode==="once"&&!this.first.signal.aborted){this.first.abort();return}if(this.mode==="repeat"&&this.waiting&&!this.waiting.signal.aborted){this.waiting.abort();return}process.exit(G.interrupted)}}function kY(e){let t=process.stderr.isTTY===!0,r=!1,n=()=>{if(r)process.stderr.write("\r\x1B[2K");r=!1};return{out:(s)=>{n(),process.stdout.write(`${s}
|
|
396
|
+
`)},err:(s)=>{n(),process.stderr.write(`${s}
|
|
397
|
+
`)},status:(s)=>{if(!t)return;if(s==null)return n();let o=process.stderr.columns||80,i=s.length<o?s:`${s.slice(0,o-2)}\u2026`;process.stderr.write(`\r\x1B[2K${i}`),r=!0},cwd:process.cwd(),signal:e.first.signal,nextInterrupt:()=>e.next(),open:Lm,interactive:process.stdin.isTTY===!0,readLine:(s)=>(n(),$6(s,!0)),readSecret:(s)=>(n(),$6(s,!1)),readAll:()=>Bun.stdin.text()}}async function T6(e,t){let r=ai[e];if(!r)throw Error(`No command ${e}`);let n=new k6;process.on("SIGINT",()=>n.take());let s=kY(n);try{let{values:o,positionals:i}=Nx(r,t);if(o.help)return s.out(r.usage),G.ok;let a=o["data-dir"]??Qt(),c;if(r.offline)c={url:"",started:!1};else if(r.local){let l=await pl(a);if(!l)return s.err("Hatchlight is not running. Start it with `hatchlight`."),G.failed;c={url:l,started:!1}}else s.status("Connecting to Hatchlight\u2026"),c=await fl(a,Nm(),Dm(o)),s.status(null);return n.mode=r.interruptible,await r.run(o,i,{api:new Kx(c.url),io:s,url:c.url,dataDir:a,startedServer:c.started})}catch(o){if(s.status(null),o instanceof ie)return s.err(o.message),s.err(`See: hatchlight ${e} --help`),G.usage;if(o instanceof as)return s.err(o.message),G.failed;return s.err(`${o.message??o}`),G.failed}}var P6=b(()=>{Pt();Wl();S6();qx()});Pt();Wl();Om();qx();Vx();import{writeSync as TY}from"fs";import{join as Ua}from"path";import{parseArgs as PY}from"util";var[Ur,...lu]=process.argv.slice(2);if(Ur==="mcp"){await Promise.resolve().then(() => d6());await u6(lu),process.exit(0)}if(Ur==="users"){await Promise.resolve().then(() => f6());process.exit(await p6(lu))}if(Ur==="backup"||Ur==="restore"){await Promise.resolve().then(() => x6());process.exit(await(Ur==="backup"?v6:_6)(lu))}if(Ur!=null&&Object.hasOwn(ai,Ur)){await Promise.resolve().then(() => P6());process.exit(await T6(Ur,lu))}if(Ur!=null&&!Ur.startsWith("-")&&Ur!=="serve")console.error(`Unknown command: ${Ur}
|
|
398
|
+
See the commands with: hatchlight --help`),process.exit(2);var EY=`Hatchlight \u2014 one interface for many image generation models
|
|
399
|
+
|
|
400
|
+
Usage: hatchlight [serve] [options] Start the app
|
|
401
|
+
hatchlight <command> [options]
|
|
402
|
+
|
|
403
|
+
Commands (see hatchlight <command> --help):
|
|
404
|
+
${c6()}
|
|
405
|
+
mcp Connect an AI agent
|
|
406
|
+
users Manage a server's accounts, from its data directory
|
|
407
|
+
backup Save a server's data in one file
|
|
408
|
+
restore Put a backup back, with the server stopped
|
|
409
|
+
|
|
410
|
+
Options for serve:
|
|
411
|
+
--port <n> Port to listen on (default 4096; 0 picks a free one)
|
|
412
|
+
--mode <m> personal: one person on this computer (default)
|
|
413
|
+
server: several people over the network; needs
|
|
414
|
+
HATCHLIGHT_PUBLIC_URL, and reads HATCHLIGHT_ALLOWED_HOSTS,
|
|
415
|
+
HATCHLIGHT_TRUSTED_PROXIES, and the LoRAs each member
|
|
416
|
+
may add: HATCHLIGHT_LORA_FILES_PER_PERSON (default 20)
|
|
417
|
+
and HATCHLIGHT_LORA_GB_PER_PERSON (default 10), and the
|
|
418
|
+
room each member's pictures may take:
|
|
419
|
+
HATCHLIGHT_ASSET_GB_PER_PERSON (unset: no limit)
|
|
420
|
+
--host <a> Address to listen on (default 127.0.0.1, or 0.0.0.0 in
|
|
421
|
+
server mode)
|
|
422
|
+
--data-dir <p> Where sessions, images and keys are stored
|
|
423
|
+
(default ${Qt()}). API keys are encrypted
|
|
424
|
+
with HATCHLIGHT_SECRET_FILE, or secret.key made there
|
|
425
|
+
--dev Accept requests from the Vite dev server and skip the UI
|
|
426
|
+
--no-open Do not open the browser
|
|
427
|
+
--resources <p> Where a packaged app keeps the built UI (web/) and the
|
|
428
|
+
database migrations (drizzle/)
|
|
429
|
+
--parent-pid <n> Stop when the process with this id ends, such as the
|
|
430
|
+
desktop app that started this server, or when it closes
|
|
431
|
+
this server's standard input
|
|
432
|
+
-h, --help Show this help
|
|
433
|
+
`,{values:qt}=PY({args:Ur==="serve"?lu:process.argv.slice(2),options:{port:{type:"string",default:"4096"},mode:{type:"string"},host:{type:"string"},"data-dir":{type:"string"},dev:{type:"boolean",default:!1},"no-open":{type:"boolean",default:!1},resources:{type:"string"},"parent-pid":{type:"string"},help:{type:"boolean",short:"h",default:!1}}});if(qt.help)console.log(EY),process.exit(0);var au=Number(qt.port);if(!Number.isInteger(au)||au<0||au>65535)console.error(`Invalid port: ${qt.port}`),process.exit(1);var ui;try{ui=m4({mode:qt.mode,host:qt.host},process.env)}catch(e){if(!(e instanceof jr))throw e;console.error(`${e.message}.`),process.exit(1)}var li=ui.transport,cu=qt["parent-pid"]==null?null:Number(qt["parent-pid"]);if(cu!=null&&!(Number.isInteger(cu)&&cu>0))console.error(`Invalid parent process id: ${qt["parent-pid"]}`),process.exit(1);var Ba=jm(qt.resources),E6=Ba?Ua(Ba,"web"):Ua(import.meta.dir,"..","..","..","apps","web","dist"),IY=Ba?Ua(Ba,"drizzle"):void 0,$o=qt["data-dir"]??Qt(),A6=lt(process.env,"MODELS_DIR")??(qt["data-dir"]||li?Ua($o,"models"):null),Wx=A6?null:await N1($o),Jx=A6??await j1(Wx),qa=await CL({dataDir:$o,modelsDir:Jx,trainerDir:L1($o),modelsLocationFile:Wx?Ob(Wx):void 0,migrationsDir:IY,server:li!=null,assetQuotaBytes:ui.assetQuotaBytes}).catch((e)=>{if(!(e instanceof wn||e instanceof ts))throw e;console.error(`${e.message}.`),process.exit(1)}),AY=1048576,Xx=R4({...qa,allowedOrigins:qt.dev?["http://localhost:5173"]:[],server:li??void 0,mcp:li?P0({fetch:(e)=>Promise.resolve(Xx.fetch(e,{peer:"127.0.0.1"})),maxBodyBytes:AY}):void 0,loraQuota:ui.loraQuota??void 0,agents:new O0(()=>uN(!qt.resources&&Ba?{dataDir:qt["data-dir"],npmPackage:"hatchlight"}:{dataDir:qt["data-dir"],resources:Ba}))});if(!qt.dev){if(!await Bun.file(Ua(E6,"index.html")).exists())console.error("The web UI is not built. Run `bun run build` first."),qa.close(),process.exit(1);ML(Xx,E6)}function RY(){try{return Bun.serve({hostname:ui.host,port:au,idleTimeout:0,maxRequestBodySize:Hc,fetch:(e,t)=>Xx.fetch(e,{peer:t.requestIP(e)?.address})})}catch(e){if(e.code!=="EADDRINUSE")throw e;console.error(`Port ${au} is already in use. Choose another with --port.`),qa.close(),process.exit(1)}}var Bm=RY();await qa.start();var Yx=li?.publicOrigin??`http://localhost:${Bm.port}`;await xI($o,{pid:process.pid,url:w4(ui.host,Bm.port)}).catch((e)=>{console.error(`Agents will not find this server: ${e.message}`)});var So=(e)=>TY(1,`${e}
|
|
434
|
+
`);So(`Hatchlight is running at ${Yx}`);if(li){So(`Listening on ${ui.host}:${Bm.port}`);let e=qa.accounts.setupCode();if(e)So(""),So(` Set up this server: open ${Yx} and enter the code ${e}`),So(" The code changes each time the server starts, until it is set up."),So("")}So(`Data directory: ${$o}`);if(Jx!==Ua($o,"models"))So(`Local models: ${Jx}`);if(!qt.dev&&!qt["no-open"]&&!li)Lm(Yx);var I6=!1;async function Qx(){if(I6)return;I6=!0,Bm.stop(!0),await SI($o).catch(()=>{}),qa.close(),process.exit(0)}for(let e of["SIGINT","SIGTERM"])process.on(e,Qx);if(cu!=null)(async()=>{for await(let e of Bun.stdin.stream());Qx()})(),setInterval(()=>{try{process.kill(cu,0)}catch(e){if(e.code!=="EPERM")Qx()}},2000);
|