sqlite-zod-orm 3.8.0 → 3.9.0

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/src/types.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * at the type level — full autocomplete on schema fields AND relationship methods.
6
6
  */
7
7
  import { z } from 'zod';
8
- import type { QueryBuilder } from './query-builder';
8
+ import type { QueryBuilder } from './query';
9
9
 
10
10
  export type ZodType = z.ZodTypeAny;
11
11
  export type SchemaMap = Record<string, z.ZodType<any>>;
@@ -31,10 +31,17 @@ export type DatabaseOptions<R extends RelationsConfig = RelationsConfig> = {
31
31
  */
32
32
  relations?: R;
33
33
  /**
34
- * Global polling interval (ms) for `.on()` and `.subscribe()`.
35
- * Can be overridden per-call. Default: 500ms.
34
+ * Global polling interval (ms) for `.on()` change listeners.
35
+ * A single poller serves all listeners. Default: 100ms.
36
+ * Ignored if `reactive` is false.
36
37
  */
37
38
  pollInterval?: number;
39
+ /**
40
+ * Enable trigger-based change tracking for `.on()` listeners.
41
+ * Set to `false` to skip trigger/table creation entirely — calling
42
+ * `.on()` will throw. Default: `true`.
43
+ */
44
+ reactive?: boolean;
38
45
  };
39
46
 
40
47
  export type Relationship = {
@@ -144,11 +151,14 @@ export type NavEntityAccessor<
144
151
  Table extends string,
145
152
  > = {
146
153
  insert: (data: Omit<z.input<S[Table & keyof S]>, 'id'>) => NavEntity<S, R, Table>;
154
+ insertMany: (rows: Omit<z.input<S[Table & keyof S]>, 'id'>[]) => NavEntity<S, R, Table>[];
147
155
  update: ((id: number, data: Partial<Omit<z.input<S[Table & keyof S]>, 'id'>>) => NavEntity<S, R, Table> | null)
148
156
  & ((data: Partial<Omit<z.input<S[Table & keyof S]>, 'id'>>) => UpdateBuilder<NavEntity<S, R, Table>>);
149
157
  upsert: (conditions?: Partial<z.infer<S[Table & keyof S]>>, data?: Partial<z.infer<S[Table & keyof S]>>) => NavEntity<S, R, Table>;
150
158
  delete: (id: number) => void;
151
159
  select: (...cols: (keyof z.infer<S[Table & keyof S]> & string)[]) => QueryBuilder<NavEntity<S, R, Table>>;
160
+ on: ((event: 'insert' | 'update', callback: (row: NavEntity<S, R, Table>) => void | Promise<void>) => () => void) &
161
+ ((event: 'delete', callback: (row: { id: number }) => void | Promise<void>) => () => void);
152
162
  _tableName: string;
153
163
  readonly _schema?: S[Table & keyof S];
154
164
  };
@@ -168,12 +178,17 @@ export type AugmentedEntity<S extends z.ZodType<any>> = InferSchema<S> & {
168
178
  delete: () => void;
169
179
  };
170
180
 
181
+ export type ChangeEvent = 'insert' | 'update' | 'delete';
182
+
171
183
  export type EntityAccessor<S extends z.ZodType<any>> = {
172
184
  insert: (data: EntityData<S>) => AugmentedEntity<S>;
185
+ insertMany: (rows: EntityData<S>[]) => AugmentedEntity<S>[];
173
186
  update: ((id: number, data: Partial<EntityData<S>>) => AugmentedEntity<S> | null) & ((data: Partial<EntityData<S>>) => UpdateBuilder<AugmentedEntity<S>>);
174
187
  upsert: (conditions?: Partial<InferSchema<S>>, data?: Partial<InferSchema<S>>) => AugmentedEntity<S>;
175
188
  delete: (id: number) => void;
176
189
  select: (...cols: (keyof InferSchema<S> & string)[]) => QueryBuilder<AugmentedEntity<S>>;
190
+ on: ((event: 'insert' | 'update', callback: (row: AugmentedEntity<S>) => void | Promise<void>) => () => void) &
191
+ ((event: 'delete', callback: (row: { id: number }) => void | Promise<void>) => () => void);
177
192
  _tableName: string;
178
193
  readonly _schema?: S;
179
194
  };
@@ -186,7 +201,7 @@ export type TypedAccessors<T extends SchemaMap> = {
186
201
  // Proxy query column types
187
202
  // =============================================================================
188
203
 
189
- import type { ColumnNode } from './proxy-query';
204
+ import type { ColumnNode } from './query';
190
205
 
191
206
  export type ColumnRef = ColumnNode & string;
192
207
 
package/dist/satidb.js DELETED
@@ -1,26 +0,0 @@
1
- // @bun
2
- var HW=Object.defineProperty;var XW=($,W)=>{for(var _ in W)HW($,_,{get:W[_],enumerable:!0,configurable:!0,set:(H)=>W[_]=()=>H})};import{Database as R_}from"bun:sqlite";import{EventEmitter as q_}from"events";var v={};XW(v,{void:()=>cW,util:()=>w,unknown:()=>uW,union:()=>oW,undefined:()=>ZW,tuple:()=>sW,transformer:()=>J_,symbol:()=>hW,string:()=>a$,strictObject:()=>dW,setErrorMap:()=>QW,set:()=>eW,record:()=>aW,quotelessJson:()=>JW,promise:()=>X_,preprocess:()=>M_,pipeline:()=>B_,ostring:()=>j_,optional:()=>Y_,onumber:()=>z_,oboolean:()=>U_,objectUtil:()=>h$,object:()=>nW,number:()=>t$,nullable:()=>Q_,null:()=>mW,never:()=>lW,nativeEnum:()=>H_,nan:()=>gW,map:()=>tW,makeIssue:()=>F$,literal:()=>__,lazy:()=>W_,late:()=>PW,isValid:()=>o,isDirty:()=>P$,isAsync:()=>Q$,isAborted:()=>f$,intersection:()=>iW,instanceof:()=>NW,getParsedType:()=>m,getErrorMap:()=>Y$,function:()=>$_,enum:()=>G_,effect:()=>J_,discriminatedUnion:()=>rW,defaultErrorMap:()=>c,datetimeRegex:()=>r$,date:()=>xW,custom:()=>s$,coerce:()=>V_,boolean:()=>e$,bigint:()=>TW,array:()=>pW,any:()=>yW,addIssueToContext:()=>V,ZodVoid:()=>b$,ZodUnknown:()=>r,ZodUnion:()=>V$,ZodUndefined:()=>z$,ZodType:()=>R,ZodTuple:()=>u,ZodTransformer:()=>Z,ZodSymbol:()=>D$,ZodString:()=>g,ZodSet:()=>G$,ZodSchema:()=>R,ZodRecord:()=>v$,ZodReadonly:()=>q$,ZodPromise:()=>H$,ZodPipeline:()=>I$,ZodParsedType:()=>U,ZodOptional:()=>x,ZodObject:()=>b,ZodNumber:()=>i,ZodNullable:()=>n,ZodNull:()=>U$,ZodNever:()=>y,ZodNativeEnum:()=>A$,ZodNaN:()=>C$,ZodMap:()=>k$,ZodLiteral:()=>O$,ZodLazy:()=>E$,ZodIssueCode:()=>j,ZodIntersection:()=>L$,ZodFunction:()=>B$,ZodFirstPartyTypeKind:()=>O,ZodError:()=>f,ZodEnum:()=>a,ZodEffects:()=>Z,ZodDiscriminatedUnion:()=>N$,ZodDefault:()=>S$,ZodDate:()=>W$,ZodCatch:()=>R$,ZodBranded:()=>g$,ZodBoolean:()=>j$,ZodBigInt:()=>s,ZodArray:()=>T,ZodAny:()=>_$,Schema:()=>R,ParseStatus:()=>k,OK:()=>C,NEVER:()=>L_,INVALID:()=>E,EMPTY_PATH:()=>MW,DIRTY:()=>$$,BRAND:()=>fW});var w;(function($){$.assertEqual=(G)=>{};function W(G){}$.assertIs=W;function _(G){throw Error()}$.assertNever=_,$.arrayToEnum=(G)=>{let X={};for(let J of G)X[J]=J;return X},$.getValidEnumValues=(G)=>{let X=$.objectKeys(G).filter((Y)=>typeof G[G[Y]]!=="number"),J={};for(let Y of X)J[Y]=G[Y];return $.objectValues(J)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(X){return G[X]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let X=[];for(let J in G)if(Object.prototype.hasOwnProperty.call(G,J))X.push(J);return X},$.find=(G,X)=>{for(let J of G)if(X(J))return J;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function H(G,X=" | "){return G.map((J)=>typeof J==="string"?`'${J}'`:J).join(X)}$.joinValues=H,$.jsonStringifyReplacer=(G,X)=>{if(typeof X==="bigint")return X.toString();return X}})(w||(w={}));var h$;(function($){$.mergeShapes=(W,_)=>{return{...W,..._}}})(h$||(h$={}));var U=w.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),m=($)=>{switch(typeof $){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN($)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":if(Array.isArray($))return U.array;if($===null)return U.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return U.promise;if(typeof Map<"u"&&$ instanceof Map)return U.map;if(typeof Set<"u"&&$ instanceof Set)return U.set;if(typeof Date<"u"&&$ instanceof Date)return U.date;return U.object;default:return U.unknown}};var j=w.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"]),JW=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class f extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(_)=>{this.issues=[...this.issues,_]},this.addIssues=(_=[])=>{this.issues=[...this.issues,..._]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(G){return G.message},_={_errors:[]},H=(G)=>{for(let X of G.issues)if(X.code==="invalid_union")X.unionErrors.map(H);else if(X.code==="invalid_return_type")H(X.returnTypeError);else if(X.code==="invalid_arguments")H(X.argumentsError);else if(X.path.length===0)_._errors.push(W(X));else{let J=_,Y=0;while(Y<X.path.length){let Q=X.path[Y];if(Y!==X.path.length-1)J[Q]=J[Q]||{_errors:[]};else J[Q]=J[Q]||{_errors:[]},J[Q]._errors.push(W(X));J=J[Q],Y++}}};return H(this),_}static assert($){if(!($ instanceof f))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,w.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},_=[];for(let H of this.issues)if(H.path.length>0){let G=H.path[0];W[G]=W[G]||[],W[G].push($(H))}else _.push($(H));return{formErrors:_,fieldErrors:W}}get formErrors(){return this.flatten()}}f.create=($)=>{return new f($)};var YW=($,W)=>{let _;switch($.code){case j.invalid_type:if($.received===U.undefined)_="Required";else _=`Expected ${$.expected}, received ${$.received}`;break;case j.invalid_literal:_=`Invalid literal value, expected ${JSON.stringify($.expected,w.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:_=`Unrecognized key(s) in object: ${w.joinValues($.keys,", ")}`;break;case j.invalid_union:_="Invalid input";break;case j.invalid_union_discriminator:_=`Invalid discriminator value. Expected ${w.joinValues($.options)}`;break;case j.invalid_enum_value:_=`Invalid enum value. Expected ${w.joinValues($.options)}, received '${$.received}'`;break;case j.invalid_arguments:_="Invalid function arguments";break;case j.invalid_return_type:_="Invalid function return type";break;case j.invalid_date:_="Invalid date";break;case j.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(_=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")_=`${_} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)_=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)_=`Invalid input: must end with "${$.validation.endsWith}"`;else w.assertNever($.validation);else if($.validation!=="regex")_=`Invalid ${$.validation}`;else _="Invalid";break;case j.too_small:if($.type==="array")_=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")_=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")_=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")_=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")_=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else _="Invalid input";break;case j.too_big:if($.type==="array")_=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")_=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")_=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")_=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")_=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else _="Invalid input";break;case j.custom:_="Invalid input";break;case j.invalid_intersection_types:_="Intersection results could not be merged";break;case j.not_multiple_of:_=`Number must be a multiple of ${$.multipleOf}`;break;case j.not_finite:_="Number must be finite";break;default:_=W.defaultError,w.assertNever($)}return{message:_}},c=YW;var c$=c;function QW($){c$=$}function Y$(){return c$}var F$=($)=>{let{data:W,path:_,errorMaps:H,issueData:G}=$,X=[..._,...G.path||[]],J={...G,path:X};if(G.message!==void 0)return{...G,path:X,message:G.message};let Y="",Q=H.filter((M)=>!!M).slice().reverse();for(let M of Q)Y=M(J,{data:W,defaultError:Y}).message;return{...G,path:X,message:Y}},MW=[];function V($,W){let _=Y$(),H=F$({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,_,_===c?void 0:c].filter((G)=>!!G)});$.common.issues.push(H)}class k{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let _=[];for(let H of W){if(H.status==="aborted")return E;if(H.status==="dirty")$.dirty();_.push(H.value)}return{status:$.value,value:_}}static async mergeObjectAsync($,W){let _=[];for(let H of W){let G=await H.key,X=await H.value;_.push({key:G,value:X})}return k.mergeObjectSync($,_)}static mergeObjectSync($,W){let _={};for(let H of W){let{key:G,value:X}=H;if(G.status==="aborted")return E;if(X.status==="aborted")return E;if(G.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof X.value<"u"||H.alwaysSet))_[G.value]=X.value}return{status:$.value,value:_}}}var E=Object.freeze({status:"aborted"}),$$=($)=>({status:"dirty",value:$}),C=($)=>({status:"valid",value:$}),f$=($)=>$.status==="aborted",P$=($)=>$.status==="dirty",o=($)=>$.status==="valid",Q$=($)=>typeof Promise<"u"&&$ instanceof Promise;var L;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(L||(L={}));class h{constructor($,W,_,H){this._cachedPath=[],this.parent=$,this.data=W,this._path=_,this._key=H}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}}var p$=($,W)=>{if(o(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let _=new f($.common.issues);return this._error=_,this._error}}}};function S($){if(!$)return{};let{errorMap:W,invalid_type_error:_,required_error:H,description:G}=$;if(W&&(_||H))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:G};return{errorMap:(J,Y)=>{let{message:Q}=$;if(J.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??H??Y.defaultError};if(J.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??_??Y.defaultError}},description:G}}class R{get description(){return this._def.description}_getType($){return m($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:m($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new k,ctx:{common:$.parent.common,data:$.data,parsedType:m($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(Q$(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let _=this.safeParse($,W);if(_.success)return _.data;throw _.error}safeParse($,W){let _={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:m($)},H=this._parseSync({data:$,path:_.path,parent:_});return p$(_,H)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:m($)};if(!this["~standard"].async)try{let _=this._parseSync({data:$,path:[],parent:W});return o(_)?{value:_.value}:{issues:W.common.issues}}catch(_){if(_?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((_)=>o(_)?{value:_.value}:{issues:W.common.issues})}async parseAsync($,W){let _=await this.safeParseAsync($,W);if(_.success)return _.data;throw _.error}async safeParseAsync($,W){let _={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:m($)},H=this._parse({data:$,path:_.path,parent:_}),G=await(Q$(H)?H:Promise.resolve(H));return p$(_,G)}refine($,W){let _=(H)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(H);else return W};return this._refinement((H,G)=>{let X=$(H),J=()=>G.addIssue({code:j.custom,..._(H)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return J(),!1;else return!0});if(!X)return J(),!1;else return!0})}refinement($,W){return this._refinement((_,H)=>{if(!$(_))return H.addIssue(typeof W==="function"?W(_,H):W),!1;else return!0})}_refinement($){return new Z({schema:this,typeName:O.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,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:(W)=>this["~validate"](W)}}optional(){return x.create(this,this._def)}nullable(){return n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return T.create(this)}promise(){return H$.create(this,this._def)}or($){return V$.create([this,$],this._def)}and($){return L$.create(this,$,this._def)}transform($){return new Z({...S(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new S$({...S(this._def),innerType:this,defaultValue:W,typeName:O.ZodDefault})}brand(){return new g$({typeName:O.ZodBranded,type:this,...S(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new R$({...S(this._def),innerType:this,catchValue:W,typeName:O.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return I$.create(this,$)}readonly(){return q$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var BW=/^c[^\s-]{8,}$/i,jW=/^[0-9a-z]+$/,zW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,UW=/^[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,VW=/^[a-z0-9_-]{21}$/i,LW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,EW=/^[-+]?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)?)??$/,OW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,AW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Z$,SW=/^(?:(?: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])$/,RW=/^(?:(?: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])$/,qW=/^(([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]))$/,wW=/^(([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])$/,KW=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,FW=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,d$="((\\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])))",DW=new RegExp(`^${d$}$`);function o$($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let _=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${_}`}function bW($){return new RegExp(`^${o$($)}$`)}function r$($){let W=`${d$}T${o$($)}`,_=[];if(_.push($.local?"Z?":"Z"),$.offset)_.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${_.join("|")})`,new RegExp(`^${W}$`)}function vW($,W){if((W==="v4"||!W)&&SW.test($))return!0;if((W==="v6"||!W)&&qW.test($))return!0;return!1}function kW($,W){if(!LW.test($))return!1;try{let[_]=$.split(".");if(!_)return!1;let H=_.replace(/-/g,"+").replace(/_/g,"/").padEnd(_.length+(4-_.length%4)%4,"="),G=JSON.parse(atob(H));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(W&&G.alg!==W)return!1;return!0}catch{return!1}}function CW($,W){if((W==="v4"||!W)&&RW.test($))return!0;if((W==="v6"||!W)&&wW.test($))return!0;return!1}class g extends R{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==U.string){let G=this._getOrReturnCtx($);return V(G,{code:j.invalid_type,expected:U.string,received:G.parsedType}),E}let _=new k,H=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)H=this._getOrReturnCtx($,H),V(H,{code:j.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),_.dirty()}else if(G.kind==="max"){if($.data.length>G.value)H=this._getOrReturnCtx($,H),V(H,{code:j.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),_.dirty()}else if(G.kind==="length"){let X=$.data.length>G.value,J=$.data.length<G.value;if(X||J){if(H=this._getOrReturnCtx($,H),X)V(H,{code:j.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(J)V(H,{code:j.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});_.dirty()}}else if(G.kind==="email"){if(!OW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"email",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="emoji"){if(!Z$)Z$=new RegExp(AW,"u");if(!Z$.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"emoji",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="uuid"){if(!UW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"uuid",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="nanoid"){if(!VW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"nanoid",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="cuid"){if(!BW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"cuid",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="cuid2"){if(!jW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"cuid2",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="ulid"){if(!zW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"ulid",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{H=this._getOrReturnCtx($,H),V(H,{validation:"url",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"regex",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))H=this._getOrReturnCtx($,H),V(H,{code:j.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),_.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))H=this._getOrReturnCtx($,H),V(H,{code:j.invalid_string,validation:{startsWith:G.value},message:G.message}),_.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))H=this._getOrReturnCtx($,H),V(H,{code:j.invalid_string,validation:{endsWith:G.value},message:G.message}),_.dirty()}else if(G.kind==="datetime"){if(!r$(G).test($.data))H=this._getOrReturnCtx($,H),V(H,{code:j.invalid_string,validation:"datetime",message:G.message}),_.dirty()}else if(G.kind==="date"){if(!DW.test($.data))H=this._getOrReturnCtx($,H),V(H,{code:j.invalid_string,validation:"date",message:G.message}),_.dirty()}else if(G.kind==="time"){if(!bW(G).test($.data))H=this._getOrReturnCtx($,H),V(H,{code:j.invalid_string,validation:"time",message:G.message}),_.dirty()}else if(G.kind==="duration"){if(!EW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"duration",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="ip"){if(!vW($.data,G.version))H=this._getOrReturnCtx($,H),V(H,{validation:"ip",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="jwt"){if(!kW($.data,G.alg))H=this._getOrReturnCtx($,H),V(H,{validation:"jwt",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="cidr"){if(!CW($.data,G.version))H=this._getOrReturnCtx($,H),V(H,{validation:"cidr",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="base64"){if(!KW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"base64",code:j.invalid_string,message:G.message}),_.dirty()}else if(G.kind==="base64url"){if(!FW.test($.data))H=this._getOrReturnCtx($,H),V(H,{validation:"base64url",code:j.invalid_string,message:G.message}),_.dirty()}else w.assertNever(G);return{status:_.value,value:$.data}}_regex($,W,_){return this.refinement((H)=>$.test(H),{validation:W,code:j.invalid_string,...L.errToObj(_)})}_addCheck($){return new g({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...L.errToObj($)})}url($){return this._addCheck({kind:"url",...L.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...L.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...L.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...L.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...L.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...L.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...L.errToObj($)})}base64($){return this._addCheck({kind:"base64",...L.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...L.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...L.errToObj($)})}ip($){return this._addCheck({kind:"ip",...L.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...L.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...L.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...L.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...L.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...L.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...L.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...L.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...L.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...L.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...L.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...L.errToObj(W)})}nonempty($){return this.min(1,L.errToObj($))}trim(){return new g({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new g({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new g({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}g.create=($)=>{return new g({checks:[],typeName:O.ZodString,coerce:$?.coerce??!1,...S($)})};function IW($,W){let _=($.toString().split(".")[1]||"").length,H=(W.toString().split(".")[1]||"").length,G=_>H?_:H,X=Number.parseInt($.toFixed(G).replace(".","")),J=Number.parseInt(W.toFixed(G).replace(".",""));return X%J/10**G}class i extends R{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==U.number){let G=this._getOrReturnCtx($);return V(G,{code:j.invalid_type,expected:U.number,received:G.parsedType}),E}let _=void 0,H=new k;for(let G of this._def.checks)if(G.kind==="int"){if(!w.isInteger($.data))_=this._getOrReturnCtx($,_),V(_,{code:j.invalid_type,expected:"integer",received:"float",message:G.message}),H.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)_=this._getOrReturnCtx($,_),V(_,{code:j.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),H.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)_=this._getOrReturnCtx($,_),V(_,{code:j.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),H.dirty()}else if(G.kind==="multipleOf"){if(IW($.data,G.value)!==0)_=this._getOrReturnCtx($,_),V(_,{code:j.not_multiple_of,multipleOf:G.value,message:G.message}),H.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))_=this._getOrReturnCtx($,_),V(_,{code:j.not_finite,message:G.message}),H.dirty()}else w.assertNever(G);return{status:H.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,L.toString(W))}gt($,W){return this.setLimit("min",$,!1,L.toString(W))}lte($,W){return this.setLimit("max",$,!0,L.toString(W))}lt($,W){return this.setLimit("max",$,!1,L.toString(W))}setLimit($,W,_,H){return new i({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:_,message:L.toString(H)}]})}_addCheck($){return new i({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:L.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:L.toString(W)})}finite($){return this._addCheck({kind:"finite",message:L.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&w.isInteger($.value))}get isFinite(){let $=null,W=null;for(let _ of this._def.checks)if(_.kind==="finite"||_.kind==="int"||_.kind==="multipleOf")return!0;else if(_.kind==="min"){if(W===null||_.value>W)W=_.value}else if(_.kind==="max"){if($===null||_.value<$)$=_.value}return Number.isFinite(W)&&Number.isFinite($)}}i.create=($)=>{return new i({checks:[],typeName:O.ZodNumber,coerce:$?.coerce||!1,...S($)})};class s extends R{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==U.bigint)return this._getInvalidInput($);let _=void 0,H=new k;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)_=this._getOrReturnCtx($,_),V(_,{code:j.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),H.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)_=this._getOrReturnCtx($,_),V(_,{code:j.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),H.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))_=this._getOrReturnCtx($,_),V(_,{code:j.not_multiple_of,multipleOf:G.value,message:G.message}),H.dirty()}else w.assertNever(G);return{status:H.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return V(W,{code:j.invalid_type,expected:U.bigint,received:W.parsedType}),E}gte($,W){return this.setLimit("min",$,!0,L.toString(W))}gt($,W){return this.setLimit("min",$,!1,L.toString(W))}lte($,W){return this.setLimit("max",$,!0,L.toString(W))}lt($,W){return this.setLimit("max",$,!1,L.toString(W))}setLimit($,W,_,H){return new s({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:_,message:L.toString(H)}]})}_addCheck($){return new s({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:L.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}s.create=($)=>{return new s({checks:[],typeName:O.ZodBigInt,coerce:$?.coerce??!1,...S($)})};class j$ extends R{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==U.boolean){let _=this._getOrReturnCtx($);return V(_,{code:j.invalid_type,expected:U.boolean,received:_.parsedType}),E}return C($.data)}}j$.create=($)=>{return new j$({typeName:O.ZodBoolean,coerce:$?.coerce||!1,...S($)})};class W$ extends R{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==U.date){let G=this._getOrReturnCtx($);return V(G,{code:j.invalid_type,expected:U.date,received:G.parsedType}),E}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return V(G,{code:j.invalid_date}),E}let _=new k,H=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)H=this._getOrReturnCtx($,H),V(H,{code:j.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),_.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)H=this._getOrReturnCtx($,H),V(H,{code:j.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),_.dirty()}else w.assertNever(G);return{status:_.value,value:new Date($.data.getTime())}}_addCheck($){return new W$({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:L.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:L.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}W$.create=($)=>{return new W$({checks:[],coerce:$?.coerce||!1,typeName:O.ZodDate,...S($)})};class D$ extends R{_parse($){if(this._getType($)!==U.symbol){let _=this._getOrReturnCtx($);return V(_,{code:j.invalid_type,expected:U.symbol,received:_.parsedType}),E}return C($.data)}}D$.create=($)=>{return new D$({typeName:O.ZodSymbol,...S($)})};class z$ extends R{_parse($){if(this._getType($)!==U.undefined){let _=this._getOrReturnCtx($);return V(_,{code:j.invalid_type,expected:U.undefined,received:_.parsedType}),E}return C($.data)}}z$.create=($)=>{return new z$({typeName:O.ZodUndefined,...S($)})};class U$ extends R{_parse($){if(this._getType($)!==U.null){let _=this._getOrReturnCtx($);return V(_,{code:j.invalid_type,expected:U.null,received:_.parsedType}),E}return C($.data)}}U$.create=($)=>{return new U$({typeName:O.ZodNull,...S($)})};class _$ extends R{constructor(){super(...arguments);this._any=!0}_parse($){return C($.data)}}_$.create=($)=>{return new _$({typeName:O.ZodAny,...S($)})};class r extends R{constructor(){super(...arguments);this._unknown=!0}_parse($){return C($.data)}}r.create=($)=>{return new r({typeName:O.ZodUnknown,...S($)})};class y extends R{_parse($){let W=this._getOrReturnCtx($);return V(W,{code:j.invalid_type,expected:U.never,received:W.parsedType}),E}}y.create=($)=>{return new y({typeName:O.ZodNever,...S($)})};class b$ extends R{_parse($){if(this._getType($)!==U.undefined){let _=this._getOrReturnCtx($);return V(_,{code:j.invalid_type,expected:U.void,received:_.parsedType}),E}return C($.data)}}b$.create=($)=>{return new b$({typeName:O.ZodVoid,...S($)})};class T extends R{_parse($){let{ctx:W,status:_}=this._processInputParams($),H=this._def;if(W.parsedType!==U.array)return V(W,{code:j.invalid_type,expected:U.array,received:W.parsedType}),E;if(H.exactLength!==null){let X=W.data.length>H.exactLength.value,J=W.data.length<H.exactLength.value;if(X||J)V(W,{code:X?j.too_big:j.too_small,minimum:J?H.exactLength.value:void 0,maximum:X?H.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:H.exactLength.message}),_.dirty()}if(H.minLength!==null){if(W.data.length<H.minLength.value)V(W,{code:j.too_small,minimum:H.minLength.value,type:"array",inclusive:!0,exact:!1,message:H.minLength.message}),_.dirty()}if(H.maxLength!==null){if(W.data.length>H.maxLength.value)V(W,{code:j.too_big,maximum:H.maxLength.value,type:"array",inclusive:!0,exact:!1,message:H.maxLength.message}),_.dirty()}if(W.common.async)return Promise.all([...W.data].map((X,J)=>{return H.type._parseAsync(new h(W,X,W.path,J))})).then((X)=>{return k.mergeArray(_,X)});let G=[...W.data].map((X,J)=>{return H.type._parseSync(new h(W,X,W.path,J))});return k.mergeArray(_,G)}get element(){return this._def.type}min($,W){return new T({...this._def,minLength:{value:$,message:L.toString(W)}})}max($,W){return new T({...this._def,maxLength:{value:$,message:L.toString(W)}})}length($,W){return new T({...this._def,exactLength:{value:$,message:L.toString(W)}})}nonempty($){return this.min(1,$)}}T.create=($,W)=>{return new T({type:$,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...S(W)})};function M$($){if($ instanceof b){let W={};for(let _ in $.shape){let H=$.shape[_];W[_]=x.create(M$(H))}return new b({...$._def,shape:()=>W})}else if($ instanceof T)return new T({...$._def,type:M$($.element)});else if($ instanceof x)return x.create(M$($.unwrap()));else if($ instanceof n)return n.create(M$($.unwrap()));else if($ instanceof u)return u.create($.items.map((W)=>M$(W)));else return $}class b extends R{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=w.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==U.object){let Q=this._getOrReturnCtx($);return V(Q,{code:j.invalid_type,expected:U.object,received:Q.parsedType}),E}let{status:_,ctx:H}=this._processInputParams($),{shape:G,keys:X}=this._getCached(),J=[];if(!(this._def.catchall instanceof y&&this._def.unknownKeys==="strip")){for(let Q in H.data)if(!X.includes(Q))J.push(Q)}let Y=[];for(let Q of X){let M=G[Q],B=H.data[Q];Y.push({key:{status:"valid",value:Q},value:M._parse(new h(H,B,H.path,Q)),alwaysSet:Q in H.data})}if(this._def.catchall instanceof y){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let M of J)Y.push({key:{status:"valid",value:M},value:{status:"valid",value:H.data[M]}});else if(Q==="strict"){if(J.length>0)V(H,{code:j.unrecognized_keys,keys:J}),_.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let M of J){let B=H.data[M];Y.push({key:{status:"valid",value:M},value:Q._parse(new h(H,B,H.path,M)),alwaysSet:M in H.data})}}if(H.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let M of Y){let B=await M.key,z=await M.value;Q.push({key:B,value:z,alwaysSet:M.alwaysSet})}return Q}).then((Q)=>{return k.mergeObjectSync(_,Q)});else return k.mergeObjectSync(_,Y)}get shape(){return this._def.shape()}strict($){return L.errToObj,new b({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,_)=>{let H=this._def.errorMap?.(W,_).message??_.defaultError;if(W.code==="unrecognized_keys")return{message:L.errToObj($).message??H};return{message:H}}}:{}})}strip(){return new b({...this._def,unknownKeys:"strip"})}passthrough(){return new b({...this._def,unknownKeys:"passthrough"})}extend($){return new b({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new b({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:O.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new b({...this._def,catchall:$})}pick($){let W={};for(let _ of w.objectKeys($))if($[_]&&this.shape[_])W[_]=this.shape[_];return new b({...this._def,shape:()=>W})}omit($){let W={};for(let _ of w.objectKeys(this.shape))if(!$[_])W[_]=this.shape[_];return new b({...this._def,shape:()=>W})}deepPartial(){return M$(this)}partial($){let W={};for(let _ of w.objectKeys(this.shape)){let H=this.shape[_];if($&&!$[_])W[_]=H;else W[_]=H.optional()}return new b({...this._def,shape:()=>W})}required($){let W={};for(let _ of w.objectKeys(this.shape))if($&&!$[_])W[_]=this.shape[_];else{let G=this.shape[_];while(G instanceof x)G=G._def.innerType;W[_]=G}return new b({...this._def,shape:()=>W})}keyof(){return i$(w.objectKeys(this.shape))}}b.create=($,W)=>{return new b({shape:()=>$,unknownKeys:"strip",catchall:y.create(),typeName:O.ZodObject,...S(W)})};b.strictCreate=($,W)=>{return new b({shape:()=>$,unknownKeys:"strict",catchall:y.create(),typeName:O.ZodObject,...S(W)})};b.lazycreate=($,W)=>{return new b({shape:$,unknownKeys:"strip",catchall:y.create(),typeName:O.ZodObject,...S(W)})};class V$ extends R{_parse($){let{ctx:W}=this._processInputParams($),_=this._def.options;function H(G){for(let J of G)if(J.result.status==="valid")return J.result;for(let J of G)if(J.result.status==="dirty")return W.common.issues.push(...J.ctx.common.issues),J.result;let X=G.map((J)=>new f(J.ctx.common.issues));return V(W,{code:j.invalid_union,unionErrors:X}),E}if(W.common.async)return Promise.all(_.map(async(G)=>{let X={...W,common:{...W.common,issues:[]},parent:null};return{result:await G._parseAsync({data:W.data,path:W.path,parent:X}),ctx:X}})).then(H);else{let G=void 0,X=[];for(let Y of _){let Q={...W,common:{...W.common,issues:[]},parent:null},M=Y._parseSync({data:W.data,path:W.path,parent:Q});if(M.status==="valid")return M;else if(M.status==="dirty"&&!G)G={result:M,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(G)return W.common.issues.push(...G.ctx.common.issues),G.result;let J=X.map((Y)=>new f(Y));return V(W,{code:j.invalid_union,unionErrors:J}),E}}get options(){return this._def.options}}V$.create=($,W)=>{return new V$({options:$,typeName:O.ZodUnion,...S(W)})};var p=($)=>{if($ instanceof E$)return p($.schema);else if($ instanceof Z)return p($.innerType());else if($ instanceof O$)return[$.value];else if($ instanceof a)return $.options;else if($ instanceof A$)return w.objectValues($.enum);else if($ instanceof S$)return p($._def.innerType);else if($ instanceof z$)return[void 0];else if($ instanceof U$)return[null];else if($ instanceof x)return[void 0,...p($.unwrap())];else if($ instanceof n)return[null,...p($.unwrap())];else if($ instanceof g$)return p($.unwrap());else if($ instanceof q$)return p($.unwrap());else if($ instanceof R$)return p($._def.innerType);else return[]};class N$ extends R{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==U.object)return V(W,{code:j.invalid_type,expected:U.object,received:W.parsedType}),E;let _=this.discriminator,H=W.data[_],G=this.optionsMap.get(H);if(!G)return V(W,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[_]}),E;if(W.common.async)return G._parseAsync({data:W.data,path:W.path,parent:W});else return G._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,_){let H=new Map;for(let G of W){let X=p(G.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let J of X){if(H.has(J))throw Error(`Discriminator property ${String($)} has duplicate value ${String(J)}`);H.set(J,G)}}return new N$({typeName:O.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:H,...S(_)})}}function m$($,W){let _=m($),H=m(W);if($===W)return{valid:!0,data:$};else if(_===U.object&&H===U.object){let G=w.objectKeys(W),X=w.objectKeys($).filter((Y)=>G.indexOf(Y)!==-1),J={...$,...W};for(let Y of X){let Q=m$($[Y],W[Y]);if(!Q.valid)return{valid:!1};J[Y]=Q.data}return{valid:!0,data:J}}else if(_===U.array&&H===U.array){if($.length!==W.length)return{valid:!1};let G=[];for(let X=0;X<$.length;X++){let J=$[X],Y=W[X],Q=m$(J,Y);if(!Q.valid)return{valid:!1};G.push(Q.data)}return{valid:!0,data:G}}else if(_===U.date&&H===U.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class L$ extends R{_parse($){let{status:W,ctx:_}=this._processInputParams($),H=(G,X)=>{if(f$(G)||f$(X))return E;let J=m$(G.value,X.value);if(!J.valid)return V(_,{code:j.invalid_intersection_types}),E;if(P$(G)||P$(X))W.dirty();return{status:W.value,value:J.data}};if(_.common.async)return Promise.all([this._def.left._parseAsync({data:_.data,path:_.path,parent:_}),this._def.right._parseAsync({data:_.data,path:_.path,parent:_})]).then(([G,X])=>H(G,X));else return H(this._def.left._parseSync({data:_.data,path:_.path,parent:_}),this._def.right._parseSync({data:_.data,path:_.path,parent:_}))}}L$.create=($,W,_)=>{return new L$({left:$,right:W,typeName:O.ZodIntersection,...S(_)})};class u extends R{_parse($){let{status:W,ctx:_}=this._processInputParams($);if(_.parsedType!==U.array)return V(_,{code:j.invalid_type,expected:U.array,received:_.parsedType}),E;if(_.data.length<this._def.items.length)return V(_,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;if(!this._def.rest&&_.data.length>this._def.items.length)V(_,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let G=[..._.data].map((X,J)=>{let Y=this._def.items[J]||this._def.rest;if(!Y)return null;return Y._parse(new h(_,X,_.path,J))}).filter((X)=>!!X);if(_.common.async)return Promise.all(G).then((X)=>{return k.mergeArray(W,X)});else return k.mergeArray(W,G)}get items(){return this._def.items}rest($){return new u({...this._def,rest:$})}}u.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new u({items:$,typeName:O.ZodTuple,rest:null,...S(W)})};class v$ extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:_}=this._processInputParams($);if(_.parsedType!==U.object)return V(_,{code:j.invalid_type,expected:U.object,received:_.parsedType}),E;let H=[],G=this._def.keyType,X=this._def.valueType;for(let J in _.data)H.push({key:G._parse(new h(_,J,_.path,J)),value:X._parse(new h(_,_.data[J],_.path,J)),alwaysSet:J in _.data});if(_.common.async)return k.mergeObjectAsync(W,H);else return k.mergeObjectSync(W,H)}get element(){return this._def.valueType}static create($,W,_){if(W instanceof R)return new v$({keyType:$,valueType:W,typeName:O.ZodRecord,...S(_)});return new v$({keyType:g.create(),valueType:$,typeName:O.ZodRecord,...S(W)})}}class k$ extends R{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:_}=this._processInputParams($);if(_.parsedType!==U.map)return V(_,{code:j.invalid_type,expected:U.map,received:_.parsedType}),E;let H=this._def.keyType,G=this._def.valueType,X=[..._.data.entries()].map(([J,Y],Q)=>{return{key:H._parse(new h(_,J,_.path,[Q,"key"])),value:G._parse(new h(_,Y,_.path,[Q,"value"]))}});if(_.common.async){let J=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,M=await Y.value;if(Q.status==="aborted"||M.status==="aborted")return E;if(Q.status==="dirty"||M.status==="dirty")W.dirty();J.set(Q.value,M.value)}return{status:W.value,value:J}})}else{let J=new Map;for(let Y of X){let{key:Q,value:M}=Y;if(Q.status==="aborted"||M.status==="aborted")return E;if(Q.status==="dirty"||M.status==="dirty")W.dirty();J.set(Q.value,M.value)}return{status:W.value,value:J}}}}k$.create=($,W,_)=>{return new k$({valueType:W,keyType:$,typeName:O.ZodMap,...S(_)})};class G$ extends R{_parse($){let{status:W,ctx:_}=this._processInputParams($);if(_.parsedType!==U.set)return V(_,{code:j.invalid_type,expected:U.set,received:_.parsedType}),E;let H=this._def;if(H.minSize!==null){if(_.data.size<H.minSize.value)V(_,{code:j.too_small,minimum:H.minSize.value,type:"set",inclusive:!0,exact:!1,message:H.minSize.message}),W.dirty()}if(H.maxSize!==null){if(_.data.size>H.maxSize.value)V(_,{code:j.too_big,maximum:H.maxSize.value,type:"set",inclusive:!0,exact:!1,message:H.maxSize.message}),W.dirty()}let G=this._def.valueType;function X(Y){let Q=new Set;for(let M of Y){if(M.status==="aborted")return E;if(M.status==="dirty")W.dirty();Q.add(M.value)}return{status:W.value,value:Q}}let J=[..._.data.values()].map((Y,Q)=>G._parse(new h(_,Y,_.path,Q)));if(_.common.async)return Promise.all(J).then((Y)=>X(Y));else return X(J)}min($,W){return new G$({...this._def,minSize:{value:$,message:L.toString(W)}})}max($,W){return new G$({...this._def,maxSize:{value:$,message:L.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}G$.create=($,W)=>{return new G$({valueType:$,minSize:null,maxSize:null,typeName:O.ZodSet,...S(W)})};class B$ extends R{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==U.function)return V(W,{code:j.invalid_type,expected:U.function,received:W.parsedType}),E;function _(J,Y){return F$({data:J,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,Y$(),c].filter((Q)=>!!Q),issueData:{code:j.invalid_arguments,argumentsError:Y}})}function H(J,Y){return F$({data:J,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,Y$(),c].filter((Q)=>!!Q),issueData:{code:j.invalid_return_type,returnTypeError:Y}})}let G={errorMap:W.common.contextualErrorMap},X=W.data;if(this._def.returns instanceof H$){let J=this;return C(async function(...Y){let Q=new f([]),M=await J._def.args.parseAsync(Y,G).catch((A)=>{throw Q.addIssue(_(Y,A)),Q}),B=await Reflect.apply(X,this,M);return await J._def.returns._def.type.parseAsync(B,G).catch((A)=>{throw Q.addIssue(H(B,A)),Q})})}else{let J=this;return C(function(...Y){let Q=J._def.args.safeParse(Y,G);if(!Q.success)throw new f([_(Y,Q.error)]);let M=Reflect.apply(X,this,Q.data),B=J._def.returns.safeParse(M,G);if(!B.success)throw new f([H(M,B.error)]);return B.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new B$({...this._def,args:u.create($).rest(r.create())})}returns($){return new B$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,_){return new B$({args:$?$:u.create([]).rest(r.create()),returns:W||r.create(),typeName:O.ZodFunction,...S(_)})}}class E$ extends R{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}E$.create=($,W)=>{return new E$({getter:$,typeName:O.ZodLazy,...S(W)})};class O$ extends R{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return V(W,{received:W.data,code:j.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:$.data}}get value(){return this._def.value}}O$.create=($,W)=>{return new O$({value:$,typeName:O.ZodLiteral,...S(W)})};function i$($,W){return new a({values:$,typeName:O.ZodEnum,...S(W)})}class a extends R{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),_=this._def.values;return V(W,{expected:w.joinValues(_),received:W.parsedType,code:j.invalid_type}),E}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),_=this._def.values;return V(W,{received:W.data,code:j.invalid_enum_value,options:_}),E}return C($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return a.create($,{...this._def,...W})}exclude($,W=this._def){return a.create(this.options.filter((_)=>!$.includes(_)),{...this._def,...W})}}a.create=i$;class A$ extends R{_parse($){let W=w.getValidEnumValues(this._def.values),_=this._getOrReturnCtx($);if(_.parsedType!==U.string&&_.parsedType!==U.number){let H=w.objectValues(W);return V(_,{expected:w.joinValues(H),received:_.parsedType,code:j.invalid_type}),E}if(!this._cache)this._cache=new Set(w.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let H=w.objectValues(W);return V(_,{received:_.data,code:j.invalid_enum_value,options:H}),E}return C($.data)}get enum(){return this._def.values}}A$.create=($,W)=>{return new A$({values:$,typeName:O.ZodNativeEnum,...S(W)})};class H$ extends R{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==U.promise&&W.common.async===!1)return V(W,{code:j.invalid_type,expected:U.promise,received:W.parsedType}),E;let _=W.parsedType===U.promise?W.data:Promise.resolve(W.data);return C(_.then((H)=>{return this._def.type.parseAsync(H,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}H$.create=($,W)=>{return new H$({type:$,typeName:O.ZodPromise,...S(W)})};class Z extends R{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:_}=this._processInputParams($),H=this._def.effect||null,G={addIssue:(X)=>{if(V(_,X),X.fatal)W.abort();else W.dirty()},get path(){return _.path}};if(G.addIssue=G.addIssue.bind(G),H.type==="preprocess"){let X=H.transform(_.data,G);if(_.common.async)return Promise.resolve(X).then(async(J)=>{if(W.value==="aborted")return E;let Y=await this._def.schema._parseAsync({data:J,path:_.path,parent:_});if(Y.status==="aborted")return E;if(Y.status==="dirty")return $$(Y.value);if(W.value==="dirty")return $$(Y.value);return Y});else{if(W.value==="aborted")return E;let J=this._def.schema._parseSync({data:X,path:_.path,parent:_});if(J.status==="aborted")return E;if(J.status==="dirty")return $$(J.value);if(W.value==="dirty")return $$(J.value);return J}}if(H.type==="refinement"){let X=(J)=>{let Y=H.refinement(J,G);if(_.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return J};if(_.common.async===!1){let J=this._def.schema._parseSync({data:_.data,path:_.path,parent:_});if(J.status==="aborted")return E;if(J.status==="dirty")W.dirty();return X(J.value),{status:W.value,value:J.value}}else return this._def.schema._parseAsync({data:_.data,path:_.path,parent:_}).then((J)=>{if(J.status==="aborted")return E;if(J.status==="dirty")W.dirty();return X(J.value).then(()=>{return{status:W.value,value:J.value}})})}if(H.type==="transform")if(_.common.async===!1){let X=this._def.schema._parseSync({data:_.data,path:_.path,parent:_});if(!o(X))return E;let J=H.transform(X.value,G);if(J instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:J}}else return this._def.schema._parseAsync({data:_.data,path:_.path,parent:_}).then((X)=>{if(!o(X))return E;return Promise.resolve(H.transform(X.value,G)).then((J)=>({status:W.value,value:J}))});w.assertNever(H)}}Z.create=($,W,_)=>{return new Z({schema:$,typeName:O.ZodEffects,effect:W,...S(_)})};Z.createWithPreprocess=($,W,_)=>{return new Z({schema:W,effect:{type:"preprocess",transform:$},typeName:O.ZodEffects,...S(_)})};class x extends R{_parse($){if(this._getType($)===U.undefined)return C(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}x.create=($,W)=>{return new x({innerType:$,typeName:O.ZodOptional,...S(W)})};class n extends R{_parse($){if(this._getType($)===U.null)return C(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}n.create=($,W)=>{return new n({innerType:$,typeName:O.ZodNullable,...S(W)})};class S$ extends R{_parse($){let{ctx:W}=this._processInputParams($),_=W.data;if(W.parsedType===U.undefined)_=this._def.defaultValue();return this._def.innerType._parse({data:_,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}S$.create=($,W)=>{return new S$({innerType:$,typeName:O.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...S(W)})};class R$ extends R{_parse($){let{ctx:W}=this._processInputParams($),_={...W,common:{...W.common,issues:[]}},H=this._def.innerType._parse({data:_.data,path:_.path,parent:{..._}});if(Q$(H))return H.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new f(_.common.issues)},input:_.data})}});else return{status:"valid",value:H.status==="valid"?H.value:this._def.catchValue({get error(){return new f(_.common.issues)},input:_.data})}}removeCatch(){return this._def.innerType}}R$.create=($,W)=>{return new R$({innerType:$,typeName:O.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...S(W)})};class C$ extends R{_parse($){if(this._getType($)!==U.nan){let _=this._getOrReturnCtx($);return V(_,{code:j.invalid_type,expected:U.nan,received:_.parsedType}),E}return{status:"valid",value:$.data}}}C$.create=($)=>{return new C$({typeName:O.ZodNaN,...S($)})};var fW=Symbol("zod_brand");class g$ extends R{_parse($){let{ctx:W}=this._processInputParams($),_=W.data;return this._def.type._parse({data:_,path:W.path,parent:W})}unwrap(){return this._def.type}}class I$ extends R{_parse($){let{status:W,ctx:_}=this._processInputParams($);if(_.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:_.data,path:_.path,parent:_});if(G.status==="aborted")return E;if(G.status==="dirty")return W.dirty(),$$(G.value);else return this._def.out._parseAsync({data:G.value,path:_.path,parent:_})})();else{let H=this._def.in._parseSync({data:_.data,path:_.path,parent:_});if(H.status==="aborted")return E;if(H.status==="dirty")return W.dirty(),{status:"dirty",value:H.value};else return this._def.out._parseSync({data:H.value,path:_.path,parent:_})}}static create($,W){return new I$({in:$,out:W,typeName:O.ZodPipeline})}}class q$ extends R{_parse($){let W=this._def.innerType._parse($),_=(H)=>{if(o(H))H.value=Object.freeze(H.value);return H};return Q$(W)?W.then((H)=>_(H)):_(W)}unwrap(){return this._def.innerType}}q$.create=($,W)=>{return new q$({innerType:$,typeName:O.ZodReadonly,...S(W)})};function n$($,W){let _=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof _==="string"?{message:_}:_}function s$($,W={},_){if($)return _$.create().superRefine((H,G)=>{let X=$(H);if(X instanceof Promise)return X.then((J)=>{if(!J){let Y=n$(W,H),Q=Y.fatal??_??!0;G.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let J=n$(W,H),Y=J.fatal??_??!0;G.addIssue({code:"custom",...J,fatal:Y})}return});return _$.create()}var PW={object:b.lazycreate},O;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(O||(O={}));var NW=($,W={message:`Input not instance of ${$.name}`})=>s$((_)=>_ instanceof $,W),a$=g.create,t$=i.create,gW=C$.create,TW=s.create,e$=j$.create,xW=W$.create,hW=D$.create,ZW=z$.create,mW=U$.create,yW=_$.create,uW=r.create,lW=y.create,cW=b$.create,pW=T.create,nW=b.create,dW=b.strictCreate,oW=V$.create,rW=N$.create,iW=L$.create,sW=u.create,aW=v$.create,tW=k$.create,eW=G$.create,$_=B$.create,W_=E$.create,__=O$.create,G_=a.create,H_=A$.create,X_=H$.create,J_=Z.create,Y_=x.create,Q_=n.create,M_=Z.createWithPreprocess,B_=I$.create,j_=()=>a$().optional(),z_=()=>t$().optional(),U_=()=>e$().optional(),V_={string:($)=>g.create({...$,coerce:!0}),number:($)=>i.create({...$,coerce:!0}),boolean:($)=>j$.create({...$,coerce:!0}),bigint:($)=>s.create({...$,coerce:!0}),date:($)=>W$.create({...$,coerce:!0})};var L_=E;var F=($)=>$!==null&&typeof $==="object"&&("type"in $)?$:{type:"literal",value:$};function d($){if($.type==="column")return{sql:`"${$.name}"`,params:[]};if($.type==="literal"){if($.value instanceof Date)return{sql:"?",params:[$.value.toISOString()]};if(typeof $.value==="boolean")return{sql:"?",params:[$.value?1:0]};return{sql:"?",params:[$.value]}}if($.type==="function"){let W=$.args.map(d);return{sql:`${$.name}(${W.map((_)=>_.sql).join(", ")})`,params:W.flatMap((_)=>_.params)}}if($.type==="operator"){let W=d($.left),_=d($.right);return{sql:`(${W.sql} ${$.op} ${_.sql})`,params:[...W.params,..._.params]}}throw Error("Unknown AST node type")}var y$=()=>new Proxy({},{get:($,W)=>({type:"column",name:W})}),u$=()=>new Proxy({},{get:($,W)=>(..._)=>({type:"function",name:W.toUpperCase(),args:_.map(F)})}),l$={eq:($,W)=>({type:"operator",op:"=",left:F($),right:F(W)}),ne:($,W)=>({type:"operator",op:"!=",left:F($),right:F(W)}),gt:($,W)=>({type:"operator",op:">",left:F($),right:F(W)}),gte:($,W)=>({type:"operator",op:">=",left:F($),right:F(W)}),lt:($,W)=>({type:"operator",op:"<",left:F($),right:F(W)}),lte:($,W)=>({type:"operator",op:"<=",left:F($),right:F(W)}),and:($,W)=>({type:"operator",op:"AND",left:F($),right:F(W)}),or:($,W)=>({type:"operator",op:"OR",left:F($),right:F(W)}),like:($,W)=>({type:"operator",op:"LIKE",left:F($),right:F(W)}),isNull:($)=>({type:"operator",op:"IS",left:F($),right:{type:"literal",value:null}}),isNotNull:($)=>({type:"operator",op:"IS NOT",left:F($),right:{type:"literal",value:null}}),in:($,W)=>({type:"function",name:`${d(F($)).sql} IN`,args:W.map((_)=>F(_))}),not:($)=>({type:"operator",op:"NOT",left:{type:"literal",value:""},right:F($)})};var E_={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!=",$in:"IN"};function w$($){if($ instanceof Date)return $.toISOString();if(typeof $==="boolean")return $?1:0;return $}function $W($,W){let _=[],G=`SELECT ${W.selects.length>0?W.selects.map((X)=>`${$}.${X}`).join(", "):`${$}.*`} FROM ${$}`;if(W.whereAST){let X=d(W.whereAST);G+=` WHERE ${X.sql}`,_.push(...X.params)}else if(W.wheres.length>0){let X=[];for(let J of W.wheres)if(J.operator==="IN"){let Y=J.value;if(Y.length===0)X.push("1 = 0");else{let Q=Y.map(()=>"?").join(", ");X.push(`${J.field} IN (${Q})`),_.push(...Y.map(w$))}}else X.push(`${J.field} ${J.operator} ?`),_.push(w$(J.value));G+=` WHERE ${X.join(" AND ")}`}if(W.orderBy.length>0){let X=W.orderBy.map((J)=>`${J.field} ${J.direction.toUpperCase()}`);G+=` ORDER BY ${X.join(", ")}`}if(W.limit!==null)G+=` LIMIT ${W.limit}`;if(W.offset!==null)G+=` OFFSET ${W.offset}`;return{sql:G,params:_}}class T${iqo;tableName;executor;singleExecutor;constructor($,W,_){this.tableName=$,this.executor=W,this.singleExecutor=_,this.iqo={selects:[],wheres:[],whereAST:null,limit:null,offset:null,orderBy:[],includes:[],raw:!1}}select(...$){return this.iqo.selects.push(...$),this}where($){if(typeof $==="function"){let W=$(y$(),u$(),l$);if(this.iqo.whereAST)this.iqo.whereAST={type:"operator",op:"AND",left:this.iqo.whereAST,right:W};else this.iqo.whereAST=W}else for(let[W,_]of Object.entries($))if(typeof _==="object"&&_!==null&&!Array.isArray(_)&&!(_ instanceof Date))for(let[H,G]of Object.entries(_)){let X=E_[H];if(!X)throw Error(`Unsupported query operator: '${H}' on field '${W}'.`);this.iqo.wheres.push({field:W,operator:X,value:G})}else this.iqo.wheres.push({field:W,operator:"=",value:_});return this}limit($){return this.iqo.limit=$,this}offset($){return this.iqo.offset=$,this}orderBy($,W="asc"){return this.iqo.orderBy.push({field:$,direction:W}),this}raw(){return this.iqo.raw=!0,this}all(){let{sql:$,params:W}=$W(this.tableName,this.iqo);return this.executor($,W,this.iqo.raw)}get(){this.iqo.limit=1;let{sql:$,params:W}=$W(this.tableName,this.iqo);return this.singleExecutor($,W,this.iqo.raw)}count(){let $=[],W=`SELECT COUNT(*) as count FROM ${this.tableName}`;if(this.iqo.whereAST){let H=d(this.iqo.whereAST);W+=` WHERE ${H.sql}`,$.push(...H.params)}else if(this.iqo.wheres.length>0){let H=[];for(let G of this.iqo.wheres)if(G.operator==="IN"){let X=G.value;if(X.length===0)H.push("1 = 0");else{let J=X.map(()=>"?").join(", ");H.push(`${G.field} IN (${J})`),$.push(...X.map(w$))}}else H.push(`${G.field} ${G.operator} ?`),$.push(w$(G.value));W+=` WHERE ${H.join(" AND ")}`}return this.executor(W,$,!0)[0]?.count??0}subscribe($,W={}){let{interval:_=500,immediate:H=!0}=W,G=this.buildFingerprintSQL(),X=null,J=()=>{try{let M=this.executor(G.sql,G.params,!0)[0],B=`${M?._cnt??0}:${M?._max??0}`;if(B!==X){X=B;let z=this.all();$(z)}}catch{}};if(H)J();let Y=setInterval(J,_);return()=>{clearInterval(Y)}}buildFingerprintSQL(){let $=[],W=`SELECT COUNT(*) as _cnt, MAX(id) as _max FROM ${this.tableName}`;if(this.iqo.whereAST){let _=d(this.iqo.whereAST);W+=` WHERE ${_.sql}`,$.push(..._.params)}else if(this.iqo.wheres.length>0){let _=[];for(let H of this.iqo.wheres)if(H.operator==="IN"){let G=H.value;if(G.length===0)_.push("1 = 0");else{let X=G.map(()=>"?").join(", ");_.push(`${H.field} IN (${X})`),$.push(...G.map(w$))}}else _.push(`${H.field} ${H.operator} ?`),$.push(w$(H.value));W+=` WHERE ${_.join(" AND ")}`}return{sql:W,params:$}}then($,W){try{let _=this.all();return Promise.resolve(_).then($,W)}catch(_){return Promise.reject(_).then($,W)}}}function l($){return`"${$}"`}function t($,W){return`${l($)}.${l(W)}`}class x${_type="COL";table;column;alias;constructor($,W,_){this.table=$,this.column=W,this.alias=_}toString(){return`${l(this.alias)}.${l(this.column)}`}valueOf(){return this.toString()}[Symbol.toPrimitive]($){return this.toString()}}function O_($,W,_){return new Proxy({},{get(H,G){if(G===Symbol.toPrimitive||G==="toString"||G==="valueOf")return;return new x$($,G,W)},ownKeys(){return[..._]},getOwnPropertyDescriptor(H,G){if(_.has(G))return{configurable:!0,enumerable:!0,value:new x$($,G,W)};return}})}function A_($){let W=new Map,_=0;return{proxy:new Proxy({},{get(G,X){if(typeof X!=="string")return;let J=$[X],Y=J?new Set(Object.keys(J.shape)):new Set;_++;let Q=`t${_}`,M=O_(X,Q,Y),B=W.get(X)||[];return B.push({tableName:X,alias:Q,proxy:M}),W.set(X,B),M}}),aliasMap:W}}function WW($){return $&&typeof $==="object"&&$._type==="COL"}function S_($,W){let _=[],H=new Map;for(let[Q,M]of W)for(let B of M)H.set(B.alias,{tableName:Q,alias:B.alias});let G=[];for(let[Q,M]of Object.entries($.select))if(WW(M))if(Q===M.column)G.push(t(M.alias,M.column));else G.push(`${t(M.alias,M.column)} AS ${l(Q)}`);else G.push(`? AS ${l(Q)}`),_.push(M);let X=[...H.values()];if(X.length===0)throw Error("No tables referenced in query.");let J=X[0],Y=`SELECT ${G.join(", ")} FROM ${l(J.tableName)} ${l(J.alias)}`;if($.join){let Q=Array.isArray($.join[0])?$.join:[$.join];for(let[M,B]of Q){let z=H.get(M.alias),A=H.get(B.alias);if(!z||!A)throw Error("Join references unknown table alias.");let q=z.alias===J.alias?A:z;Y+=` JOIN ${l(q.tableName)} ${l(q.alias)} ON ${t(M.alias,M.column)} = ${t(B.alias,B.column)}`}}if($.where&&Object.keys($.where).length>0){let Q=[];for(let[M,B]of Object.entries($.where)){let z,A=M.match(/^"([^"]+)"\."([^"]+)"$/);if(A&&H.has(A[1]))z=M;else z=t(J.alias,M);if(WW(B))Q.push(`${z} = ${t(B.alias,B.column)}`);else if(Array.isArray(B))if(B.length===0)Q.push("1 = 0");else{let q=B.map(()=>"?").join(", ");Q.push(`${z} IN (${q})`),_.push(...B)}else if(typeof B==="object"&&B!==null&&!(B instanceof Date))for(let[q,K]of Object.entries(B)){let I={$gt:">",$gte:">=",$lt:"<",$lte:"<=",$ne:"!="}[q];if(!I)throw Error(`Unsupported where operator: ${q}`);Q.push(`${z} ${I} ?`),_.push(K)}else Q.push(`${z} = ?`),_.push(B instanceof Date?B.toISOString():B)}if(Q.length>0)Y+=` WHERE ${Q.join(" AND ")}`}if($.orderBy){let Q=[];for(let[M,B]of Object.entries($.orderBy)){let z,A=M.match(/^"([^"]+)"\."([^"]+)"$/);if(A&&H.has(A[1]))z=M;else z=t(J.alias,M);Q.push(`${z} ${B.toUpperCase()}`)}if(Q.length>0)Y+=` ORDER BY ${Q.join(", ")}`}if($.groupBy&&$.groupBy.length>0){let Q=$.groupBy.map((M)=>t(M.alias,M.column));Y+=` GROUP BY ${Q.join(", ")}`}if($.limit!==void 0)Y+=` LIMIT ${$.limit}`;if($.offset!==void 0)Y+=` OFFSET ${$.offset}`;return{sql:Y,params:_}}function _W($,W,_){let{proxy:H,aliasMap:G}=A_($),X=W(H),{sql:J,params:Y}=S_(X,G);return _(J,Y)}var X$=($)=>$;class GW extends q_{db;schemas;relationships;lazyMethods;subscriptions;options;constructor($,W,_={}){super();if(this.db=new R_($),this.db.run("PRAGMA foreign_keys = ON"),this.schemas=W,this.options=_,this.subscriptions={insert:{},update:{},delete:{}},this.relationships=this.parseRelationships(W),this.lazyMethods=this.buildLazyMethods(),this.initializeTables(),this.runMigrations(),_.indexes)this.createIndexes(_.indexes);if(_.changeTracking)this.setupChangeTracking();Object.keys(W).forEach((H)=>{let G=H,X={insert:(J)=>this.insert(H,J),get:(J)=>this.get(H,J),update:(J,Y)=>{if(typeof J==="number")return this.update(H,J,Y);return this._createUpdateBuilder(H,J)},upsert:(J,Y)=>this.upsert(H,Y,J),delete:(J)=>this.delete(H,J),subscribe:(J,Y)=>this.subscribe(J,H,Y),unsubscribe:(J,Y)=>this.unsubscribe(J,H,Y),select:(...J)=>this._createQueryBuilder(H,J)};this[G]=X})}parseRelationships($){let W=[];for(let[_,H]of Object.entries($)){let G=X$(H).shape;for(let[X,J]of Object.entries(G)){let Y=J;if(Y instanceof v.ZodOptional)Y=Y._def.innerType;if(Y instanceof v.ZodLazy){let Q=Y._def.getter(),M=null,B=null;if(Q instanceof v.ZodArray)M="one-to-many",B=Q._def.type;else M="belongs-to",B=Q;if(M&&B){let z=Object.keys($).find((A)=>$[A]===B);if(z){let A=M==="belongs-to"?`${X}Id`:"";W.push({type:M,from:_,to:z,relationshipField:X,foreignKey:A})}}}}}return W}buildLazyMethods(){let $={};for(let W of this.relationships)if($[W.from]=$[W.from]||[],W.type==="one-to-many"){let _=this.relationships.find((G)=>G.type==="belongs-to"&&G.from===W.to&&G.to===W.from);if(!_)throw Error(`No 'belongs-to' relationship found for one-to-many from ${W.from} to ${W.to}`);let H=_.foreignKey;$[W.from].push({name:W.relationshipField,type:"one-to-many",childEntityName:W.to,parentEntityName:W.from,fetch:(G)=>({insert:(X)=>this.insert(W.to,{...X,[H]:G.id}),get:(X)=>{let J=typeof X==="number"?{id:X}:X;return this.get(W.to,{...J,[H]:G.id})},findOne:(X)=>this.findOne(W.to,{...X,[H]:G.id}),find:(X={})=>this.find(W.to,{...X,[H]:G.id}),update:(X,J)=>this.update(W.to,X,J),upsert:(X={},J={})=>this.upsert(W.to,{...J,[H]:G.id},{...X,[H]:G.id}),delete:(X)=>{if(X)this.delete(W.to,X);else this.find(W.to,{[H]:G.id}).forEach((Y)=>this.delete(W.to,Y.id))},subscribe:(X,J)=>this.subscribe(X,W.to,J),unsubscribe:(X,J)=>this.unsubscribe(X,W.to,J),push:(X)=>this.insert(W.to,{...X,[H]:G.id})})})}else if(W.type==="belongs-to"){$[W.from].push({name:W.relationshipField,type:"belongs-to",fetch:(Y)=>{let Q=Y[W.foreignKey];return()=>Q?this.get(W.to,{id:Q}):null}});let _=W.from;$[W.to]=$[W.to]||[];let H=this.relationships.find((Y)=>Y.type==="one-to-many"&&Y.from===W.to&&Y.to===W.from);if(!H)throw Error(`No one-to-many relationship found for inverse from ${W.to} to ${W.from}`);let G=H.relationshipField,X=this.relationships.find((Y)=>Y.type==="belongs-to"&&Y.from===W.from&&Y.to===W.to);if(!X)throw Error(`No 'belongs-to' relationship found for ${W.from} to ${W.to}`);let J=X.foreignKey;if(!$[W.to].some((Y)=>Y.name===G))$[W.to].push({name:G,type:"one-to-many",childEntityName:W.from,parentEntityName:W.to,fetch:(Y)=>({insert:(Q)=>this.insert(W.from,{...Q,[J]:Y.id}),get:(Q)=>{let M=typeof Q==="number"?{id:Q}:Q;return this.get(W.from,{...M,[J]:Y.id})},findOne:(Q)=>this.findOne(W.from,{...Q,[J]:Y.id}),find:(Q={})=>this.find(W.from,{...Q,[J]:Y.id}),update:(Q,M)=>this.update(W.from,Q,M),upsert:(Q={},M={})=>this.upsert(W.from,{...M,[J]:Y.id},{...Q,[J]:Y.id}),delete:(Q)=>{if(Q)this.delete(W.from,Q);else this.find(W.from,{[J]:Y.id}).forEach((B)=>this.delete(W.from,B.id))},subscribe:(Q,M)=>this.subscribe(Q,W.from,M),unsubscribe:(Q,M)=>this.unsubscribe(Q,W.from,M),push:(Q)=>this.insert(W.from,{...Q,[J]:Y.id})})})}return $}initializeTables(){for(let[$,W]of Object.entries(this.schemas)){let _=this.getStorableFields(W),H=new Set(_.map((Q)=>Q.name)),G=_.map((Q)=>`${Q.name} ${this.zodTypeToSqlType(Q.type)}`),X=[],J=this.relationships.filter((Q)=>Q.type==="belongs-to"&&Q.from===$);for(let Q of J){if(!H.has(Q.foreignKey))G.push(`${Q.foreignKey} INTEGER`);X.push(`FOREIGN KEY (${Q.foreignKey}) REFERENCES ${Q.to}(id) ON DELETE SET NULL`)}let Y=`CREATE TABLE IF NOT EXISTS ${$} (id INTEGER PRIMARY KEY AUTOINCREMENT, ${G.join(", ")}${X.length>0?", "+X.join(", "):""})`;this.db.run(Y)}}runMigrations(){this.db.run(`CREATE TABLE IF NOT EXISTS _sati_meta (
3
- id INTEGER PRIMARY KEY AUTOINCREMENT,
4
- table_name TEXT NOT NULL,
5
- column_name TEXT NOT NULL,
6
- added_at TEXT DEFAULT (datetime('now')),
7
- UNIQUE(table_name, column_name)
8
- )`);for(let[$,W]of Object.entries(this.schemas)){let _=new Set(this.db.query(`PRAGMA table_info(${$})`).all().map((J)=>J.name)),H=this.getStorableFields(W),X=this.relationships.filter((J)=>J.type==="belongs-to"&&J.from===$).map((J)=>J.foreignKey);for(let J of H)if(!_.has(J.name)){let Y=this.zodTypeToSqlType(J.type);this.db.run(`ALTER TABLE ${$} ADD COLUMN ${J.name} ${Y}`),this.db.query("INSERT OR IGNORE INTO _sati_meta (table_name, column_name) VALUES (?, ?)").run($,J.name)}for(let J of X)if(!_.has(J))this.db.run(`ALTER TABLE ${$} ADD COLUMN ${J} INTEGER`),this.db.query("INSERT OR IGNORE INTO _sati_meta (table_name, column_name) VALUES (?, ?)").run($,J)}}createIndexes($){for(let[W,_]of Object.entries($)){if(!this.schemas[W])throw Error(`Cannot create index on unknown table '${W}'`);for(let H of _){let G=Array.isArray(H)?H:[H],X=`idx_${W}_${G.join("_")}`,J=G.join(", ");this.db.run(`CREATE INDEX IF NOT EXISTS ${X} ON ${W} (${J})`)}}}setupChangeTracking(){this.db.run(`CREATE TABLE IF NOT EXISTS _sati_changes (
9
- id INTEGER PRIMARY KEY AUTOINCREMENT,
10
- table_name TEXT NOT NULL,
11
- row_id INTEGER NOT NULL,
12
- action TEXT NOT NULL CHECK(action IN ('INSERT', 'UPDATE', 'DELETE')),
13
- changed_at TEXT DEFAULT (datetime('now'))
14
- )`),this.db.run("CREATE INDEX IF NOT EXISTS idx_sati_changes_table ON _sati_changes (table_name, id)");for(let $ of Object.keys(this.schemas))this.db.run(`CREATE TRIGGER IF NOT EXISTS _sati_trg_${$}_insert
15
- AFTER INSERT ON ${$}
16
- BEGIN
17
- INSERT INTO _sati_changes (table_name, row_id, action) VALUES ('${$}', NEW.id, 'INSERT');
18
- END`),this.db.run(`CREATE TRIGGER IF NOT EXISTS _sati_trg_${$}_update
19
- AFTER UPDATE ON ${$}
20
- BEGIN
21
- INSERT INTO _sati_changes (table_name, row_id, action) VALUES ('${$}', NEW.id, 'UPDATE');
22
- END`),this.db.run(`CREATE TRIGGER IF NOT EXISTS _sati_trg_${$}_delete
23
- AFTER DELETE ON ${$}
24
- BEGIN
25
- INSERT INTO _sati_changes (table_name, row_id, action) VALUES ('${$}', OLD.id, 'DELETE');
26
- END`)}getChangeSeq($){if(!this.options.changeTracking)return-1;let W=$?"SELECT MAX(id) as seq FROM _sati_changes WHERE table_name = ?":"SELECT MAX(id) as seq FROM _sati_changes",_=$?[$]:[];return this.db.query(W).get(..._)?.seq??0}getChangesSince($,W){let _=W?"SELECT * FROM _sati_changes WHERE id > ? AND table_name = ? ORDER BY id ASC":"SELECT * FROM _sati_changes WHERE id > ? ORDER BY id ASC",H=W?[$,W]:[$];return this.db.query(_).all(...H)}isRelationshipField($,W){let _=X$($).shape[W];if(_ instanceof v.ZodOptional)_=_._def.innerType;return _ instanceof v.ZodLazy}getStorableFields($){return Object.entries(X$($).shape).filter(([W])=>W!=="id"&&!this.isRelationshipField($,W)).map(([W,_])=>({name:W,type:_}))}zodTypeToSqlType($){if($ instanceof v.ZodOptional)$=$._def.innerType;if($ instanceof v.ZodDefault)$=$._def.innerType;if($ instanceof v.ZodString||$ instanceof v.ZodDate)return"TEXT";if($ instanceof v.ZodNumber||$ instanceof v.ZodBoolean)return"INTEGER";if($._def.typeName==="ZodInstanceOf"&&$._def.type===Buffer)return"BLOB";return"TEXT"}transformForStorage($){let W={};for(let[_,H]of Object.entries($))if(H instanceof Date)W[_]=H.toISOString();else if(typeof H==="boolean")W[_]=H?1:0;else W[_]=H;return W}transformFromStorage($,W){let _={};for(let[H,G]of Object.entries($)){let X=X$(W).shape[H];if(X instanceof v.ZodOptional)X=X._def.innerType;if(X instanceof v.ZodDefault)X=X._def.innerType;if(X instanceof v.ZodDate&&typeof G==="string")_[H]=new Date(G);else if(X instanceof v.ZodBoolean&&typeof G==="number")_[H]=G===1;else _[H]=G}return _}_attachMethods($,W,_){let H=W;H.update=(Y)=>this.update($,W.id,Y),H.delete=()=>this.delete($,W.id);let G=this.lazyMethods[$]||[];for(let Y of G)if(_&&_[Y.name]!==void 0){if(Y.type==="belongs-to"){let Q=_[Y.name];H[Y.name]=()=>Q}else if(Y.type==="one-to-many"){let Q=_[Y.name]||[],M=this.relationships.find((z)=>z.type==="belongs-to"&&z.from===Y.childEntityName&&z.to===Y.parentEntityName);if(!M)throw Error(`No 'belongs-to' relationship found for one-to-many from ${Y.parentEntityName} to ${Y.childEntityName}`);let B=M.foreignKey;H[Y.name]={insert:(z)=>this.insert(Y.childEntityName,{...z,[B]:W.id}),get:(z)=>{let A=typeof z==="number"?{id:z}:z;return this.get(Y.childEntityName,{...A,[B]:W.id})},findOne:(z={})=>{return this.findOne(Y.childEntityName,{...z,[B]:W.id})},find:(z={})=>{if(Object.keys(z).length===0)return Q;return this.find(Y.childEntityName,{...z,[B]:W.id})},update:(z,A)=>this.update(Y.childEntityName,z,A),upsert:(z={},A={})=>this.upsert(Y.childEntityName,{...A,[B]:W.id},{...z,[B]:W.id}),delete:(z)=>{if(z)this.delete(Y.childEntityName,z);else this.find(Y.childEntityName,{[B]:W.id}).forEach((q)=>this.delete(Y.childEntityName,q.id))},subscribe:(z,A)=>this.subscribe(z,Y.childEntityName,A),unsubscribe:(z,A)=>this.unsubscribe(z,Y.childEntityName,A),push:(z)=>this.insert(Y.childEntityName,{...z,[B]:W.id})}}}else{let Q=Y.fetch(W);if(Y.type==="one-to-many")H[Y.name]=Q;else H[Y.name]=Q}let X=new Set(this.getStorableFields(this.schemas[$]).map((Y)=>Y.name));return new Proxy(H,{set:(Y,Q,M)=>{if(X.has(Q)&&Y[Q]!==M)this.update($,Y.id,{[Q]:M});return Y[Q]=M,!0},get:(Y,Q,M)=>Reflect.get(Y,Q,M)})}buildWhereClause($,W){let _=[],H=[];for(let G in $){if(G.startsWith("$"))continue;let X=$[G],J=W?`${W}.${G}`:G;if(typeof X==="object"&&X!==null&&!Array.isArray(X)&&!(X instanceof Date)){let Y=Object.keys(X)[0];if(!Y||!Y.startsWith("$"))throw Error(`Querying on nested object field '${G}' is not supported. Use simple values or query operators like $gt.`);let Q=X[Y],M="";switch(Y){case"$gt":M=">";break;case"$gte":M=">=";break;case"$lt":M="<";break;case"$lte":M="<=";break;case"$ne":M="!=";break;case"$in":if(!Array.isArray(Q))throw Error(`$in operator for field '${G}' requires an array value.`);if(Q.length===0)_.push("1 = 0");else{let B=Q.map(()=>"?").join(", ");_.push(`${J} IN (${B})`),H.push(...Q.map((z)=>this.transformForStorage({v:z}).v))}continue;default:throw Error(`Unsupported query operator: '${Y}' on field '${G}'.`)}_.push(`${J} ${M} ?`),H.push(this.transformForStorage({operand:Q}).operand)}else _.push(`${J} = ?`),H.push(this.transformForStorage({value:X}).value)}return{clause:_.length>0?`WHERE ${_.join(" AND ")}`:"",values:H}}buildJoinQuery($,W,_){let{$limit:H,$offset:G,$sortBy:X,$include:J,...Y}=W,Q=`SELECT ${$}.*`,M=[],B=[];for(let q of _){let K=this.relationships.find((D)=>D.from===$&&D.relationshipField===q&&D.type==="belongs-to");if(K){let D=`${q}_tbl`;M.push({alias:D,entityName:K.to,relationship:K});let I=this.schemas[K.to],N=["id",...this.getStorableFields(I).map((J$)=>J$.name)].map((J$)=>`${D}.${J$} AS ${D}_${J$}`);Q+=`, ${N.join(", ")}`,B.push(`LEFT JOIN ${K.to} ${D} ON ${$}.${K.foreignKey} = ${D}.id`)}}if(Q+=` FROM ${$}`,B.length>0)Q+=` ${B.join(" ")}`;let{clause:z,values:A}=this.buildWhereClause(Y,$);if(z)Q+=` ${z}`;if(X){let[q,K="ASC"]=X.split(":");Q+=` ORDER BY ${$}.${q} ${K.toUpperCase()==="DESC"?"DESC":"ASC"}`}if(H)Q+=` LIMIT ${H}`;if(G)Q+=` OFFSET ${G}`;return{sql:Q,values:A,joinedTables:M}}parseJoinResults($,W,_){let H=[],G=[];for(let X of $){let J={},Y=this.schemas[W],Q=["id",...this.getStorableFields(Y).map((B)=>B.name)];for(let B of Q)if(X[B]!==void 0)J[B]=X[B];let M={};for(let{alias:B,entityName:z,relationship:A}of _){let q={},K=this.schemas[z],D=["id",...this.getStorableFields(K).map((P)=>P.name)],I=!1;for(let P of D){let N=`${B}_${P}`;if(X[N]!==void 0&&X[N]!==null)q[P]=X[N],I=!0}if(I){let P=this.transformFromStorage(q,K),N=this._attachMethods(z,P);M[A.relationshipField]=N}}H.push(this.transformFromStorage(J,Y)),G.push(M)}return{entities:H,includedData:G}}loadOneToManyIncludes($,W,_){let H=W.map(()=>({}));for(let G of _){let X=this.relationships.find((J)=>J.from===$&&J.relationshipField===G&&J.type==="one-to-many");if(X){let J=W.map((q)=>q.id);if(J.length===0)continue;let Y=this.relationships.find((q)=>q.type==="belongs-to"&&q.from===X.to&&q.to===X.from);if(!Y)throw Error(`No 'belongs-to' relationship found for one-to-many from ${X.from} to ${X.to}`);let Q=Y.foreignKey,M=J.map(()=>"?").join(", "),B=`SELECT * FROM ${X.to} WHERE ${Q} IN (${M})`,z=this.db.query(B).all(...J),A={};for(let q of z){let K=q[Q];if(!A[K])A[K]=[];let D=this.transformFromStorage(q,this.schemas[X.to]),I=this._attachMethods(X.to,D);A[K].push(I)}W.forEach((q,K)=>{H[K][G]=A[q.id]||[]})}}return H}transaction($){try{this.db.run("BEGIN TRANSACTION");let W=$();return this.db.run("COMMIT"),W}catch(W){throw this.db.run("ROLLBACK"),Error(`Transaction failed: ${W.message}`)}}preprocessRelationshipFields($,W){let _={...W};for(let[H,G]of Object.entries(W))if(this.isRelationshipField($,H)){if(G&&typeof G==="object"&&"id"in G){let X=`${H}Id`;_[X]=G.id,delete _[H]}else if(typeof G==="string"){let X=`${H}Id`;_[X]=G,delete _[H]}}return _}insert($,W){let _=this.schemas[$],H=this.preprocessRelationshipFields(_,W),G=X$(_).passthrough().parse(H),X=Object.fromEntries(Object.entries(G).filter(([z])=>!this.isRelationshipField(_,z))),J=this.transformForStorage(X),Y=Object.keys(J),Q;if(Y.length===0)Q=`INSERT INTO ${$} DEFAULT VALUES`;else{let z=Y.map(()=>"?").join(", ");Q=`INSERT INTO ${$} (${Y.join(", ")}) VALUES (${z})`}let M=this.db.query(Q).run(...Object.values(J)),B=this.get($,M.lastInsertRowid);if(!B)throw Error("Failed to retrieve entity after insertion");if(this.emit("insert",$,B),this.subscriptions.insert[$])this.subscriptions.insert[$].forEach((z)=>z(B));return B}get($,W){let _=typeof W==="number"?{id:W}:W;if(Object.keys(_).length===0)return null;let H=this.find($,{..._,$limit:1});return H.length>0?H[0]:null}findMany($,W){let{where:_={},orderBy:H,take:G}=W,X={..._};if(H){let J=Object.keys(H)[0],Y=H[J];X.$sortBy=`${J}:${Y}`}if(G)X.$limit=G;return this.find($,X)}findUnique($,W){let{where:_}=W,H={..._,$limit:1},G=this.find($,H);return G.length>0?G[0]:null}findOne($,W){let _=this.find($,{...W,$limit:1});return _.length>0?_[0]:null}find($,W={}){let{$include:_,...H}=W,G=[];if(_){if(typeof _==="string")G.push(_);else if(Array.isArray(_))G.push(..._)}if(G.length===0){let{$limit:M,$offset:B,$sortBy:z,...A}=H,{clause:q,values:K}=this.buildWhereClause(A),D="";if(z){let[e,K$="ASC"]=z.split(":");D=`ORDER BY ${e} ${K$.toUpperCase()==="DESC"?"DESC":"ASC"}`}let I=M?`LIMIT ${M}`:"",P=B?`OFFSET ${B}`:"",N=`SELECT * FROM ${$} ${q} ${D} ${I} ${P}`;return this.db.query(N).all(...K).map((e)=>{let K$=this.transformFromStorage(e,this.schemas[$]);return this._attachMethods($,K$)})}let X=G.filter((M)=>{return this.relationships.find((z)=>z.from===$&&z.relationshipField===M)?.type==="belongs-to"}),J=G.filter((M)=>{return this.relationships.find((z)=>z.from===$&&z.relationshipField===M)?.type==="one-to-many"}),Y,Q;if(X.length>0){let{sql:M,values:B,joinedTables:z}=this.buildJoinQuery($,H,X),A=this.db.query(M).all(...B),q=this.parseJoinResults(A,$,z);Y=q.entities,Q=q.includedData}else{let{$limit:M,$offset:B,$sortBy:z,...A}=H,{clause:q,values:K}=this.buildWhereClause(A),D="";if(z){let[e,K$="ASC"]=z.split(":");D=`ORDER BY ${e} ${K$.toUpperCase()==="DESC"?"DESC":"ASC"}`}let I=M?`LIMIT ${M}`:"",P=B?`OFFSET ${B}`:"",N=`SELECT * FROM ${$} ${q} ${D} ${I} ${P}`;Y=this.db.query(N).all(...K).map((e)=>this.transformFromStorage(e,this.schemas[$])),Q=Y.map(()=>({}))}if(J.length>0){let M=this.loadOneToManyIncludes($,Y,J);Q=Q.map((B,z)=>({...B,...M[z]}))}return Y.map((M,B)=>{return this._attachMethods($,M,Q[B])})}update($,W,_){let H=this.schemas[$],G=X$(H).partial().parse(_),X=this.transformForStorage(G);if(Object.keys(X).length===0)return this.get($,{id:W});let J=Object.keys(X).map((B)=>`${B} = ?`).join(", "),Y=[...Object.values(X),W],Q=`UPDATE ${$} SET ${J} WHERE id = ?`;this.db.query(Q).run(...Y);let M=this.get($,{id:W});if(M){if(this.emit("update",$,M),this.subscriptions.update[$])this.subscriptions.update[$].forEach((B)=>B(M))}return M}updateWithFilter($,W,_){if(typeof W==="number")return this.update($,W,_);let H=this.findOne($,W);if(!H)return null;return this.update($,H.id,_)}_updateWhere($,W,_){let H=this.schemas[$],G=X$(H).partial().parse(W),X=this.transformForStorage(G);if(Object.keys(X).length===0)return 0;let{clause:J,values:Y}=this.buildWhereClause(_);if(!J)throw Error("update().where() requires at least one condition");let Q=Object.keys(X),M=Q.map((K)=>`${K} = ?`).join(", "),B=Q.map((K)=>X[K]),z=`UPDATE ${$} SET ${M} ${J}`,q=this.db.query(z).run(...B,...Y).changes??0;if(q>0&&(this.subscriptions.update[$]?.length||this.options.changeTracking)){let K=this.find($,_);for(let D of K)if(this.emit("update",$,D),this.subscriptions.update[$])this.subscriptions.update[$].forEach((I)=>I(D))}return q}_createUpdateBuilder($,W){let _={},H={where:(G)=>{return _={..._,...G},H},exec:()=>{return this._updateWhere($,W,_)}};return H}upsert($,W,_={}){let H=this.schemas[$],G=this.preprocessRelationshipFields(H,W),X=this.preprocessRelationshipFields(H,_),Y=G.id&&typeof G.id==="number"?this.get($,{id:G.id}):Object.keys(X).length>0?this.get($,X):null;if(Y){let Q={...G};return delete Q.id,this.update($,Y.id,Q)}else{let Q={...X,...G};return delete Q.id,this.insert($,Q)}}delete($,W){let _=this.get($,{id:W});if(_){let H=`DELETE FROM ${$} WHERE id = ?`;if(this.db.query(H).run(W),this.emit("delete",$,_),this.subscriptions.delete[$])this.subscriptions.delete[$].forEach((G)=>G(_))}}subscribe($,W,_){this.subscriptions[$][W]=this.subscriptions[$][W]||[],this.subscriptions[$][W].push(_)}unsubscribe($,W,_){if(this.subscriptions[$][W])this.subscriptions[$][W]=this.subscriptions[$][W].filter((H)=>H!==_)}_createQueryBuilder($,W){let _=this.schemas[$],H=(J,Y,Q)=>{let M=this.db.query(J).all(...Y);if(Q)return M;return M.map((B)=>{let z=this.transformFromStorage(B,_);return this._attachMethods($,z)})},X=new T$($,H,(J,Y,Q)=>{let M=H(J,Y,Q);return M.length>0?M[0]:null});if(W.length>0)X.select(...W);return X}query($){return _W(this.schemas,$,(W,_)=>{return this.db.query(W).all(..._)})}}var X3=GW;export{v as z,F as wrapNode,l$ as op,u$ as createFunctionProxy,y$ as createColumnProxy,d as compileAST,X3 as SatiDB,T$ as QueryBuilder,x$ as ColumnNode};
package/src/build.ts DELETED
@@ -1,21 +0,0 @@
1
- import { EOL } from 'os';
2
-
3
- console.log("Building sqlite-zod-orm...");
4
-
5
- const result = await Bun.build({
6
- entrypoints: ['./src/index.ts'],
7
- outdir: './dist',
8
- target: 'bun',
9
- format: 'esm',
10
- minify: false,
11
- });
12
-
13
- if (!result.success) {
14
- console.error("Build failed:");
15
- for (const msg of result.logs) {
16
- console.error(msg);
17
- }
18
- process.exit(1);
19
- }
20
-
21
- console.log(`Build complete → dist/ (${result.outputs.length} file${result.outputs.length > 1 ? 's' : ''})${EOL}`);
@@ -1,312 +0,0 @@
1
- /**
2
- * proxy-query.ts — Proxy-based SQL query builder
3
- *
4
- * Enables db.query(c => { const { users: u, posts: p } = c; ... }) syntax.
5
- * Table/column access through the proxy creates ColumnNode AST nodes,
6
- * which are then compiled into parameterized SQL.
7
- */
8
-
9
- import { z } from 'zod';
10
-
11
- // ---------- Column Node ----------
12
-
13
- /**
14
- * Represents a reference to a specific table column with an alias.
15
- * Used as a building block for SQL query construction.
16
- */
17
- export class ColumnNode {
18
- readonly _type = 'COL' as const;
19
- constructor(
20
- readonly table: string,
21
- readonly column: string,
22
- readonly alias: string,
23
- ) { }
24
-
25
- /** Quoted alias.column for use as computed property key */
26
- toString(): string {
27
- return `"${this.alias}"."${this.column}"`;
28
- }
29
-
30
- [Symbol.toPrimitive](): string {
31
- return this.toString();
32
- }
33
- }
34
-
35
- // ---------- SQL Quoting Helpers ----------
36
-
37
- /** Quote an identifier with double quotes */
38
- function q(name: string): string {
39
- return `"${name}"`;
40
- }
41
-
42
- /** Quote a fully qualified reference: alias.column */
43
- function qRef(alias: string, column: string): string {
44
- return `"${alias}"."${column}"`;
45
- }
46
-
47
- // ---------- Table Proxy ----------
48
-
49
- /**
50
- * Creates a proxy representing a table with a given alias.
51
- * Property access returns ColumnNode objects.
52
- */
53
- function createTableProxy(
54
- tableName: string,
55
- alias: string,
56
- columns: Set<string>,
57
- ): Record<string, ColumnNode> {
58
- return new Proxy({} as Record<string, ColumnNode>, {
59
- get(_target, prop: string): ColumnNode | undefined {
60
- if (prop === Symbol.toPrimitive as any || prop === 'toString' || prop === 'valueOf') {
61
- return undefined;
62
- }
63
- return new ColumnNode(tableName, prop, alias);
64
- },
65
- ownKeys() {
66
- return [...columns];
67
- },
68
- getOwnPropertyDescriptor(_target, prop) {
69
- if (columns.has(prop as string)) {
70
- return { configurable: true, enumerable: true, value: new ColumnNode(tableName, prop as string, alias) };
71
- }
72
- return undefined;
73
- },
74
- });
75
- }
76
-
77
- // ---------- Context Proxy ----------
78
-
79
- interface AliasEntry {
80
- tableName: string;
81
- alias: string;
82
- proxy: Record<string, ColumnNode>;
83
- }
84
-
85
- /**
86
- * Creates the root context proxy `c` that the user destructures.
87
- * Each table access generates a unique alias.
88
- */
89
- export function createContextProxy(
90
- schemas: Record<string, z.ZodType<any>>,
91
- ): { proxy: Record<string, Record<string, ColumnNode>>; aliasMap: Map<string, AliasEntry[]> } {
92
- const aliases = new Map<string, AliasEntry[]>();
93
- let aliasCounter = 0;
94
-
95
- const proxy = new Proxy({} as Record<string, Record<string, ColumnNode>>, {
96
- get(_target, tableName: string) {
97
- if (typeof tableName !== 'string') return undefined;
98
-
99
- const schema = schemas[tableName];
100
- const shape = schema
101
- ? (schema as unknown as z.ZodObject<any>).shape
102
- : {};
103
- const columns = new Set(Object.keys(shape));
104
-
105
- aliasCounter++;
106
- const alias = `t${aliasCounter}`;
107
- const tableProxy = createTableProxy(tableName, alias, columns);
108
-
109
- // Track alias
110
- const entries = aliases.get(tableName) || [];
111
- entries.push({ tableName, alias, proxy: tableProxy });
112
- aliases.set(tableName, entries);
113
-
114
- return tableProxy;
115
- },
116
- });
117
-
118
- return { proxy, aliasMap: aliases };
119
- }
120
-
121
- // ---------- Query Result Shape ----------
122
-
123
- type AnyColumn = ColumnNode | (ColumnNode & string);
124
-
125
- export interface ProxyQueryResult {
126
- select: Record<string, AnyColumn | undefined>;
127
- join?: [AnyColumn | undefined, AnyColumn | undefined] | [AnyColumn | undefined, AnyColumn | undefined][];
128
- where?: Record<string, any>;
129
- orderBy?: Record<string, 'asc' | 'desc'>;
130
- limit?: number;
131
- offset?: number;
132
- groupBy?: (AnyColumn | undefined)[];
133
- }
134
-
135
- // ---------- Query Compiler ----------
136
-
137
- function isColumnNode(val: any): val is ColumnNode {
138
- return val && typeof val === 'object' && val._type === 'COL';
139
- }
140
-
141
- /**
142
- * Compile the result of the user's callback into SQL.
143
- */
144
- export function compileProxyQuery(
145
- queryResult: ProxyQueryResult,
146
- aliasMap: Map<string, AliasEntry[]>,
147
- ): { sql: string; params: any[] } {
148
- const params: any[] = [];
149
-
150
- // Collect all tables/aliases referenced
151
- const tablesUsed = new Map<string, { tableName: string; alias: string }>();
152
-
153
- for (const [tableName, entries] of aliasMap) {
154
- for (const entry of entries) {
155
- tablesUsed.set(entry.alias, { tableName, alias: entry.alias });
156
- }
157
- }
158
-
159
- // ---------- SELECT ----------
160
- const selectParts: string[] = [];
161
- for (const [outputName, colOrValue] of Object.entries(queryResult.select)) {
162
- if (isColumnNode(colOrValue)) {
163
- if (outputName === colOrValue.column) {
164
- selectParts.push(qRef(colOrValue.alias, colOrValue.column));
165
- } else {
166
- selectParts.push(`${qRef(colOrValue.alias, colOrValue.column)} AS ${q(outputName)}`);
167
- }
168
- } else {
169
- // Literal value
170
- selectParts.push(`? AS ${q(outputName)}`);
171
- params.push(colOrValue);
172
- }
173
- }
174
-
175
- // ---------- FROM / JOIN ----------
176
- const allAliases = [...tablesUsed.values()];
177
- if (allAliases.length === 0) throw new Error('No tables referenced in query.');
178
-
179
- const primaryAlias = allAliases[0]!;
180
- let sql = `SELECT ${selectParts.join(', ')} FROM ${q(primaryAlias.tableName)} ${q(primaryAlias.alias)}`;
181
-
182
- // Process JOINs
183
- if (queryResult.join) {
184
- const joins: [ColumnNode, ColumnNode][] = Array.isArray(queryResult.join[0])
185
- ? queryResult.join as [ColumnNode, ColumnNode][]
186
- : [queryResult.join as [ColumnNode, ColumnNode]];
187
-
188
- for (const [left, right] of joins) {
189
- const leftTable = tablesUsed.get(left.alias);
190
- const rightTable = tablesUsed.get(right.alias);
191
-
192
- if (!leftTable || !rightTable) throw new Error('Join references unknown table alias.');
193
-
194
- const joinAlias = leftTable.alias === primaryAlias.alias ? rightTable : leftTable;
195
-
196
- sql += ` JOIN ${q(joinAlias.tableName)} ${q(joinAlias.alias)} ON ${qRef(left.alias, left.column)} = ${qRef(right.alias, right.column)}`;
197
- }
198
- }
199
-
200
- // ---------- WHERE ----------
201
- if (queryResult.where && Object.keys(queryResult.where).length > 0) {
202
- const whereParts: string[] = [];
203
-
204
- for (const [key, value] of Object.entries(queryResult.where)) {
205
- let fieldRef: string;
206
-
207
- // Match quoted alias.column pattern: "alias"."column"
208
- const quotedMatch = key.match(/^"([^"]+)"\."([^"]+)"$/);
209
- if (quotedMatch && tablesUsed.has(quotedMatch[1]!)) {
210
- fieldRef = key;
211
- } else {
212
- fieldRef = qRef(primaryAlias.alias, key);
213
- }
214
-
215
- if (isColumnNode(value)) {
216
- whereParts.push(`${fieldRef} = ${qRef(value.alias, value.column)}`);
217
- } else if (Array.isArray(value)) {
218
- if (value.length === 0) {
219
- whereParts.push('1 = 0');
220
- } else {
221
- const placeholders = value.map(() => '?').join(', ');
222
- whereParts.push(`${fieldRef} IN (${placeholders})`);
223
- params.push(...value);
224
- }
225
- } else if (typeof value === 'object' && value !== null && !(value instanceof Date)) {
226
- for (const [op, operand] of Object.entries(value)) {
227
- if (op === '$in') {
228
- const arr = operand as any[];
229
- if (arr.length === 0) {
230
- whereParts.push('1 = 0');
231
- } else {
232
- const placeholders = arr.map(() => '?').join(', ');
233
- whereParts.push(`${fieldRef} IN (${placeholders})`);
234
- params.push(...arr);
235
- }
236
- continue;
237
- }
238
- const opMap: Record<string, string> = {
239
- $gt: '>', $gte: '>=', $lt: '<', $lte: '<=', $ne: '!=',
240
- };
241
- const sqlOp = opMap[op];
242
- if (!sqlOp) throw new Error(`Unsupported where operator: ${op}`);
243
- whereParts.push(`${fieldRef} ${sqlOp} ?`);
244
- params.push(operand);
245
- }
246
- } else {
247
- whereParts.push(`${fieldRef} = ?`);
248
- params.push(value instanceof Date ? value.toISOString() : value);
249
- }
250
- }
251
-
252
- if (whereParts.length > 0) {
253
- sql += ` WHERE ${whereParts.join(' AND ')}`;
254
- }
255
- }
256
-
257
- // ---------- ORDER BY ----------
258
- if (queryResult.orderBy) {
259
- const parts: string[] = [];
260
- for (const [key, dir] of Object.entries(queryResult.orderBy)) {
261
- let fieldRef: string;
262
- const quotedMatch = key.match(/^"([^"]+)"\."([^"]+)"$/);
263
- if (quotedMatch && tablesUsed.has(quotedMatch[1]!)) {
264
- fieldRef = key;
265
- } else {
266
- fieldRef = qRef(primaryAlias.alias, key);
267
- }
268
- parts.push(`${fieldRef} ${dir.toUpperCase()}`);
269
- }
270
- if (parts.length > 0) {
271
- sql += ` ORDER BY ${parts.join(', ')}`;
272
- }
273
- }
274
-
275
- // ---------- GROUP BY ----------
276
- if (queryResult.groupBy && queryResult.groupBy.length > 0) {
277
- const parts = queryResult.groupBy.filter(Boolean).map(col => qRef(col!.alias, col!.column));
278
- sql += ` GROUP BY ${parts.join(', ')}`;
279
- }
280
-
281
- // ---------- LIMIT / OFFSET ----------
282
- if (queryResult.limit !== undefined) {
283
- sql += ` LIMIT ${queryResult.limit}`;
284
- }
285
- if (queryResult.offset !== undefined) {
286
- sql += ` OFFSET ${queryResult.offset}`;
287
- }
288
-
289
- return { sql, params };
290
- }
291
-
292
- // ---------- Public API ----------
293
-
294
- /**
295
- * The main `db.query(c => {...})` entry point.
296
- *
297
- * @param schemas The schema map for all registered tables.
298
- * @param callback The user's query callback that receives the context proxy.
299
- * @param executor A function that runs the compiled SQL and returns rows.
300
- * @returns The query results.
301
- */
302
- export function executeProxyQuery<T>(
303
- schemas: Record<string, z.ZodType<any>>,
304
- callback: (ctx: any) => ProxyQueryResult,
305
- executor: (sql: string, params: any[]) => T[],
306
- ): T[] {
307
- const { proxy, aliasMap } = createContextProxy(schemas);
308
- const queryResult = callback(proxy);
309
- const { sql, params } = compileProxyQuery(queryResult, aliasMap);
310
- return executor(sql, params);
311
- }
312
-