@live-state/sync 0.0.7-canary-3 → 0.0.7-canary-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,12 +1,12 @@
1
- import {a,b,B as B$1,z as z$2,C as C$1,D as D$1,G as G$1,F as F$1,E}from'./chunk-3XEJ2M4E.js';import H from'crypto';import Tt,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect,sql}from'kysely';import {jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from'kysely/helpers/mysql';import {jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from'kysely/helpers/postgres';import {jsonArrayFrom,jsonObjectFrom}from'kysely/helpers/sqlite';var oe=a(Y=>{Object.defineProperty(Y,"__esModule",{value:true});Y.parse=yt;Y.serialize=ht;var at=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ot=/^[\u0021-\u003A\u003C-\u007E]*$/,ct=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ut=/^[\u0020-\u003A\u003D-\u007E]*$/,dt=Object.prototype.toString,lt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function yt(c,e){let t=new lt,r=c.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||pt,s=0;do{let o=c.indexOf("=",s);if(o===-1)break;let a=c.indexOf(";",s),i=a===-1?r:a;if(o>i){s=c.lastIndexOf(";",o-1)+1;continue}let u=Ee(c,s,o),l=Pe(c,o,u),d=c.slice(u,l);if(t[d]===void 0){let h=Ee(c,o+1,i),y=Pe(c,i,h),m=n(c.slice(h,y));t[d]=m;}s=i+1;}while(s<r);return t}function Ee(c,e,t){do{let r=c.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Pe(c,e,t){for(;e>t;){let r=c.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function ht(c,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!at.test(c))throw new TypeError(`argument name is invalid: ${c}`);let n=r(e);if(!ot.test(n))throw new TypeError(`argument val is invalid: ${e}`);let s=c+"="+n;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge;}if(t.domain){if(!ct.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!ut.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!mt(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":s+="; Priority=Low";break;case "medium":s+="; Priority=Medium";break;case "high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":s+="; SameSite=Strict";break;case "lax":s+="; SameSite=Lax";break;case "none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}function pt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function mt(c){return dt.call(c)==="[object Date]"}});var je="0123456789ABCDEFGHJKMNPQRSTVWXYZ",V=32;var Xe=16,Oe=10,Me=0xffffffffffff;var N;(function(c){c.Base32IncorrectEncoding="B32_ENC_INVALID",c.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",c.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",c.EncodeTimeNegative="ENC_TIME_NEG",c.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",c.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",c.PRNGDetectFailure="PRNG_DETECT",c.ULIDInvalid="ULID_INVALID",c.Unexpected="UNEXPECTED",c.UUIDInvalid="UUID_INVALID";})(N||(N={}));var q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function et(c){let e=Math.floor(c()*V);return e===V&&(e=V-1),je.charAt(e)}function tt(c){var r;let e=rt(),t=e&&(e.crypto||e.msCrypto)||(typeof H<"u"?H:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=H)!=null&&r.randomBytes)return ()=>H.randomBytes(1).readUInt8()/255;throw new q(N.PRNGDetectFailure,"Failed to find a reliable PRNG")}function rt(){return st()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function nt(c,e){let t="";for(;c>0;c--)t=et(e)+t;return t}function it(c,e=Oe){if(isNaN(c))throw new q(N.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>Me)throw new q(N.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Me}: ${c}`);if(c<0)throw new q(N.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new q(N.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,r="";for(let n=e;n>0;n--)t=c%V,r=je.charAt(t)+r,c=(c-t)/V;return r}function st(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ae(c,e){let t=tt(),r=Date.now();return it(r,Oe)+nt(Xe,t)}var J=()=>Ae().toLowerCase(),K=c=>({then(e,t){try{if(e){let r=e(c);return r instanceof Promise?r:K(r)}return K(c)}catch(r){if(t){let n=t(r);return n instanceof Promise?n:K(n)}throw r}}}),se=c=>c instanceof Promise?c:K(c);var D=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var G=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...n}){return new Promise((s,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...n}),i={resource:e,commonWhere:t,uniqueWhere:r,...n,resolve:s,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(i),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...n}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(r){t.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:n,include:s,sort:o}=t,a=e.length===1?t.limit:void 0,i=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),u=n,l=(h=Object.entries(i[0]??{})[0])==null?void 0:h[0];if(i.length>0){let y=i.map(m=>m[l]).filter(m=>m!=null);y.length>0&&(u=D(n,{[l]:{$in:y}}));}let d=await this.storage.get({resource:r,where:u,include:s,sort:o,limit:a});for(let y of e){let m=d;if(y.uniqueWhere){let[p,f]=Object.entries(y.uniqueWhere)[0];m=d.filter(T=>{var g;return ((g=T.value[p])==null?void 0:g.value)===f});}y.resolve(m);}}};function ae(c){return B$1({resource:c.query.resource,where:c.query.where,include:c.query.include,stepPath:c.stepPath,isMany:c.isMany,relationName:c.relationName})}var Z=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,r=this.schema[e];if(!(r!=null&&r.relations))return t;for(let[n,s]of Object.entries(r.relations))s.type==="one"&&s.relationalColumn&&t.set(String(s.relationalColumn),{relationName:n,targetResource:s.entity.name});return t}ensureObjectNode(e,t,r){let n=this.objectNodes.get(e);return n?r&&n.matchedQueries.add(r):(n={id:e,type:t,matchedQueries:new Set(r?[r]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,n)),n}storeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.set(r,t),o&&n){let a=o.referencedByObjects.get(n);a||(a=new Set,o.referencedByObjects.set(n,a)),a.add(e);}}removeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.delete(r),o&&n){let a=o.referencedByObjects.get(n);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(n));}}getInverseRelationName(e,t,r){let n=this.schema[e];if(!(n!=null&&n.relations))return;let s=n.relations[r];if(!s)return;let o=this.schema[t];if(o!=null&&o.relations){if(s.type==="many"&&s.foreignColumn){for(let[a,i]of Object.entries(o.relations))if(i.entity.name===e&&i.type==="one"&&i.relationalColumn===s.foreignColumn)return a}if(s.type==="one"&&s.relationalColumn){for(let[a,i]of Object.entries(o.relations))if(i.entity.name===e&&i.type==="many"&&i.foreignColumn===s.relationalColumn)return a}}}updateRelationsFromMutation(e,t,r,n){let s=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){if(!(n&&a in n))continue;let d=this.getInverseRelationName(e,u,i),h=o.referencesObjects.get(i),y=r[a];h!==y&&(h&&this.removeRelation(t,h,i,d),y&&(this.ensureObjectNode(y,u),this.storeRelation(t,y,i,d)));}}get(e,t){let r=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(r,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new G(this.storage)})}subscribe(e,t,r={}){let n=this.breakdownQuery({query:e,context:r}),s={},o=[];for(let a of n){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let i=ae(a),u=s[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",d=this.queryNodes.get(i);if(d)d.subscriptions.add(t);else if(d={hash:i,queryStep:a,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:u,childQueries:new Set},this.queryNodes.set(d.hash,d),u){let h=this.queryNodes.get(u);h&&h.childQueries.add(d.hash);}s[l]=i,o.push(()=>{let h=this.queryNodes.get(i);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(i));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var f;let{query:t,stepPath:r=[],context:n={},parentResource:s}=e,{include:o}=t,a=r.length===0,i=r.at(-1),u,l,d;if(!a&&s&&i){let T=this.schema[s],g=(f=T==null?void 0:T.relations)==null?void 0:f[i];g&&(d=g.type==="many",g.type==="one"?(u=S=>({id:S}),l=S=>S.map(b=>{var R,w;return (w=(R=b.value)==null?void 0:R[g.relationalColumn])==null?void 0:w.value}).filter(b=>b!==void 0)):(u=S=>({[g.foreignColumn]:S}),l=S=>S.map(b=>{var R,w;return (w=(R=b.value)==null?void 0:R.id)==null?void 0:w.value}).filter(b=>b!==void 0)));}let{include:h,...y}=t,p=[this.router.incrementQueryStep({query:y,stepPath:[...r],getWhere:u,referenceGetter:l,isMany:d,relationName:i},n)];if(o&&typeof o=="object"&&Object.keys(o).length>0){let T=this.schema[t.resource];if(!T)throw new Error(`Resource ${t.resource} not found`);p.push(...Object.entries(o).flatMap(([g,S])=>{let b=T.relations[g];if(!b)throw new Error(`Relation ${g} not found for resource ${t.resource}`);let R=b.entity.name,w=E(S)?S:null;return this.breakdownQuery({query:{resource:R,include:w?w.include:typeof S=="object"?S:void 0,where:w==null?void 0:w.where,limit:w==null?void 0:w.limit,sort:w==null?void 0:w.orderBy},stepPath:[...r,g],context:n,parentResource:t.resource})}));}return p}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(s=>s.stepPath.join(".")).join(" -> "));let r={},n=this.resolveStep(e[0],t).then(s=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",s.length),r[e[0].stepPath.join(".")]=[{data:s}];});for(let s=1;s<e.length;s++){let o=e[s],a=o.stepPath.slice(0,-1).join(".");n=n.then(async()=>{var u,l;let i=r[a];if(!i){r[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let d=new Map;for(let m of i)for(let p of m.data){let f=(l=(u=p==null?void 0:p.value)==null?void 0:u.id)==null?void 0:l.value;if(!f)continue;let g=o.referenceGetter([p])[0];if(g){d.has(g)||d.set(g,new Set);let S=d.get(g);S&&S.add(f);}}let h=Array.from(d.keys());if(h.length===0){r[o.stepPath.join(".")]=[];return}let y=[];for(let m of h){let p=o.getWhere(m),f={...o,relationalWhere:p},T=await this.resolveStep(f,t),g=d.get(m);if(g)for(let S of Array.from(g))y.push({includedBy:S,data:T});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",y.reduce((m,p)=>m+p.data.length,0)),r[o.stepPath.join(".")]=y;}else {let d=await this.resolveStep(o,t);r[o.stepPath.join(".")]=[{data:d}];}});}return n=n.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,r)))),n}assembleResults(e,t){var o,a,i,u,l;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let r=new Map;for(let d of e){let h=d.stepPath.join("."),y=t[h]??[],m=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:d.query.resource,includedRelations:m,resultGroups:y.length,isMany:d.isMany,relationName:d.relationName});for(let p of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:p.data.length,includedBy:p.includedBy});for(let f of p.data){let T=(a=(o=f==null?void 0:f.value)==null?void 0:o.id)==null?void 0:a.value;if(!T){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${h}"`);continue}let g=h?`${h}.${T}`:T,S=[];if(d.stepPath.length>0&&p.includedBy){let R=d.stepPath.slice(0,-1).join(".");S=[R?`${R}.${p.includedBy}`:p.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${g}" has parent keys:`,S,{stepPath:h,parentStepPath:R,includedBy:p.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${g}" (no parent)`);let b=r.get(g);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${g}" already exists, adding parent keys:`,S);for(let R of S)b.includedBy.add(R);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${g}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:m,parentKeys:S}),r.set(g,{data:f,includedBy:new Set(S),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:m});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${r.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(r.keys()));let n=Array.from(r.entries()),s=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${n.length} entries`);for(let d=n.length-1;d>=0;d--){let[h,y]=n[d],m=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${h}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let p of y.includedRelations){let f=(u=(i=m==null?void 0:m.relations)==null?void 0:i[p])==null?void 0:u.type,T=!!y.data.value[p];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${p}" for "${h}"`,{relationType:f,hasRelation:T,resourceHasRelation:!!((l=m==null?void 0:m.relations)!=null&&l[p])}),y.data.value[p])this.logger.debug(`[QueryEngine] assembleResults: Relation "${p}" already exists for "${h}"`,y.data.value[p]);else {let g=f==="many"?{value:[]}:{value:null};y.data.value[p]=g,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${p}" for "${h}" with`,g);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${h}" to resultData`),s.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to ${y.includedBy.size} parent(s)`);for(let p of Array.from(y.includedBy)){let f=r.get(p);if(!f){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${p}" not found in entriesMap for child "${h}"`);continue}let T=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${p}" via relation "${T}"`,{isMany:y.isMany,parentHasRelation:!!f.data.value[T]}),y.isMany?(f.data.value[T]??={value:[]},f.data.value[T].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${T}" on parent "${p}"`,{arrayLength:f.data.value[T].value.length})):(f.data.value[T]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${p}" to "${h}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${s.length} root items`),s}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:r,relationalWhere:n}=e,s=r.where&&n?D(r.where,n):n??r.where,o=s?{...r,where:s}:r;return se(this.router.get(o,t)).then(a=>(this.loadStepResults(e,a),a))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let r=ae(e),n=this.queryNodes.get(r),s=e.query.resource;if(!n)return;let o=this.getRelationalColumns(s);for(let a of t){let i=z$2(a),u=i.id;this.ensureObjectNode(u,s,r),n.trackedObjects.add(u);for(let[l,{relationName:d,targetResource:h}]of Array.from(o)){let y=i[l];if(y){this.ensureObjectNode(y,h);let m=this.getInverseRelationName(s,h,d);this.storeRelation(u,y,d,m);}}this.loadNestedRelations(s,u,i),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,r){let n=this.schema[e];if(n!=null&&n.relations)for(let[s,o]of Object.entries(n.relations)){let a=r[s];if(!a)continue;let i=o.entity.name,u=this.getInverseRelationName(e,i,s);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,i),this.storeRelation(t,a.id,s,u),this.loadNestedRelations(i,a.id,a));else if(o.type==="many"&&Array.isArray(a)){for(let l of a)if(l&&typeof l=="object"&&l.id){this.ensureObjectNode(l.id,i);let d=this.getInverseRelationName(i,e,s);d&&this.storeRelation(l.id,t,d,s),this.loadNestedRelations(i,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let r={};for(let n of Array.from(t.childQueries)){let s=this.queryNodes.get(n);if(!s||!s.relationName)continue;let o=this.buildIncludeFromChildQueries(n);r[s.relationName]=Object.keys(o).length>0?o:true;}return r}sendInsertsForTree(e,t,r){var a,i;let n=(i=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:i.value;if(!n)return;let s={procedure:"INSERT",resource:r,resourceId:n,type:"MUTATE",payload:t.value};for(let u of Array.from(e.subscriptions))try{u(s);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:r,resourceId:n,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(n),this.ensureObjectNode(n,r,e.hash).matchedQueries.add(e.hash);for(let u of Array.from(e.childQueries)){let l=this.queryNodes.get(u);if(!l||!l.relationName)continue;let d=l.relationName,h=l.queryStep.query.resource,y=t.value[d];if(!y)continue;let m=y.value;if(Array.isArray(m))for(let p of m)this.sendInsertsForTree(l,p,h);else m&&typeof m=="object"&&this.sendInsertsForTree(l,m,h);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let r=z$2(t);if(!r)return;let n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,n);let s=this.getRelationalColumns(e.resource);for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){let l=r[a];if(l){this.ensureObjectNode(l,u);let d=this.getInverseRelationName(e.resource,u,i);this.storeRelation(e.resourceId,l,i,d);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,r).then(a=>{for(let i of a){let u=this.queryNodes.get(i);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(i);for(let l of Array.from(u.subscriptions))try{l(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,queryHash:u.hash,resource:e.resource,resourceId:e.resourceId,stepPath:u.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let r=z$2(t);if(!r)return;let n=this.objectNodes.get(e.resourceId),s=new Set((n==null?void 0:n.matchedQueries)??[]);n||(n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,n)),this.updateRelationsFromMutation(e.resource,e.resourceId,r,e.payload),this.getMatchingQueries(e,r).then(o=>{let a=new Set(o),i=[],u=[],l=[];for(let h of o)s.has(h)?l.push(h):i.push(h);for(let h of Array.from(s))a.has(h)||u.push(h);for(let h of i){let y=this.queryNodes.get(h);y&&y.trackedObjects.add(e.resourceId);}for(let h of u){let y=this.queryNodes.get(h);y&&y.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let h of i)d.matchedQueries.add(h);for(let h of u)d.matchedQueries.delete(h);}for(let h of [...u,...l]){let y=this.queryNodes.get(h);if(y)for(let m of Array.from(y.subscriptions))try{m(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:p,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(i.length>0)for(let h of i){let y=this.queryNodes.get(h);if(!y)continue;let m=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(p=>{!p||p.length===0||this.sendInsertsForTree(y,p[0],e.resource);});}});return}}getMatchingQueries(e,t){let r=[];for(let n of Array.from(this.queryNodes.values()))n.queryStep.query.resource===e.resource&&r.push(n);return r.length===0?se([]):Promise.all(r.map(async n=>{let s=n.queryStep.query.where,o=n.queryStep.query.resource,a=e.resourceId,i=this.objectNodes.get(a);if(!i)return {hash:n.hash,matches:false};if(n.relationName){let y=n.parentQuery?this.queryNodes.get(n.parentQuery):void 0,m=y==null?void 0:y.queryStep.query.resource,p=m?this.getInverseRelationName(m,o,n.relationName):void 0,f=p?i.referencesObjects.get(p):void 0;if(!f)return {hash:n.hash,matches:false};let T=this.objectNodes.get(f);return !T||!y||!T.matchedQueries.has(y.hash)?{hash:n.hash,matches:false}:{hash:n.hash,matches:true}}if(!s)return {hash:n.hash,matches:true};let u=C$1(s,o,this.schema),l=Object.keys(u).length>0;if(!l&&t!==void 0)return {hash:n.hash,matches:D$1(t,s)};let d=await this.storage.get({resource:o,where:{id:a},include:l?u:void 0});if(!d||d.length===0)return {hash:n.hash,matches:false};let h=z$2(d[0]);return h?{hash:n.hash,matches:D$1(h,s)}:{hash:n.hash,matches:false}})).then(n=>n.filter(s=>s.matches).map(s=>s.hash))}};var qe=b(oe(),1);var X=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),ce=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),ft=ce.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ce=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),Le=z$1.object({timestamp:z$1.string().optional()}).optional(),_=Ce.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:Le}),B=Ce.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:ft,meta:Le});z$1.union([B,_]);var Qe=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var Ne=X.omit({resource:true}),ue=_.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:_.shape.meta}),de=B.omit({id:true,type:true,resource:true,procedure:true});z$1.union([de,ue]);var le=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(le);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,r]of Object.entries(c))e[t]=le(r);return e}return c},$e=c=>{let e=c.logger;return async t=>{var r;try{let n=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,s={headers:n,cookies:n.cookie?qe.default.parse(n.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),i=o.searchParams,u=le(Tt.parse(i.toString())),l=await((r=c.contextProvider)==null?void 0:r.call(c,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:u}))??{};if(t.method==="GET"){let d=a[a.length-1],{success:h,data:y,error:m}=Ne.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:m},{status:400});let p=await c.handleQuery({req:{...s,...y,type:"QUERY",resource:d,context:l,queryParams:u}});return !p||!p.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(p.data)}if(t.method==="POST")try{let d=a[a.length-1],h=a[a.length-2];if(h==="query"){if(a.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let T=a[a.length-3],g=t.body?await t.json():{};if(!T||T.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let S=await c.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:T,procedure:d,input:g.input,context:l,queryParams:u}});return Response.json(S)}let y=h,m=t.body?await t.json():{},p;if(d==="insert"||d==="update"){let{success:T,data:g,error:S}=de.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:S},{status:400});p=g;}else {let{success:T,data:g,error:S}=ue.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:S},{status:400});p=g;}let f=await c.handleMutation({req:{...s,type:"MUTATE",resource:y,input:p.payload,context:l,resourceId:p.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{},meta:p.meta}});return Response.json(f)}catch(d){return e.error("Error parsing mutation from the client:",d),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return e.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var _e=b(oe(),1);var L=z$1.string(),ye=z$1.union([Qe,X]),St=z$1.object({id:L,type:z$1.literal("SUBSCRIBE")}).and(ye),bt=z$1.object({id:L,type:z$1.literal("UNSUBSCRIBE")}).and(ye),Rt=z$1.object({id:L,type:z$1.literal("QUERY")}).and(ye),wt=z$1.object({id:L,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),ke=B.extend({id:L}),vt=_.extend({id:L}),xt=z$1.union([vt,ke]),De=z$1.union([St,Rt,wt,xt,bt]),It=z$1.object({id:L,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),Mt=z$1.object({id:L,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([It,Mt,ke]);z$1.object({resource:z$1.string(),data:z$1.array(ce)});var Ve=c=>{let e={},t=c.logger;return (r,n)=>{var d;let s=h=>{r.send(JSON.stringify(h));},o=J(),a=new Map,i={headers:n.headers,cookies:typeof n.headers.cookie=="string"?_e.default.parse(n.headers.cookie):{}},u=parse(n.url.split("?")[1]),l=(d=c.contextProvider)==null?void 0:d.call(c,{transport:"WEBSOCKET",headers:i.headers,cookies:i.cookies,queryParams:u});e[o]=r,t.info("Client connected:",o),r.on("message",async h=>{try{t.debug("Message received from the client:",h);let y=De.parse(JSON.parse(h.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:m,id:p,...f}=y,T=m==="SUBSCRIBE";if("procedure"in f){let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:f.resource,procedure:f.procedure,input:f.input,context:await l??{},queryParams:u},subscription:T?S=>{var b;!S.resourceId||!S.payload||!Object.keys(S.payload).length||(b=e[o])==null||b.send(JSON.stringify(S));}:void 0});if(T){if(!g||!g.data||!g.query)throw new Error("Invalid resource");g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:g.query.resource,data:(g.data??[]).map(S=>S.value)}});}else s({id:p,type:"REPLY",data:g});}else {let g=await c.handleQuery({req:{...i,...f,type:"QUERY",context:await l??{},queryParams:u},subscription:T?S=>{var b;!S.resourceId||!S.payload||!Object.keys(S.payload).length||(b=e[o])==null||b.send(JSON.stringify(S));}:void 0});if(!g||!g.data)throw new Error("Invalid resource");T&&g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:f.resource,data:(g.data??[]).map(S=>S.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:m,id:p,...f}=y,T=a.get(B$1(f));T&&(T(),a.delete(B$1(f)));}else if(y.type==="CUSTOM_QUERY"){let{resource:m,procedure:p,input:f,id:T}=y;t.debug("Received custom query from client:",y);try{let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:m,procedure:p,input:f,context:await l??{},queryParams:u}});s({id:T,type:"REPLY",data:g});}catch(g){s({id:T,type:"REJECT",resource:m,message:g.message}),t.error("Error handling custom query from the client:",g);}}else if(y.type==="MUTATE"){let{resource:m}=y;t.debug("Received mutation from client:",y);try{let p=await c.handleMutation({req:{...i,type:"MUTATE",resource:m,input:y.payload,context:{messageId:y.id,...await l??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:u,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&s({id:y.id,type:"REPLY",data:p});}catch(p){s({id:y.id,type:"REJECT",resource:m,message:p.message}),t.error("Error parsing mutation from the client:",p);}}}catch(y){t.error("Error handling message from the client:",y);}}),r.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let h of Array.from(a.values()))h();});}};function Be(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Lr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ve(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{$e(e)(Be(r)).then(o=>o.json().then(a=>n.status(o.status).send(a)));});};var ee=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,r,n,s,o,a,i){this._collection=e,this._client=t,this._where=r??{},this._include=n??{},this._limit=s,this._single=o,this._sort=a,this._shouldAwait=i,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new c(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new c(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new c(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new c(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let r=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,r,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,r){return new c(e,t,void 0,void 0,void 0,void 0,void 0,r??false)}};var Ot=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),he=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(r=>Ot(r)?z$2(r):r))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function $(c,e){let t=new he(c),r=s=>{let o=ee._init(s,t,true);return Object.assign(Object.create(o),{insert:i=>c.insert(s,i),update:(i,u)=>c.update(s,i,u)})},n={get(s,o){if(o==="findOne")return c.findOne.bind(c);if(o==="find")return c.find.bind(c);if(o==="insert")return c.insert.bind(c);if(o==="update")return c.update.bind(c);if(o==="transaction")return async a=>c.transaction(async({trx:i,commit:u,rollback:l})=>{let d=$(i,e);return a({trx:d,commit:u,rollback:l})});if(o in e){let a=e[o];return r(a)}}};return new Proxy({},n)}var pe=class c{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){if(t.resourceSchema===void 0)continue;let r=t;r.hooks&&this.hooksRegistry.set(r.resourceSchema.name,r.hooks);}}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}},zr=c=>pe.create({...c}),Fe=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),Ue=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),me=class c{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,r,n,s){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=r??{},this.authorization=n,this.hooks=s;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:Ue,query:Fe}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new c(this.resourceSchema,r,n,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new c(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async r=>{let n={resource:r.resource,where:r.where,include:r.include,lastSyncedAt:r.lastSyncedAt,limit:r.limit,sort:r.sort},s=B$1(n);return {data:await t.rawFind({resource:r.resource,commonWhere:r.where,uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort}),unsubscribe:void 0,queryHash:s}})(e);handleMutation=async({req:e,db:t,schema:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}else {if(i.procedure==="INSERT"||i.procedure==="UPDATE")return this.handleSet({req:i,db:s,operation:i.procedure,schema:r});throw new Error(`Unknown procedure: ${i.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(e){var t,r;return (r=(t=this.authorization)==null?void 0:t.read)==null?void 0:r.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:r,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let s=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&s)throw new Error("Resource already exists");if(r==="UPDATE"&&!s)throw new Error("Resource not found");let o={value:e.input};return t.transaction(async({trx:a})=>{var l,d,h,y,m,p,f;if(r==="INSERT"){let{data:T,acceptedValues:g}=await a.rawInsert(e.resource,e.resourceId,o,(l=e.context)==null?void 0:l.messageId,e.context);if(!g)throw new Error("Mutation rejected");let S=z$2(T);if(S.id=S.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let b=this.authorization.insert({ctx:e.context,value:S});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let R=C$1(b,e.resource,n),w=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):T,x=z$2(w);if(x.id=x.id??e.resourceId,!D$1(x,b))throw new Error("Not authorized")}}return {data:T,acceptedValues:g}}if((y=(h=this.authorization)==null?void 0:h.update)!=null&&y.preMutation){let T=z$2(s);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let S=C$1(g,e.resource,n),b=Object.keys(S).length>0?await a.rawFindById(e.resource,e.resourceId,S):s,R=z$2(b);if(R.id=R.id??e.resourceId,!D$1(R,g))throw new Error("Not authorized")}}let{data:i,acceptedValues:u}=await a.rawUpdate(e.resource,e.resourceId,o,(m=e.context)==null?void 0:m.messageId,e.context);if(!u)throw new Error("Mutation rejected");if((f=(p=this.authorization)==null?void 0:p.update)!=null&&f.postMutation){let T=z$2(i);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let S=C$1(g,e.resource,n),b=Object.keys(S).length>0?await a.rawFindById(e.resource,e.resourceId,S):i,R=z$2(b);if(R.id=R.id??e.resourceId,!D$1(R,g))throw new Error("Not authorized")}}return {data:i,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},fe=class{resourceSchema=void 0;middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}throw new Error(`Unknown procedure: ${i.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},ge=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new me(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:Ue,query:Fe}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new fe(r,n).use(...this.middlewares)}use(...e){return new c([...this.middlewares,...e])}static create(){return new c}},Fr=ge.create;var z=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let r=this._getTimestamp(),n=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([s,o])=>[s,{value:o,_meta:{timestamp:r}}]))});return z$2(n.data)}async update(e,t,r){let n=this._getTimestamp(),{id:s,...o}=r,a=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([l,d])=>[l,{value:d,_meta:{timestamp:n}}]))}),i=z$2(a.data),u={};for(let l of Object.keys(o))l in i&&(u[l]=i[l]);return u}};var Nt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function C(c){var n,s,o;let e=(n=c.getExecutor)==null?void 0:n.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let r=((o=(s=t.constructor)==null?void 0:s.name)==null?void 0:o.toLowerCase())??"";return r.includes("postgres")?"postgres":r.includes("mysql")?"mysql":r.includes("sqlite")?"sqlite":"postgres"}function We(c){let e=C(c);return Nt[e]}var qt="42701";function F(c){var t;if(c.code===qt)return true;let e=((t=c.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function Se(c,e){let{type:t,enumValues:r,enumName:n}=c;if(r&&r.length>0)return e==="postgres"&&n?n:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function $t(c,e,t,r){if(t!=="postgres")return;let n=new Map;for(let s of Object.values(e))for(let o of Object.values(s.fields)){let a=o.getStorageFieldType();a.enumValues&&a.enumName&&n.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let s of Array.from(n.values())){let{name:o,values:a}=s;try{let i=a.map(u=>`'${u}'`).join(", ");await sql`
1
+ import {a,b,B as B$1,z as z$2,C,D as D$1,G as G$1,F as F$1,E}from'./chunk-3XEJ2M4E.js';import H from'crypto';import Tt,{parse}from'qs';import {z as z$1}from'zod';import {Kysely,PostgresDialect,sql}from'kysely';import {jsonArrayFrom as jsonArrayFrom$1,jsonObjectFrom as jsonObjectFrom$1}from'kysely/helpers/mysql';import {jsonArrayFrom as jsonArrayFrom$2,jsonObjectFrom as jsonObjectFrom$2}from'kysely/helpers/postgres';import {jsonArrayFrom,jsonObjectFrom}from'kysely/helpers/sqlite';var oe=a(Y=>{Object.defineProperty(Y,"__esModule",{value:true});Y.parse=yt;Y.serialize=ht;var at=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ot=/^[\u0021-\u003A\u003C-\u007E]*$/,ct=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ut=/^[\u0020-\u003A\u003D-\u007E]*$/,dt=Object.prototype.toString,lt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function yt(c,e){let t=new lt,r=c.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||pt,s=0;do{let o=c.indexOf("=",s);if(o===-1)break;let a=c.indexOf(";",s),i=a===-1?r:a;if(o>i){s=c.lastIndexOf(";",o-1)+1;continue}let u=Ae(c,s,o),l=Ee(c,o,u),d=c.slice(u,l);if(t[d]===void 0){let h=Ae(c,o+1,i),y=Ee(c,i,h),m=n(c.slice(h,y));t[d]=m;}s=i+1;}while(s<r);return t}function Ae(c,e,t){do{let r=c.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Ee(c,e,t){for(;e>t;){let r=c.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function ht(c,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!at.test(c))throw new TypeError(`argument name is invalid: ${c}`);let n=r(e);if(!ot.test(n))throw new TypeError(`argument val is invalid: ${e}`);let s=c+"="+n;if(!t)return s;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);s+="; Max-Age="+t.maxAge;}if(t.domain){if(!ct.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!ut.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!mt(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);s+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(s+="; HttpOnly"),t.secure&&(s+="; Secure"),t.partitioned&&(s+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":s+="; Priority=Low";break;case "medium":s+="; Priority=Medium";break;case "high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":s+="; SameSite=Strict";break;case "lax":s+="; SameSite=Lax";break;case "none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return s}function pt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function mt(c){return dt.call(c)==="[object Date]"}});var Ce="0123456789ABCDEFGHJKMNPQRSTVWXYZ",V=32;var Xe=16,je=10,Ie=0xffffffffffff;var N;(function(c){c.Base32IncorrectEncoding="B32_ENC_INVALID",c.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",c.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",c.EncodeTimeNegative="ENC_TIME_NEG",c.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",c.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",c.PRNGDetectFailure="PRNG_DETECT",c.ULIDInvalid="ULID_INVALID",c.Unexpected="UNEXPECTED",c.UUIDInvalid="UUID_INVALID";})(N||(N={}));var q=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function et(c){let e=Math.floor(c()*V);return e===V&&(e=V-1),Ce.charAt(e)}function tt(c){var r;let e=rt(),t=e&&(e.crypto||e.msCrypto)||(typeof H<"u"?H:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=H)!=null&&r.randomBytes)return ()=>H.randomBytes(1).readUInt8()/255;throw new q(N.PRNGDetectFailure,"Failed to find a reliable PRNG")}function rt(){return st()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function nt(c,e){let t="";for(;c>0;c--)t=et(e)+t;return t}function it(c,e=je){if(isNaN(c))throw new q(N.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>Ie)throw new q(N.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Ie}: ${c}`);if(c<0)throw new q(N.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new q(N.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,r="";for(let n=e;n>0;n--)t=c%V,r=Ce.charAt(t)+r,c=(c-t)/V;return r}function st(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Oe(c,e){let t=tt(),r=Date.now();return it(r,je)+nt(Xe,t)}var J=()=>Oe().toLowerCase(),K=c=>({then(e,t){try{if(e){let r=e(c);return r instanceof Promise?r:K(r)}return K(c)}catch(r){if(t){let n=t(r);return n instanceof Promise?n:K(n)}throw r}}}),se=c=>c instanceof Promise?c:K(c);var _=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var G=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...n}){return new Promise((s,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...n}),i={resource:e,commonWhere:t,uniqueWhere:r,...n,resolve:s,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(i),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...n}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(r){t.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:n,include:s,sort:o}=t,a=e.length===1?t.limit:void 0,i=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),u=n,l=(h=Object.entries(i[0]??{})[0])==null?void 0:h[0];if(i.length>0){let y=i.map(m=>m[l]).filter(m=>m!=null);y.length>0&&(u=_(n,{[l]:{$in:y}}));}let d=await this.storage.get({resource:r,where:u,include:s,sort:o,limit:a});for(let y of e){let m=d;if(y.uniqueWhere){let[p,f]=Object.entries(y.uniqueWhere)[0];m=d.filter(T=>{var g;return ((g=T.value[p])==null?void 0:g.value)===f});}y.resolve(m);}}};function ae(c){return B$1({resource:c.query.resource,where:c.query.where,include:c.query.include,stepPath:c.stepPath,isMany:c.isMany,relationName:c.relationName})}var Z=class{router;storage;schema;logger;queryNodes=new Map;objectNodes=new Map;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=e.logger;}getRelationalColumns(e){let t=new Map,r=this.schema[e];if(!(r!=null&&r.relations))return t;for(let[n,s]of Object.entries(r.relations))s.type==="one"&&s.relationalColumn&&t.set(String(s.relationalColumn),{relationName:n,targetResource:s.entity.name});return t}ensureObjectNode(e,t,r){let n=this.objectNodes.get(e);return n?r&&n.matchedQueries.add(r):(n={id:e,type:t,matchedQueries:new Set(r?[r]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,n)),n}storeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.set(r,t),o&&n){let a=o.referencedByObjects.get(n);a||(a=new Set,o.referencedByObjects.set(n,a)),a.add(e);}}removeRelation(e,t,r,n){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.delete(r),o&&n){let a=o.referencedByObjects.get(n);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(n));}}getInverseRelationName(e,t,r){let n=this.schema[e];if(!(n!=null&&n.relations))return;let s=n.relations[r];if(!s)return;let o=this.schema[t];if(o!=null&&o.relations){if(s.type==="many"&&s.foreignColumn){for(let[a,i]of Object.entries(o.relations))if(i.entity.name===e&&i.type==="one"&&i.relationalColumn===s.foreignColumn)return a}if(s.type==="one"&&s.relationalColumn){for(let[a,i]of Object.entries(o.relations))if(i.entity.name===e&&i.type==="many"&&i.foreignColumn===s.relationalColumn)return a}}}updateRelationsFromMutation(e,t,r,n){let s=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){if(!(n&&a in n))continue;let d=this.getInverseRelationName(e,u,i),h=o.referencesObjects.get(i),y=r[a];h!==y&&(h&&this.removeRelation(t,h,i,d),y&&(this.ensureObjectNode(y,u),this.storeRelation(t,y,i,d)));}}get(e,t){let r=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(r,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new G(this.storage)})}subscribe(e,t,r={}){let n=this.breakdownQuery({query:e,context:r}),s={},o=[];for(let a of n){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let i=ae(a),u=s[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",d=this.queryNodes.get(i);if(d)d.subscriptions.add(t);else if(d={hash:i,queryStep:a,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:u,childQueries:new Set},this.queryNodes.set(d.hash,d),u){let h=this.queryNodes.get(u);h&&h.childQueries.add(d.hash);}s[l]=i,o.push(()=>{let h=this.queryNodes.get(i);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(i));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var f;let{query:t,stepPath:r=[],context:n={},parentResource:s}=e,{include:o}=t,a=r.length===0,i=r.at(-1),u,l,d;if(!a&&s&&i){let T=this.schema[s],g=(f=T==null?void 0:T.relations)==null?void 0:f[i];g&&(d=g.type==="many",g.type==="one"?(u=R=>({id:R}),l=R=>R.map(S=>{var b,w;return (w=(b=S.value)==null?void 0:b[g.relationalColumn])==null?void 0:w.value}).filter(S=>S!==void 0)):(u=R=>({[g.foreignColumn]:R}),l=R=>R.map(S=>{var b,w;return (w=(b=S.value)==null?void 0:b.id)==null?void 0:w.value}).filter(S=>S!==void 0)));}let{include:h,...y}=t,p=[this.router.incrementQueryStep({query:y,stepPath:[...r],getWhere:u,referenceGetter:l,isMany:d,relationName:i},n)];if(o&&typeof o=="object"&&Object.keys(o).length>0){let T=this.schema[t.resource];if(!T)throw new Error(`Resource ${t.resource} not found`);p.push(...Object.entries(o).flatMap(([g,R])=>{let S=T.relations[g];if(!S)throw new Error(`Relation ${g} not found for resource ${t.resource}`);let b=S.entity.name,w=E(R)?R:null;return this.breakdownQuery({query:{resource:b,include:w?w.include:typeof R=="object"?R:void 0,where:w==null?void 0:w.where,limit:w==null?void 0:w.limit,sort:w==null?void 0:w.orderBy},stepPath:[...r,g],context:n,parentResource:t.resource})}));}return p}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(s=>s.stepPath.join(".")).join(" -> "));let r={},n=this.resolveStep(e[0],t).then(s=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",s.length),r[e[0].stepPath.join(".")]=[{data:s}];});for(let s=1;s<e.length;s++){let o=e[s],a=o.stepPath.slice(0,-1).join(".");n=n.then(async()=>{var u,l;let i=r[a];if(!i){r[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let d=new Map;for(let m of i)for(let p of m.data){let f=(l=(u=p==null?void 0:p.value)==null?void 0:u.id)==null?void 0:l.value;if(!f)continue;let g=o.referenceGetter([p])[0];if(g){d.has(g)||d.set(g,new Set);let R=d.get(g);R&&R.add(f);}}let h=Array.from(d.keys());if(h.length===0){r[o.stepPath.join(".")]=[];return}let y=[];for(let m of h){let p=o.getWhere(m),f={...o,relationalWhere:p},T=await this.resolveStep(f,t),g=d.get(m);if(g)for(let R of Array.from(g))y.push({includedBy:R,data:T});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",y.reduce((m,p)=>m+p.data.length,0)),r[o.stepPath.join(".")]=y;}else {let d=await this.resolveStep(o,t);r[o.stepPath.join(".")]=[{data:d}];}});}return n=n.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,r)))),n}assembleResults(e,t){var o,a,i,u,l;this.logger.debug("[QueryEngine] assembleResults: Starting assembly"),this.logger.debug("[QueryEngine] assembleResults: Plan steps:",e.length),this.logger.debug("[QueryEngine] assembleResults: Step results keys:",Object.keys(t));let r=new Map;for(let d of e){let h=d.stepPath.join("."),y=t[h]??[],m=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:d.query.resource,includedRelations:m,resultGroups:y.length,isMany:d.isMany,relationName:d.relationName});for(let p of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:p.data.length,includedBy:p.includedBy});for(let f of p.data){let T=(a=(o=f==null?void 0:f.value)==null?void 0:o.id)==null?void 0:a.value;if(!T){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${h}"`);continue}let g=h?`${h}.${T}`:T,R=[];if(d.stepPath.length>0&&p.includedBy){let b=d.stepPath.slice(0,-1).join(".");R=[b?`${b}.${p.includedBy}`:p.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${g}" has parent keys:`,R,{stepPath:h,parentStepPath:b,includedBy:p.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${g}" (no parent)`);let S=r.get(g);if(S){this.logger.debug(`[QueryEngine] assembleResults: Entity "${g}" already exists, adding parent keys:`,R);for(let b of R)S.includedBy.add(b);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${g}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:m,parentKeys:R}),r.set(g,{data:f,includedBy:new Set(R),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:m});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${r.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(r.keys()));let n=Array.from(r.entries()),s=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${n.length} entries`);for(let d=n.length-1;d>=0;d--){let[h,y]=n[d],m=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${h}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let p of y.includedRelations){let f=(u=(i=m==null?void 0:m.relations)==null?void 0:i[p])==null?void 0:u.type,T=!!y.data.value[p];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${p}" for "${h}"`,{relationType:f,hasRelation:T,resourceHasRelation:!!((l=m==null?void 0:m.relations)!=null&&l[p])}),y.data.value[p])this.logger.debug(`[QueryEngine] assembleResults: Relation "${p}" already exists for "${h}"`,y.data.value[p]);else {let g=f==="many"?{value:[]}:{value:null};y.data.value[p]=g,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${p}" for "${h}" with`,g);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${h}" to resultData`),s.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to ${y.includedBy.size} parent(s)`);for(let p of Array.from(y.includedBy)){let f=r.get(p);if(!f){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${p}" not found in entriesMap for child "${h}"`);continue}let T=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${p}" via relation "${T}"`,{isMany:y.isMany,parentHasRelation:!!f.data.value[T]}),y.isMany?(f.data.value[T]??={value:[]},f.data.value[T].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${T}" on parent "${p}"`,{arrayLength:f.data.value[T].value.length})):(f.data.value[T]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${p}" to "${h}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${s.length} root items`),s}resolveStep(e,t){this.logger.debug("[QueryEngine] Resolving step",e.stepPath.join("."),"with query",JSON.stringify(e.query,null,2),"relationalWhere",JSON.stringify(e.relationalWhere,null,2));let{query:r,relationalWhere:n}=e,s=r.where&&n?_(r.where,n):n??r.where,o=s?{...r,where:s}:r;return se(this.router.get(o,t)).then(a=>(this.loadStepResults(e,a),a))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let r=ae(e),n=this.queryNodes.get(r),s=e.query.resource;if(!n)return;let o=this.getRelationalColumns(s);for(let a of t){let i=z$2(a),u=i.id;this.ensureObjectNode(u,s,r),n.trackedObjects.add(u);for(let[l,{relationName:d,targetResource:h}]of Array.from(o)){let y=i[l];if(y){this.ensureObjectNode(y,h);let m=this.getInverseRelationName(s,h,d);this.storeRelation(u,y,d,m);}}this.loadNestedRelations(s,u,i),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,r){let n=this.schema[e];if(n!=null&&n.relations)for(let[s,o]of Object.entries(n.relations)){let a=r[s];if(!a)continue;let i=o.entity.name,u=this.getInverseRelationName(e,i,s);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,i),this.storeRelation(t,a.id,s,u),this.loadNestedRelations(i,a.id,a));else if(o.type==="many"&&Array.isArray(a)){for(let l of a)if(l&&typeof l=="object"&&l.id){this.ensureObjectNode(l.id,i);let d=this.getInverseRelationName(i,e,s);d&&this.storeRelation(l.id,t,d,s),this.loadNestedRelations(i,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let r={};for(let n of Array.from(t.childQueries)){let s=this.queryNodes.get(n);if(!s||!s.relationName)continue;let o=this.buildIncludeFromChildQueries(n);r[s.relationName]=Object.keys(o).length>0?o:true;}return r}sendInsertsForTree(e,t,r){var a,i;let n=(i=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:i.value;if(!n)return;let s={procedure:"INSERT",resource:r,resourceId:n,type:"MUTATE",payload:t.value};for(let u of Array.from(e.subscriptions))try{u(s);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:r,resourceId:n,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(n),this.ensureObjectNode(n,r,e.hash).matchedQueries.add(e.hash);for(let u of Array.from(e.childQueries)){let l=this.queryNodes.get(u);if(!l||!l.relationName)continue;let d=l.relationName,h=l.queryStep.query.resource,y=t.value[d];if(!y)continue;let m=y.value;if(Array.isArray(m))for(let p of m)this.sendInsertsForTree(l,p,h);else m&&typeof m=="object"&&this.sendInsertsForTree(l,m,h);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let r=z$2(t);if(!r)return;let n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,n);let s=this.getRelationalColumns(e.resource);for(let[a,{relationName:i,targetResource:u}]of Array.from(s)){let l=r[a];if(l){this.ensureObjectNode(l,u);let d=this.getInverseRelationName(e.resource,u,i);this.storeRelation(e.resourceId,l,i,d);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,r).then(a=>{for(let i of a){let u=this.queryNodes.get(i);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(i);for(let l of Array.from(u.subscriptions))try{l(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,queryHash:u.hash,resource:e.resource,resourceId:e.resourceId,stepPath:u.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let r=z$2(t);if(!r)return;let n=this.objectNodes.get(e.resourceId),s=new Set((n==null?void 0:n.matchedQueries)??[]);n||(n={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,n)),this.updateRelationsFromMutation(e.resource,e.resourceId,r,e.payload),this.getMatchingQueries(e,r).then(o=>{let a=new Set(o),i=[],u=[],l=[];for(let h of o)s.has(h)?l.push(h):i.push(h);for(let h of Array.from(s))a.has(h)||u.push(h);for(let h of i){let y=this.queryNodes.get(h);y&&y.trackedObjects.add(e.resourceId);}for(let h of u){let y=this.queryNodes.get(h);y&&y.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let h of i)d.matchedQueries.add(h);for(let h of u)d.matchedQueries.delete(h);}for(let h of [...u,...l]){let y=this.queryNodes.get(h);if(y)for(let m of Array.from(y.subscriptions))try{m(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:p,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(i.length>0)for(let h of i){let y=this.queryNodes.get(h);if(!y)continue;let m=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(m).length>0?m:void 0}).then(p=>{!p||p.length===0||this.sendInsertsForTree(y,p[0],e.resource);});}});return}}getMatchingQueries(e,t){let r=[];for(let n of Array.from(this.queryNodes.values()))n.queryStep.query.resource===e.resource&&r.push(n);return r.length===0?se([]):Promise.all(r.map(async n=>{let s=n.queryStep.query.where,o=n.queryStep.query.resource,a=e.resourceId,i=this.objectNodes.get(a);if(!i)return {hash:n.hash,matches:false};if(n.relationName){let y=n.parentQuery?this.queryNodes.get(n.parentQuery):void 0,m=y==null?void 0:y.queryStep.query.resource,p=m?this.getInverseRelationName(m,o,n.relationName):void 0,f=p?i.referencesObjects.get(p):void 0;if(!f)return {hash:n.hash,matches:false};let T=this.objectNodes.get(f);return !T||!y||!T.matchedQueries.has(y.hash)?{hash:n.hash,matches:false}:{hash:n.hash,matches:true}}if(!s)return {hash:n.hash,matches:true};let u=C(s,o,this.schema),l=Object.keys(u).length>0;if(!l&&t!==void 0)return {hash:n.hash,matches:D$1(t,s)};let d=await this.storage.get({resource:o,where:{id:a},include:l?u:void 0});if(!d||d.length===0)return {hash:n.hash,matches:false};let h=z$2(d[0]);return h?{hash:n.hash,matches:D$1(h,s)}:{hash:n.hash,matches:false}})).then(n=>n.filter(s=>s.matches).map(s=>s.hash))}};var qe=b(oe(),1);var X=z$1.object({resource:z$1.string(),where:z$1.record(z$1.string(),z$1.any()).optional(),include:z$1.record(z$1.string(),z$1.any()).optional(),lastSyncedAt:z$1.string().optional(),limit:z$1.coerce.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),ce=z$1.record(z$1.string(),z$1.object({value:z$1.any().nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})),ft=ce.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Pe=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),Le=z$1.object({timestamp:z$1.string().optional()}).optional(),D=Pe.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:Le}),B=Pe.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:ft,meta:Le});z$1.union([B,D]);var Qe=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var Ne=X.omit({resource:true}),ue=D.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:D.shape.meta}),de=B.omit({id:true,type:true,resource:true,procedure:true});z$1.union([de,ue]);var le=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(le);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,r]of Object.entries(c))e[t]=le(r);return e}return c},$e=c=>{let e=c.logger;return async t=>{var r;try{let n=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,s={headers:n,cookies:n.cookie?qe.default.parse(n.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),i=o.searchParams,u=le(Tt.parse(i.toString())),l=await((r=c.contextProvider)==null?void 0:r.call(c,{transport:"HTTP",headers:s.headers,cookies:s.cookies,queryParams:u}))??{};if(t.method==="GET"){let d=a[a.length-1],{success:h,data:y,error:m}=Ne.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:m},{status:400});let p=await c.handleQuery({req:{...s,...y,type:"QUERY",resource:d,context:l,queryParams:u}});return !p||!p.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(p.data)}if(t.method==="POST")try{let d=a[a.length-1],h=a[a.length-2];if(h==="query"){if(a.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let T=a[a.length-3],g=t.body?await t.json():{};if(!T||T.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let R=await c.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:T,procedure:d,input:g.input,context:l,queryParams:u}});return Response.json(R)}let y=h,m=t.body?await t.json():{},p;if(d==="insert"||d==="update"){let{success:T,data:g,error:R}=de.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=g;}else {let{success:T,data:g,error:R}=ue.safeParse(m);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=g;}let f=await c.handleMutation({req:{...s,type:"MUTATE",resource:y,input:p.payload,context:l,resourceId:p.resourceId,procedure:d==="insert"||d==="update"?d.toUpperCase():d,queryParams:{},meta:p.meta}});return Response.json(f)}catch(d){return e.error("Error parsing mutation from the client:",d),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return e.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var De=b(oe(),1);var L=z$1.string(),ye=z$1.union([Qe,X]),Rt=z$1.object({id:L,type:z$1.literal("SUBSCRIBE")}).and(ye),St=z$1.object({id:L,type:z$1.literal("UNSUBSCRIBE")}).and(ye),bt=z$1.object({id:L,type:z$1.literal("QUERY")}).and(ye),wt=z$1.object({id:L,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),ke=B.extend({id:L}),xt=D.extend({id:L}),vt=z$1.union([xt,ke]),_e=z$1.union([Rt,bt,wt,vt,St]),Mt=z$1.object({id:L,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),It=z$1.object({id:L,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([Mt,It,ke]);z$1.object({resource:z$1.string(),data:z$1.array(ce)});var Ve=c=>{let e={},t=c.logger;return (r,n)=>{var d;let s=h=>{r.send(JSON.stringify(h));},o=J(),a=new Map,i={headers:n.headers,cookies:typeof n.headers.cookie=="string"?De.default.parse(n.headers.cookie):{}},u=parse(n.url.split("?")[1]),l=(d=c.contextProvider)==null?void 0:d.call(c,{transport:"WEBSOCKET",headers:i.headers,cookies:i.cookies,queryParams:u});e[o]=r,t.info("Client connected:",o),r.on("message",async h=>{try{t.debug("Message received from the client:",h);let y=_e.parse(JSON.parse(h.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:m,id:p,...f}=y,T=m==="SUBSCRIBE";if("procedure"in f){let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:f.resource,procedure:f.procedure,input:f.input,context:await l??{},queryParams:u},subscription:T?R=>{var S;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(S=e[o])==null||S.send(JSON.stringify(R));}:void 0});if(T){if(!g||!g.data||!g.query)throw new Error("Invalid resource");g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:g.query.resource,data:(g.data??[]).map(R=>R.value)}});}else s({id:p,type:"REPLY",data:g});}else {let g=await c.handleQuery({req:{...i,...f,type:"QUERY",context:await l??{},queryParams:u},subscription:T?R=>{var S;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(S=e[o])==null||S.send(JSON.stringify(R));}:void 0});if(!g||!g.data)throw new Error("Invalid resource");T&&g.unsubscribe&&a.set(B$1(f),g.unsubscribe),s({id:p,type:"REPLY",data:{resource:f.resource,data:(g.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:m,id:p,...f}=y,T=a.get(B$1(f));T&&(T(),a.delete(B$1(f)));}else if(y.type==="CUSTOM_QUERY"){let{resource:m,procedure:p,input:f,id:T}=y;t.debug("Received custom query from client:",y);try{let g=await c.handleCustomQuery({req:{...i,type:"CUSTOM_QUERY",resource:m,procedure:p,input:f,context:await l??{},queryParams:u}});s({id:T,type:"REPLY",data:g});}catch(g){s({id:T,type:"REJECT",resource:m,message:g.message}),t.error("Error handling custom query from the client:",g);}}else if(y.type==="MUTATE"){let{resource:m}=y;t.debug("Received mutation from client:",y);try{let p=await c.handleMutation({req:{...i,type:"MUTATE",resource:m,input:y.payload,context:{messageId:y.id,...await l??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:u,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&s({id:y.id,type:"REPLY",data:p});}catch(p){s({id:y.id,type:"REJECT",resource:m,message:p.message}),t.error("Error parsing mutation from the client:",p);}}}catch(y){t.error("Error handling message from the client:",y);}}),r.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let h of Array.from(a.values()))h();});}};function Be(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Lr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ve(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{$e(e)(Be(r)).then(o=>o.json().then(a=>n.status(o.status).send(a)));});};var ee=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,r,n,s,o,a,i){this._collection=e,this._client=t,this._where=r??{},this._include=n??{},this._limit=s,this._single=o,this._sort=a,this._shouldAwait=i,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new c(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new c(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new c(this._collection,this._client,this._where,this._include,e,this._single,this._sort,this._shouldAwait)}one(e){return this.first({id:e})}first(e){return new c(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let r=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,r,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(t=>this._single?t[0]:t):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),t=>{if(this._single)return e(t[0]);e(t);})}static _init(e,t,r){return new c(e,t,void 0,void 0,void 0,void 0,void 0,r??false)}};var jt=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),he=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(r=>jt(r)?z$2(r):r))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function $(c,e){let t=new he(c),r=s=>{let o=ee._init(s,t,true);return Object.assign(Object.create(o),{insert:i=>c.insert(s,i),update:(i,u)=>c.update(s,i,u)})},n={get(s,o){if(o==="findOne")return c.findOne.bind(c);if(o==="find")return c.find.bind(c);if(o==="insert")return c.insert.bind(c);if(o==="update")return c.update.bind(c);if(o==="transaction")return async a=>c.transaction(async({trx:i,commit:u,rollback:l})=>{let d=$(i,e);return a({trx:d,commit:u,rollback:l})});if(o in e){let a=e[o];return r(a)}}};return new Proxy({},n)}var pe=class c{routes;hooksRegistry=new Map;constructor(e){this.routes=e.routes;for(let t of Object.values(e.routes)){if(t.resourceSchema===void 0)continue;let r=t;r.hooks&&this.hooksRegistry.set(r.resourceSchema.name,r.hooks);}}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}},zr=c=>pe.create({...c}),Fe=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),Ue=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),me=class c{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,r,n,s){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=r??{},this.authorization=n,this.hooks=s;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:Ue,query:Fe}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new c(this.resourceSchema,r,n,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new c(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async r=>{let n={resource:r.resource,where:r.where,include:r.include,lastSyncedAt:r.lastSyncedAt,limit:r.limit,sort:r.sort},s=B$1(n);return {data:await t.rawFind({resource:r.resource,commonWhere:r.where,uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort}),unsubscribe:void 0,queryHash:s}})(e);handleMutation=async({req:e,db:t,schema:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}else {if(i.procedure==="INSERT"||i.procedure==="UPDATE")return this.handleSet({req:i,db:s,operation:i.procedure,schema:r});throw new Error(`Unknown procedure: ${i.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(e){var t,r;return (r=(t=this.authorization)==null?void 0:t.read)==null?void 0:r.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:r,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let s=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&s)throw new Error("Resource already exists");if(r==="UPDATE"&&!s)throw new Error("Resource not found");let o={value:e.input};return t.transaction(async({trx:a})=>{var l,d,h,y,m,p,f;if(r==="INSERT"){let{data:T,acceptedValues:g}=await a.rawInsert(e.resource,e.resourceId,o,(l=e.context)==null?void 0:l.messageId,e.context);if(!g)throw new Error("Mutation rejected");let R=z$2(T);if(R.id=R.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let S=this.authorization.insert({ctx:e.context,value:R});if(typeof S=="boolean"){if(!S)throw new Error("Not authorized")}else {let b=C(S,e.resource,n),w=Object.keys(b).length>0?await a.rawFindById(e.resource,e.resourceId,b):T,v=z$2(w);if(v.id=v.id??e.resourceId,!D$1(v,S))throw new Error("Not authorized")}}return {data:T,acceptedValues:g}}if((y=(h=this.authorization)==null?void 0:h.update)!=null&&y.preMutation){let T=z$2(s);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let R=C(g,e.resource,n),S=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):s,b=z$2(S);if(b.id=b.id??e.resourceId,!D$1(b,g))throw new Error("Not authorized")}}let{data:i,acceptedValues:u}=await a.rawUpdate(e.resource,e.resourceId,o,(m=e.context)==null?void 0:m.messageId,e.context);if(!u)throw new Error("Mutation rejected");if((f=(p=this.authorization)==null?void 0:p.update)!=null&&f.postMutation){let T=z$2(i);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let R=C(g,e.resource,n),S=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):i,b=z$2(S);if(b.id=b.id??e.resourceId,!D$1(b,g))throw new Error("Not authorized")}}return {data:i,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},fe=class{resourceSchema=void 0;middlewares;customMutations;customQueries;constructor(e,t){this.middlewares=new Set,this.customMutations=e??{},this.customQueries=t??{};}use(...e){for(let t of e)this.middlewares.add(t);return this}handleMutation=async({req:e,db:t,schema:r})=>{var a;let n=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(n),o=$(s,r);return await this.wrapInMiddlewares(async i=>{if(!i.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[i.procedure];if(u){let l=u.inputValidator["~standard"].validate(i.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var p;let m=(p=y.path)==null?void 0:p.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return m?`${m}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return i.input=d.value,u.handler({req:i,db:o})}throw new Error(`Unknown procedure: ${i.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let n=$(t,r);return await this.wrapInMiddlewares(async s=>{let o=this.customQueries[s.procedure];if(!o)throw new Error(`Unknown query procedure: ${s.procedure}`);let a=o.inputValidator["~standard"].validate(s.input),i=a instanceof Promise?await a:a;if(i.issues){let u=i.issues.map(l=>{var h;let d=(h=l.path)==null?void 0:h.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return s.input=i.value,o.handler({req:s,db:n})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}};function Fr(c){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:r})=>c({ctx:t.context,req:t,next:n=>(t.context=n,r(t))})}}var ge=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new me(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:Ue,query:Fe}),r={},n={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:n[s]=o;return new fe(r,n).use(...this.middlewares)}use(...e){let t=e.map(r=>r&&r._brand==="TypedMiddleware"?r._rawMiddleware:r);return new c([...this.middlewares,...t])}static create(){return new c}},Ur=ge.create;var z=class{_mutationTimestamp;_setMutationTimestamp(e){let t=this._clone();return t._mutationTimestamp=e,t}_getTimestamp(){return this._mutationTimestamp??new Date().toISOString()}_clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}async insert(e,t){let r=this._getTimestamp(),n=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([s,o])=>[s,{value:o,_meta:{timestamp:r}}]))});return z$2(n.data)}async update(e,t,r){let n=this._getTimestamp(),{id:s,...o}=r,a=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([l,d])=>[l,{value:d,_meta:{timestamp:n}}]))}),i=z$2(a.data),u={};for(let l of Object.keys(o))l in i&&(u[l]=i[l]);return u}};var Nt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function P(c){var n,s,o;let e=(n=c.getExecutor)==null?void 0:n.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let r=((o=(s=t.constructor)==null?void 0:s.name)==null?void 0:o.toLowerCase())??"";return r.includes("postgres")?"postgres":r.includes("mysql")?"mysql":r.includes("sqlite")?"sqlite":"postgres"}function We(c){let e=P(c);return Nt[e]}var qt="42701";function F(c){var t;if(c.code===qt)return true;let e=((t=c.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function Re(c,e){let{type:t,enumValues:r,enumName:n}=c;if(r&&r.length>0)return e==="postgres"&&n?n:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function $t(c,e,t,r){if(t!=="postgres")return;let n=new Map;for(let s of Object.values(e))for(let o of Object.values(s.fields)){let a=o.getStorageFieldType();a.enumValues&&a.enumName&&n.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let s of Array.from(n.values())){let{name:o,values:a}=s;try{let i=a.map(u=>`'${u}'`).join(", ");await sql`
2
2
  DO $$ BEGIN
3
3
  CREATE TYPE ${sql.id(o)} AS ENUM (${sql.raw(i)});
4
4
  EXCEPTION
5
5
  WHEN duplicate_object THEN null;
6
6
  END $$;
7
- `.execute(c);}catch(i){r==null||r.warn("Could not create enum type",o,i);}}}function U(c,e){return c.some(t=>t.name===e)}function kt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function be(c,e){let[t]=e.split(".");return U(c,t)}function Te(c,e,t,r=false){let n=c;return e.unique&&(n=n.unique()),e.nullable||(n=n.notNull()),e.primary&&(n=n.primaryKey()),e.default!==void 0&&(n=n.defaultTo(e.default)),!r&&e.references&&be(t,e.references)&&(n=n.references(e.references)),n}function Dt(c,e,t,r,n){let s=[];for(let[o,a]of Object.entries(c.fields)){let i=e==null?void 0:e.columns.find(l=>l.name===o),u=a.getStorageFieldType();i?(i.dataType,u.type):(s.push({name:o,storageFieldType:u}),u.references&&!be(t,u.references)&&r.push({tableName:n,columnName:o,references:u.references}));}return s}function He(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function _t(c,e,t,r,n,s){if(t.length===0)return;let o=c.schema.createTable(e);for(let{name:a,storageFieldType:i}of t)if(He(i,n))o=o.addColumn(a,sql.raw(i.enumName),u=>Te(u,i,r));else {let u=Se(i,n);o=o.addColumn(a,u,l=>Te(l,i,r));}await o.execute().catch(a=>{if(!F(a))throw s==null||s.error("Error creating table",e,a),a});}async function Vt(c,e,t,r,n,s,o){for(let{name:a,storageFieldType:i}of t){let u=i.references?be(r,i.references):false,l=He(i,s)?sql.raw(i.enumName):Se(i,s);await c.schema.alterTable(e).addColumn(a,l,d=>Te(d,i,r,!u)).execute().catch(d=>{if(!F(d))throw o==null||o.error("Error adding column",a,d),d}),i.references&&!u&&!n.some(d=>d.tableName===e&&d.columnName===a)&&n.push({tableName:e,columnName:a,references:i.references}),i.index&&await c.schema.createIndex(`${e}_${a}_index`).on(e).column(a).execute().catch(()=>{});}}async function Bt(c,e,t,r,n,s){let o=`${e}_meta`,a=[];for(let[i,u]of Object.entries(t.fields)){let l=u.getStorageFieldType();kt(r,i)||a.push({name:i,storageFieldType:l});}if(!r&&a.length>0){let i=c.schema.createTable(o);for(let{name:u,storageFieldType:l}of a)i=i.addColumn(u,"varchar",d=>{let h=d;return l.primary&&(h=h.primaryKey(),U(n,e)&&(h=h.references(`${e}.${u}`))),h});await i.execute().catch(u=>{if(!F(u))throw s==null||s.error("Error creating meta table",o,u),u});}else if(r)for(let{name:i,storageFieldType:u}of a)await c.schema.alterTable(o).addColumn(i,"varchar",l=>{let d=l;return u.primary&&(d=d.primaryKey(),U(n,e)&&(d=d.references(`${e}.${i}`))),d}).execute().catch(l=>{if(!F(l))throw s==null||s.error("Error adding meta column",i,l),l});}async function Ke(c,e,t,r,n){let[s,o]=r.split("."),a=`${e}_${t}_fk`;try{await sql`
7
+ `.execute(c);}catch(i){r==null||r.warn("Could not create enum type",o,i);}}}function U(c,e){return c.some(t=>t.name===e)}function kt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function Se(c,e){let[t]=e.split(".");return U(c,t)}function Te(c,e,t,r=false){let n=c;return e.unique&&(n=n.unique()),e.nullable||(n=n.notNull()),e.primary&&(n=n.primaryKey()),e.default!==void 0&&(n=n.defaultTo(e.default)),!r&&e.references&&Se(t,e.references)&&(n=n.references(e.references)),n}function _t(c,e,t,r,n){let s=[];for(let[o,a]of Object.entries(c.fields)){let i=e==null?void 0:e.columns.find(l=>l.name===o),u=a.getStorageFieldType();i?(i.dataType,u.type):(s.push({name:o,storageFieldType:u}),u.references&&!Se(t,u.references)&&r.push({tableName:n,columnName:o,references:u.references}));}return s}function He(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function Dt(c,e,t,r,n,s){if(t.length===0)return;let o=c.schema.createTable(e);for(let{name:a,storageFieldType:i}of t)if(He(i,n))o=o.addColumn(a,sql.raw(i.enumName),u=>Te(u,i,r));else {let u=Re(i,n);o=o.addColumn(a,u,l=>Te(l,i,r));}await o.execute().catch(a=>{if(!F(a))throw s==null||s.error("Error creating table",e,a),a});}async function Vt(c,e,t,r,n,s,o){for(let{name:a,storageFieldType:i}of t){let u=i.references?Se(r,i.references):false,l=He(i,s)?sql.raw(i.enumName):Re(i,s);await c.schema.alterTable(e).addColumn(a,l,d=>Te(d,i,r,!u)).execute().catch(d=>{if(!F(d))throw o==null||o.error("Error adding column",a,d),d}),i.references&&!u&&!n.some(d=>d.tableName===e&&d.columnName===a)&&n.push({tableName:e,columnName:a,references:i.references}),i.index&&await c.schema.createIndex(`${e}_${a}_index`).on(e).column(a).execute().catch(()=>{});}}async function Bt(c,e,t,r,n,s){let o=`${e}_meta`,a=[];for(let[i,u]of Object.entries(t.fields)){let l=u.getStorageFieldType();kt(r,i)||a.push({name:i,storageFieldType:l});}if(!r&&a.length>0){let i=c.schema.createTable(o);for(let{name:u,storageFieldType:l}of a)i=i.addColumn(u,"varchar",d=>{let h=d;return l.primary&&(h=h.primaryKey(),U(n,e)&&(h=h.references(`${e}.${u}`))),h});await i.execute().catch(u=>{if(!F(u))throw s==null||s.error("Error creating meta table",o,u),u});}else if(r)for(let{name:i,storageFieldType:u}of a)await c.schema.alterTable(o).addColumn(i,"varchar",l=>{let d=l;return u.primary&&(d=d.primaryKey(),U(n,e)&&(d=d.references(`${e}.${i}`))),d}).execute().catch(l=>{if(!F(l))throw s==null||s.error("Error adding meta column",i,l),l});}async function Ke(c,e,t,r,n){let[s,o]=r.split("."),a=`${e}_${t}_fk`;try{await sql`
8
8
  ALTER TABLE ${sql.id(e)}
9
9
  ADD CONSTRAINT ${sql.id(a)}
10
10
  FOREIGN KEY (${sql.id(t)})
11
11
  REFERENCES ${sql.id(s)} (${sql.id(o)})
12
- `.execute(c);}catch(i){F(i)||n==null||n.warn("Could not add foreign key constraint",e,t,r,i);}}async function zt(c,e,t,r){for(let{tableName:n,columnName:s,references:o}of e){let a=t.find(l=>l.name===n),i=a==null?void 0:a.columns.find(l=>l.name===s),[u]=o.split(".");a&&i&&U(t,u)&&await Ke(c,n,s,o,r);}}async function Ft(c,e,t,r){for(let[n,s]of Object.entries(e)){let o=`${n}_meta`,a=t.find(i=>i.name===o);if(a)for(let[i,u]of Object.entries(s.fields)){let l=u.getStorageFieldType(),d=a.columns.find(h=>h.name===i);l.primary&&d&&U(t,n)&&await Ke(c,o,i,`${n}.${i}`,r);}}}async function Je(c,e,t){let r=C(c),n=await c.introspection.getTables(),s=[];await $t(c,e,r,t);for(let[a,i]of Object.entries(e)){let u=n.find(h=>h.name===a),l=n.find(h=>h.name===`${a}_meta`),d=Dt(i,u,n,s,a);if(u)for(let[h,y]of Object.entries(i.fields)){let m=u.columns.find(T=>T.name===h),p=y.getStorageFieldType(),f=Se(p,r);m&&m.dataType!==f&&(t==null||t.warn("Column type mismatch:",h,"expected to have type:",f,"but has type:",m.dataType));}!u&&d.length>0?await _t(c,a,d,n,r,t):u&&await Vt(c,a,d,n,s,r,t),await Bt(c,a,i,l,n,t);}let o=await c.introspection.getTables();await zt(c,s,o,t),await Ft(c,e,o,t);}function te(c,e,t,r){if(!c)throw new Error("Schema not initialized");let n=c[e];if(!n)throw new Error("Resource not found");let s=r.$or,o=r.$and;return (s?t.or:t.and)(s?r.$or.map(a=>te(c,e,t,a)):o?r.$and.map(a=>te(c,e,t,a)):Object.entries(r).map(([a,i])=>{var u,l;if(n.fields[a])return (i==null?void 0:i.$eq)!==void 0?t(`${e}.${a}`,i.$eq===null?"is":"=",i.$eq):(i==null?void 0:i.$in)!==void 0?t(`${e}.${a}`,"in",i.$in):(i==null?void 0:i.$not)!==void 0?((u=i==null?void 0:i.$not)==null?void 0:u.$in)!==void 0?t(`${e}.${a}`,"not in",i.$not.$in):((l=i==null?void 0:i.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${a}`,i.$not.$eq===null?"is not":"!=",i.$not.$eq):t(`${e}.${a}`,i.$not===null?"is not":"!=",i.$not):(i==null?void 0:i.$gt)!==void 0?t(`${e}.${a}`,">",i.$gt):(i==null?void 0:i.$gte)!==void 0?t(`${e}.${a}`,">=",i.$gte):(i==null?void 0:i.$lt)!==void 0?t(`${e}.${a}`,"<",i.$lt):(i==null?void 0:i.$lte)!==void 0?t(`${e}.${a}`,"<=",i.$lte):t(`${e}.${a}`,i===null?"is":"=",i);if(n.relations[a]){let d=n.relations[a],h=d.entity.name;return d.type==="many"?t.exists(ne(c,h,t.selectFrom(h).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),i)):te(c,h,t,i)}return null}).filter(Boolean))}function re(c,e,t,r){let n=c[e];if(!n)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let s of r.$and)t=re(c,e,t,s);return t}else if(r.$or){for(let s of r.$or)t=re(c,e,t,s);return t}for(let[s,o]of Object.entries(r)){if(!n.relations[s])continue;let a=n.relations[s],i=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,l=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(i,`${i}.${u}`,`${e}.${l}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=re(c,i,t,o));}return t}function ne(c,e,t,r){return !r||Object.keys(r).length===0?t:(t=re(c,e,t,r),t.where(n=>te(c,e,n,r)))}function Ut(c,e,t,r,n){let s=C(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function Wt(c,e,t,r,n){let s=C(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function ie(c,e,t,r,n,s){if(!r)return t;if(!c)throw new Error("Schema not initialized");let o=c[e];if(!o)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:a,jsonArrayFrom:i}=n;for(let u of Object.keys(r)){if(!o.relations[u])throw new Error(`Relation ${u} not found in resource ${e}`);let l=o.relations[u],d=l.entity.name,h=r[u],y=l.type==="one"?"id":l.foreignColumn,m=l.type==="one"?l.relationalColumn:"id",p=l.type==="one"?a:i,f=E(h)?h:null,T=f==null?void 0:f.include;t=t.select(g=>{let S=`${d}_meta`,b=Wt(g,c,d,d,s).whereRef(`${d}.${y}`,"=",`${e}.${m}`).select(R=>a(Ut(R,c,d,S,s).whereRef(`${S}.id`,"=",`${d}.id`)).as("_meta"));if(f!=null&&f.where&&(b=ne(c,d,b,f.where)),f!=null&&f.orderBy)for(let R of f.orderBy)b=b.orderBy(`${d}.${R.key}`,R.direction);return (f==null?void 0:f.limit)!==void 0&&(b=b.limit(f.limit)),T&&Object.keys(T).length>0&&(b=ie(c,d,b,T,n,s)),p(b).as(u)});}return t}var Re=class c extends z{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,r,n){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=We(this.db),this.schema=t,this.logger=r,this.server=n,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,r){this.schema=e,this.logger=t,this.server=r,await Je(this.db,e,t);}selectMetaColumns(e,t,r){var o;let n=C(this.db),s=(o=this.schema)==null?void 0:o[t];if(n==="sqlite"&&(s!=null&&s.fields)){let a=Object.keys(s.fields),i=e.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return e.selectFrom(r).selectAll(r)}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(i=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(i,e,n).whereRef(`${n}.id`,"=",`${e}.id`)).as("_meta"));s=ie(this.schema,e,s,r,this.dialectHelpers,this.db);let o=await s.executeTakeFirst();if(!o)return;let a=this.parseRelationalJsonStrings(o,e);return this.convertToMaterializedLiveType(a,e)}async findOne(e,t,r){let n=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(n)return z$2(n)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:n,limit:s,sort:o}=e,a=`${t}_meta`,i=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,a).whereRef(`${a}.id`,"=",`${t}.id`)).as("_meta"));i=ne(this.schema,t,i,r),i=ie(this.schema,t,i,n,this.dialectHelpers,this.db),s!==void 0&&(i=i.limit(s)),o!==void 0&&o.forEach(l=>{i=i.orderBy(l.key,l.direction);});let u=await i.execute();return u.length===0?[]:u.map(l=>{let d=this.parseRelationalJsonStrings(l,t);return this.convertToMaterializedLiveType(d,t)})}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(n=>z$2(n))}async rawInsert(e,t,r,n,s){var p,f,T,g,S,b,R;let o=(f=(p=this.server)==null?void 0:p.router)==null?void 0:f.getHooks(e),a=(T=this.schema)==null?void 0:T[e],[i,u]=((g=a==null?void 0:a.mergeMutation)==null?void 0:g.call(a,"set",r.value,void 0))??[r,r.value];if(!u)return {data:r,acceptedValues:null};let l=i,d={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let w=z$2(d);w.id=t;let x=await o.beforeInsert({ctx:s,value:w,rawValue:d,db:this});x&&(l=x);}let h={},y={};for(let[w,x]of Object.entries(l.value)){let O=(S=x._meta)==null?void 0:S.timestamp;if(!O)continue;let j=(R=(b=a==null?void 0:a.fields[w])==null?void 0:b.getStorageFieldType)==null?void 0:R.call(b);(j==null?void 0:j.type)==="jsonb"||(j==null?void 0:j.type)==="json"?h[w]=JSON.stringify(x.value):h[w]=x.value,y[w]=O;}await this.db.insertInto(e).values({...h,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute();let m=this.buildMutation(e,t,"INSERT",l,n);if(m&&this.trackMutation(m,l),o!=null&&o.afterInsert){let w={...l,value:{...l.value,id:{value:t}}},x=z$2(w);x.id=t,await o.afterInsert({ctx:s,value:x,rawValue:w,db:this});}return {data:l,acceptedValues:u}}async rawUpdate(e,t,r,n,s){var f,T,g,S,b,R,w;let o=(T=(f=this.server)==null?void 0:f.router)==null?void 0:T.getHooks(e),a=(g=this.schema)==null?void 0:g[e],i=await this.rawFindById(e,t),[u,l]=((S=a==null?void 0:a.mergeMutation)==null?void 0:S.call(a,"set",r.value,i))??[r,r.value];if(!l)return {data:r,acceptedValues:null};let d=u,h={...d,value:{...d.value,id:{value:t}}};if(o!=null&&o.beforeUpdate){let x=z$2(h);x.id=t;let O;if(i){let A={...i,value:{...i.value,id:{value:t}}};O=z$2(A),O.id=t;}let j=await o.beforeUpdate({ctx:s,value:x,rawValue:h,previousValue:O,previousRawValue:i,db:this});j&&(d=j);}let y={},m={};for(let[x,O]of Object.entries(d.value)){let j=(b=O._meta)==null?void 0:b.timestamp;if(!j)continue;let A=(w=(R=a==null?void 0:a.fields[x])==null?void 0:R.getStorageFieldType)==null?void 0:w.call(R);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[x]=JSON.stringify(O.value):y[x]=O.value,m[x]=j;}if(Object.keys(y).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...m,id:t}).onConflict(x=>x.column("id").doUpdateSet(m)).execute()]);let p=this.buildMutation(e,t,"UPDATE",d,n);if(p){let x=await this.rawFindById(e,t);x&&this.trackMutation(p,x);}if(o!=null&&o.afterUpdate){let x=await this.rawFindById(e,t);if(x){let O={...x,value:{...x.value,id:{value:t}}},j=z$2(O);j.id=t;let A;if(i){let Ze={...i,value:{...i.value,id:{value:t}}};A=z$2(Ze),A.id=t;}await o.afterUpdate({ctx:s,value:j,rawValue:O,previousValue:A,previousRawValue:i,db:this});}}return {data:d,acceptedValues:l}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let s=Math.random().toString(36).substring(2,15),o=this.mutationStack,a=[];this.mutationStack=a;let i=await this.db.savepoint(s).execute(),u=false,l=false;try{return await e({trx:this,commit:async()=>{await i.releaseSavepoint(s).execute(),u=!0,o.push(...a);},rollback:async()=>{await i.rollbackToSavepoint(s).execute(),l=!0,a.length=0;}}).then(d=>i.isCommitted||i.isRolledBack||u||l?d:i.releaseSavepoint(s).execute().then(()=>(o.push(...a),d)))}catch(d){throw l||await i.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,d}finally{this.mutationStack=o;}}let t=[],r=this.mutationStack;this.mutationStack=t;let n=await this.db.startTransaction().execute();try{let s=new c(n,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{await n.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await n.rollback().execute(),t.length=0;}}).then(o=>n.isCommitted||n.isRolledBack?o:n.commit().execute().then(()=>(this.notifyMutations(t),o)))}catch(s){throw await n.rollback().execute(),t.length=0,s}finally{this.mutationStack=r;}}get internalDB(){return this.db}isRelationalField(e,t){var n;if(!this.schema)return false;let r=this.schema[e];return !!((n=r==null?void 0:r.relations)!=null&&n[t])}parseRelationalJsonStrings(e,t){var s,o;if(C(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(a=>this.parseRelationalJsonStrings(a,t));let n={};for(let[a,i]of Object.entries(e))if(a==="_meta"&&typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{n[a]=JSON.parse(i);}catch{n[a]=i;}else n[a]=i;else if(this.isRelationalField(t,a))if(typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let u=JSON.parse(i);if(this.schema){let l=this.schema[t],d=(s=l==null?void 0:l.relations)==null?void 0:s[a];if(d){let h=d.entity.name;n[a]=this.parseRelationalJsonStrings(u,h);}else n[a]=u;}else n[a]=u;}catch{n[a]=i;}else n[a]=i;else if(typeof i=="object"&&i!==null&&!Array.isArray(i))if(this.schema){let u=this.schema[t],l=(o=u==null?void 0:u.relations)==null?void 0:o[a];if(l){let d=l.entity.name;n[a]=this.parseRelationalJsonStrings(i,d);}else n[a]=i;}else n[a]=i;else Array.isArray(i)?n[a]=i.map(u=>{var l,d;if(typeof u=="string")try{let h=JSON.parse(u);if(this.schema){let y=this.schema[t],m=(l=y==null?void 0:y.relations)==null?void 0:l[a];if(m){let p=m.entity.name;return this.parseRelationalJsonStrings(h,p)}}return h}catch{return u}if(typeof u=="object"&&u!==null&&this.schema){let h=this.schema[t],y=(d=h==null?void 0:h.relations)==null?void 0:d[a];if(y){let m=y.entity.name;return this.parseRelationalJsonStrings(u,m)}}return u}):n[a]=i;else n[a]=i;return n}convertToMaterializedLiveType(e,t){var n;let r=(n=this.schema)==null?void 0:n[t];return {value:Object.entries(e).reduce((s,[o,a])=>{var d,h,y,m,p,f,T,g,S;if(o==="_meta")return s;let i=(h=(d=r==null?void 0:r.fields[o])==null?void 0:d.getStorageFieldType)==null?void 0:h.call(d),u=(i==null?void 0:i.type)==="jsonb"||(i==null?void 0:i.type)==="json",l=(r==null?void 0:r.relations)&&o in r.relations;if(o==="id")s[o]={value:a};else if(u)s[o]={value:a,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[o]}};else if(l){let b=r.relations[o].entity,R=(b==null?void 0:b.name)??t;Array.isArray(a)?s[o]={value:a.map(w=>this.convertToMaterializedLiveType(w,R)),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}}:a!==null&&typeof a=="object"?s[o]={...this.convertToMaterializedLiveType(a,R),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:s[o]={value:a,_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[o],relation:true}};}else Array.isArray(a)?s[o]={value:a,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[o]}}:typeof a=="object"&&a!==null&&!(a instanceof Date)?s[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[o]}}:s[o]={value:a,_meta:{timestamp:(S=e==null?void 0:e._meta)==null?void 0:S[o]}};return s},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",s=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||s&&o}buildMutation(e,t,r,n,s){var a;let o={};for(let[i,u]of Object.entries(n.value)){if(i==="id")continue;let l=(a=u._meta)==null?void 0:a.timestamp;l&&(o[i]={value:u.value,_meta:{timestamp:l}});}return Object.keys(o).length===0?null:{id:s??J(),type:"MUTATE",resource:e,resourceId:t,procedure:r,payload:o}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let r=e;for(let n of r)this.server.notifySubscribers(n,t);}else {let r=e;for(let{mutation:n,entityData:s}of r)this.server.notifySubscribers(n,s);}}};var we=class c{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G$1({level:e.logLevel??F$1.INFO}),(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new Z({router:{get:async(r,n)=>{var d;let{headers:s,cookies:o,queryParams:a,context:i}=(n==null?void 0:n.context)??{};if(!(n!=null&&n.batcher))throw new Error("Batcher is required");let u={...r,type:"QUERY",headers:s,cookies:o,queryParams:a,context:i},l=await((d=this.router.routes[r.resource])==null?void 0:d.handleQuery({req:u,batcher:n.batcher}));return (l==null?void 0:l.data)??[]},incrementQueryStep:(r,n={})=>{var a;let s=(a=this.router.routes[r.query.resource])==null?void 0:a.getAuthorizationClause({...r.query,type:"QUERY",headers:n.headers,cookies:n.cookies,queryParams:n.queryParams,context:n.context});if(typeof s=="boolean"&&!s)throw new Error("Not authorized");let o=D(r.query.where,typeof s=="object"?s:void 0);return {...r,query:{...r.query,where:o}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:r,cookies:n,queryParams:s,context:o,...a}=t,i={headers:r,cookies:n,queryParams:s,context:o},u=e.subscription?this.queryEngine.subscribe(a,d=>{var h;(h=e.subscription)==null||h.call(e,d);},i):void 0;return {data:await this.queryEngine.get(a,{context:i}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){let t=await this.wrapInMiddlewares(async h=>{let y=this.router.routes[h.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:h,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:n,cookies:s,queryParams:o,context:a}=e.req,i={headers:n,cookies:s,queryParams:o,context:a},u=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(u,h=>{var y;(y=e.subscription)==null||y.call(e,h);},i):void 0,d=await this.queryEngine.get(u,{context:i});return e.subscription?{data:d,unsubscribe:l,query:u}:d.map(h=>z$2(h))}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},Rn=we.create;export{fe as ProcedureRoute,me as Route,ge as RouteFactory,pe as Router,Re as SQLStorage,we as Server,z as Storage,$ as createServerDB,Lr as expressAdapter,Fr as routeFactory,zr as router,Rn as server};
12
+ `.execute(c);}catch(i){F(i)||n==null||n.warn("Could not add foreign key constraint",e,t,r,i);}}async function zt(c,e,t,r){for(let{tableName:n,columnName:s,references:o}of e){let a=t.find(l=>l.name===n),i=a==null?void 0:a.columns.find(l=>l.name===s),[u]=o.split(".");a&&i&&U(t,u)&&await Ke(c,n,s,o,r);}}async function Ft(c,e,t,r){for(let[n,s]of Object.entries(e)){let o=`${n}_meta`,a=t.find(i=>i.name===o);if(a)for(let[i,u]of Object.entries(s.fields)){let l=u.getStorageFieldType(),d=a.columns.find(h=>h.name===i);l.primary&&d&&U(t,n)&&await Ke(c,o,i,`${n}.${i}`,r);}}}async function Je(c,e,t){let r=P(c),n=await c.introspection.getTables(),s=[];await $t(c,e,r,t);for(let[a,i]of Object.entries(e)){let u=n.find(h=>h.name===a),l=n.find(h=>h.name===`${a}_meta`),d=_t(i,u,n,s,a);if(u)for(let[h,y]of Object.entries(i.fields)){let m=u.columns.find(T=>T.name===h),p=y.getStorageFieldType(),f=Re(p,r);m&&m.dataType!==f&&(t==null||t.warn("Column type mismatch:",h,"expected to have type:",f,"but has type:",m.dataType));}!u&&d.length>0?await Dt(c,a,d,n,r,t):u&&await Vt(c,a,d,n,s,r,t),await Bt(c,a,i,l,n,t);}let o=await c.introspection.getTables();await zt(c,s,o,t),await Ft(c,e,o,t);}function te(c,e,t,r){if(!c)throw new Error("Schema not initialized");let n=c[e];if(!n)throw new Error("Resource not found");let s=r.$or,o=r.$and;return (s?t.or:t.and)(s?r.$or.map(a=>te(c,e,t,a)):o?r.$and.map(a=>te(c,e,t,a)):Object.entries(r).map(([a,i])=>{var u,l;if(n.fields[a])return (i==null?void 0:i.$eq)!==void 0?t(`${e}.${a}`,i.$eq===null?"is":"=",i.$eq):(i==null?void 0:i.$in)!==void 0?t(`${e}.${a}`,"in",i.$in):(i==null?void 0:i.$not)!==void 0?((u=i==null?void 0:i.$not)==null?void 0:u.$in)!==void 0?t(`${e}.${a}`,"not in",i.$not.$in):((l=i==null?void 0:i.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${a}`,i.$not.$eq===null?"is not":"!=",i.$not.$eq):t(`${e}.${a}`,i.$not===null?"is not":"!=",i.$not):(i==null?void 0:i.$gt)!==void 0?t(`${e}.${a}`,">",i.$gt):(i==null?void 0:i.$gte)!==void 0?t(`${e}.${a}`,">=",i.$gte):(i==null?void 0:i.$lt)!==void 0?t(`${e}.${a}`,"<",i.$lt):(i==null?void 0:i.$lte)!==void 0?t(`${e}.${a}`,"<=",i.$lte):t(`${e}.${a}`,i===null?"is":"=",i);if(n.relations[a]){let d=n.relations[a],h=d.entity.name;return d.type==="many"?t.exists(ne(c,h,t.selectFrom(h).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),i)):te(c,h,t,i)}return null}).filter(Boolean))}function re(c,e,t,r){let n=c[e];if(!n)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let s of r.$and)t=re(c,e,t,s);return t}else if(r.$or){for(let s of r.$or)t=re(c,e,t,s);return t}for(let[s,o]of Object.entries(r)){if(!n.relations[s])continue;let a=n.relations[s],i=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,l=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(i,`${i}.${u}`,`${e}.${l}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=re(c,i,t,o));}return t}function ne(c,e,t,r){return !r||Object.keys(r).length===0?t:(t=re(c,e,t,r),t.where(n=>te(c,e,n,r)))}function Ut(c,e,t,r,n){let s=P(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function Wt(c,e,t,r,n){let s=P(n),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),i=c.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return c.selectFrom(r).selectAll(r)}function ie(c,e,t,r,n,s){if(!r)return t;if(!c)throw new Error("Schema not initialized");let o=c[e];if(!o)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:a,jsonArrayFrom:i}=n;for(let u of Object.keys(r)){if(!o.relations[u])throw new Error(`Relation ${u} not found in resource ${e}`);let l=o.relations[u],d=l.entity.name,h=r[u],y=l.type==="one"?"id":l.foreignColumn,m=l.type==="one"?l.relationalColumn:"id",p=l.type==="one"?a:i,f=E(h)?h:null,T=f==null?void 0:f.include;t=t.select(g=>{let R=`${d}_meta`,S=Wt(g,c,d,d,s).whereRef(`${d}.${y}`,"=",`${e}.${m}`).select(b=>a(Ut(b,c,d,R,s).whereRef(`${R}.id`,"=",`${d}.id`)).as("_meta"));if(f!=null&&f.where&&(S=ne(c,d,S,f.where)),f!=null&&f.orderBy)for(let b of f.orderBy)S=S.orderBy(`${d}.${b.key}`,b.direction);return (f==null?void 0:f.limit)!==void 0&&(S=S.limit(f.limit)),T&&Object.keys(T).length>0&&(S=ie(c,d,S,T,n,s)),p(S).as(u)});}return t}var be=class c extends z{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,r,n){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=We(this.db),this.schema=t,this.logger=r,this.server=n,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,r){this.schema=e,this.logger=t,this.server=r,await Je(this.db,e,t);}selectMetaColumns(e,t,r){var o;let n=P(this.db),s=(o=this.schema)==null?void 0:o[t];if(n==="sqlite"&&(s!=null&&s.fields)){let a=Object.keys(s.fields),i=e.selectFrom(r);for(let u of a)i=i.select(`${r}.${u}`);return i}return e.selectFrom(r).selectAll(r)}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(i=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(i,e,n).whereRef(`${n}.id`,"=",`${e}.id`)).as("_meta"));s=ie(this.schema,e,s,r,this.dialectHelpers,this.db);let o=await s.executeTakeFirst();if(!o)return;let a=this.parseRelationalJsonStrings(o,e);return this.convertToMaterializedLiveType(a,e)}async findOne(e,t,r){let n=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(n)return z$2(n)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:n,limit:s,sort:o}=e,a=`${t}_meta`,i=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,a).whereRef(`${a}.id`,"=",`${t}.id`)).as("_meta"));i=ne(this.schema,t,i,r),i=ie(this.schema,t,i,n,this.dialectHelpers,this.db),s!==void 0&&(i=i.limit(s)),o!==void 0&&o.forEach(l=>{i=i.orderBy(l.key,l.direction);});let u=await i.execute();return u.length===0?[]:u.map(l=>{let d=this.parseRelationalJsonStrings(l,t);return this.convertToMaterializedLiveType(d,t)})}async find(e,t){return (await this.get({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort})).map(n=>z$2(n))}async rawInsert(e,t,r,n,s){var p,f,T,g,R,S,b;let o=(f=(p=this.server)==null?void 0:p.router)==null?void 0:f.getHooks(e),a=(T=this.schema)==null?void 0:T[e],[i,u]=((g=a==null?void 0:a.mergeMutation)==null?void 0:g.call(a,"set",r.value,void 0))??[r,r.value];if(!u)return {data:r,acceptedValues:null};let l=i,d={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let w=z$2(d);w.id=t;let v=await o.beforeInsert({ctx:s,value:w,rawValue:d,db:this});v&&(l=v);}let h={},y={};for(let[w,v]of Object.entries(l.value)){let j=(R=v._meta)==null?void 0:R.timestamp;if(!j)continue;let C=(b=(S=a==null?void 0:a.fields[w])==null?void 0:S.getStorageFieldType)==null?void 0:b.call(S);(C==null?void 0:C.type)==="jsonb"||(C==null?void 0:C.type)==="json"?h[w]=JSON.stringify(v.value):h[w]=v.value,y[w]=j;}await this.db.insertInto(e).values({...h,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute();let m=this.buildMutation(e,t,"INSERT",l,n);if(m&&this.trackMutation(m,l),o!=null&&o.afterInsert){let w={...l,value:{...l.value,id:{value:t}}},v=z$2(w);v.id=t,await o.afterInsert({ctx:s,value:v,rawValue:w,db:this});}return {data:l,acceptedValues:u}}async rawUpdate(e,t,r,n,s){var f,T,g,R,S,b,w;let o=(T=(f=this.server)==null?void 0:f.router)==null?void 0:T.getHooks(e),a=(g=this.schema)==null?void 0:g[e],i=await this.rawFindById(e,t),[u,l]=((R=a==null?void 0:a.mergeMutation)==null?void 0:R.call(a,"set",r.value,i))??[r,r.value];if(!l)return {data:r,acceptedValues:null};let d=u,h={...d,value:{...d.value,id:{value:t}}};if(o!=null&&o.beforeUpdate){let v=z$2(h);v.id=t;let j;if(i){let O={...i,value:{...i.value,id:{value:t}}};j=z$2(O),j.id=t;}let C=await o.beforeUpdate({ctx:s,value:v,rawValue:h,previousValue:j,previousRawValue:i,db:this});C&&(d=C);}let y={},m={};for(let[v,j]of Object.entries(d.value)){let C=(S=j._meta)==null?void 0:S.timestamp;if(!C)continue;let O=(w=(b=a==null?void 0:a.fields[v])==null?void 0:b.getStorageFieldType)==null?void 0:w.call(b);(O==null?void 0:O.type)==="jsonb"||(O==null?void 0:O.type)==="json"?y[v]=JSON.stringify(j.value):y[v]=j.value,m[v]=C;}if(Object.keys(y).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...m,id:t}).onConflict(v=>v.column("id").doUpdateSet(m)).execute()]);let p=this.buildMutation(e,t,"UPDATE",d,n);if(p){let v=await this.rawFindById(e,t);v&&this.trackMutation(p,v);}if(o!=null&&o.afterUpdate){let v=await this.rawFindById(e,t);if(v){let j={...v,value:{...v.value,id:{value:t}}},C=z$2(j);C.id=t;let O;if(i){let Ze={...i,value:{...i.value,id:{value:t}}};O=z$2(Ze),O.id=t;}await o.afterUpdate({ctx:s,value:C,rawValue:j,previousValue:O,previousRawValue:i,db:this});}}return {data:d,acceptedValues:l}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let s=Math.random().toString(36).substring(2,15),o=this.mutationStack,a=[];this.mutationStack=a;let i=await this.db.savepoint(s).execute(),u=false,l=false;try{return await e({trx:this,commit:async()=>{await i.releaseSavepoint(s).execute(),u=!0,o.push(...a);},rollback:async()=>{await i.rollbackToSavepoint(s).execute(),l=!0,a.length=0;}}).then(d=>i.isCommitted||i.isRolledBack||u||l?d:i.releaseSavepoint(s).execute().then(()=>(o.push(...a),d)))}catch(d){throw l||await i.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,d}finally{this.mutationStack=o;}}let t=[],r=this.mutationStack;this.mutationStack=t;let n=await this.db.startTransaction().execute();try{let s=new c(n,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{await n.commit().execute(),this.notifyMutations(t);},rollback:async()=>{await n.rollback().execute(),t.length=0;}}).then(o=>n.isCommitted||n.isRolledBack?o:n.commit().execute().then(()=>(this.notifyMutations(t),o)))}catch(s){throw await n.rollback().execute(),t.length=0,s}finally{this.mutationStack=r;}}get internalDB(){return this.db}isRelationalField(e,t){var n;if(!this.schema)return false;let r=this.schema[e];return !!((n=r==null?void 0:r.relations)!=null&&n[t])}parseRelationalJsonStrings(e,t){var s,o;if(P(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(a=>this.parseRelationalJsonStrings(a,t));let n={};for(let[a,i]of Object.entries(e))if(a==="_meta"&&typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{n[a]=JSON.parse(i);}catch{n[a]=i;}else n[a]=i;else if(this.isRelationalField(t,a))if(typeof i=="string")if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let u=JSON.parse(i);if(this.schema){let l=this.schema[t],d=(s=l==null?void 0:l.relations)==null?void 0:s[a];if(d){let h=d.entity.name;n[a]=this.parseRelationalJsonStrings(u,h);}else n[a]=u;}else n[a]=u;}catch{n[a]=i;}else n[a]=i;else if(typeof i=="object"&&i!==null&&!Array.isArray(i))if(this.schema){let u=this.schema[t],l=(o=u==null?void 0:u.relations)==null?void 0:o[a];if(l){let d=l.entity.name;n[a]=this.parseRelationalJsonStrings(i,d);}else n[a]=i;}else n[a]=i;else Array.isArray(i)?n[a]=i.map(u=>{var l,d;if(typeof u=="string")try{let h=JSON.parse(u);if(this.schema){let y=this.schema[t],m=(l=y==null?void 0:y.relations)==null?void 0:l[a];if(m){let p=m.entity.name;return this.parseRelationalJsonStrings(h,p)}}return h}catch{return u}if(typeof u=="object"&&u!==null&&this.schema){let h=this.schema[t],y=(d=h==null?void 0:h.relations)==null?void 0:d[a];if(y){let m=y.entity.name;return this.parseRelationalJsonStrings(u,m)}}return u}):n[a]=i;else n[a]=i;return n}convertToMaterializedLiveType(e,t){var n;let r=(n=this.schema)==null?void 0:n[t];return {value:Object.entries(e).reduce((s,[o,a])=>{var d,h,y,m,p,f,T,g,R;if(o==="_meta")return s;let i=(h=(d=r==null?void 0:r.fields[o])==null?void 0:d.getStorageFieldType)==null?void 0:h.call(d),u=(i==null?void 0:i.type)==="jsonb"||(i==null?void 0:i.type)==="json",l=(r==null?void 0:r.relations)&&o in r.relations;if(o==="id")s[o]={value:a};else if(u)s[o]={value:a,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[o]}};else if(l){let S=r.relations[o].entity,b=(S==null?void 0:S.name)??t;Array.isArray(a)?s[o]={value:a.map(w=>this.convertToMaterializedLiveType(w,b)),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}}:a!==null&&typeof a=="object"?s[o]={...this.convertToMaterializedLiveType(a,b),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:s[o]={value:a,_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[o],relation:true}};}else Array.isArray(a)?s[o]={value:a,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[o]}}:typeof a=="object"&&a!==null&&!(a instanceof Date)?s[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[o]}}:s[o]={value:a,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[o]}};return s},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",s=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||s&&o}buildMutation(e,t,r,n,s){var a;let o={};for(let[i,u]of Object.entries(n.value)){if(i==="id")continue;let l=(a=u._meta)==null?void 0:a.timestamp;l&&(o[i]={value:u.value,_meta:{timestamp:l}});}return Object.keys(o).length===0?null:{id:s??J(),type:"MUTATE",resource:e,resourceId:t,procedure:r,payload:o}}trackMutation(e,t){this.db.isTransaction?this.mutationStack.push({mutation:e,entityData:t}):this.notifyMutations([e],t);}notifyMutations(e,t){if(this.server)if(t!==void 0){let r=e;for(let n of r)this.server.notifySubscribers(n,t);}else {let r=e;for(let{mutation:n,entityData:s}of r)this.server.notifySubscribers(n,s);}}};var we=class c{router;storage;schema;middlewares=new Set;logger;contextProvider;queryEngine;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G$1({level:e.logLevel??F$1.INFO}),(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger,this),this.contextProvider=e.contextProvider,this.queryEngine=new Z({router:{get:async(r,n)=>{var d;let{headers:s,cookies:o,queryParams:a,context:i}=(n==null?void 0:n.context)??{};if(!(n!=null&&n.batcher))throw new Error("Batcher is required");let u={...r,type:"QUERY",headers:s,cookies:o,queryParams:a,context:i},l=await((d=this.router.routes[r.resource])==null?void 0:d.handleQuery({req:u,batcher:n.batcher}));return (l==null?void 0:l.data)??[]},incrementQueryStep:(r,n={})=>{var a;let s=(a=this.router.routes[r.query.resource])==null?void 0:a.getAuthorizationClause({...r.query,type:"QUERY",headers:n.headers,cookies:n.cookies,queryParams:n.queryParams,context:n.context});if(typeof s=="boolean"&&!s)throw new Error("Not authorized");let o=_(r.query.where,typeof s=="object"?s:void 0);return {...r,query:{...r.query,where:o}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}handleQuery(e){return this.wrapInMiddlewares(async t=>{let{headers:r,cookies:n,queryParams:s,context:o,...a}=t,i={headers:r,cookies:n,queryParams:s,context:o},u=e.subscription?this.queryEngine.subscribe(a,d=>{var h;(h=e.subscription)==null||h.call(e,d);},i):void 0;return {data:await this.queryEngine.get(a,{context:i}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){let t=await this.wrapInMiddlewares(async h=>{let y=this.router.routes[h.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:h,db:this.storage,schema:this.schema})})(e.req);if(!(typeof t=="object"&&t!==null&&"buildQueryRequest"in t&&typeof t.buildQueryRequest=="function")){if(e.subscription)throw new Error("Subscriptions require custom queries to return a QueryBuilder");return t}let{headers:n,cookies:s,queryParams:o,context:a}=e.req,i={headers:n,cookies:s,queryParams:o,context:a},u=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(u,h=>{var y;(y=e.subscription)==null||y.call(e,h);},i):void 0,d=await this.queryEngine.get(u,{context:i});return e.subscription?{data:d,unsubscribe:l,query:u}:d.map(h=>z$2(h))}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}notifySubscribers(e,t){this.queryEngine.handleMutation(e,t);}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>s=>n({req:s,next:r}),e)(t)}},wn=we.create;export{fe as ProcedureRoute,me as Route,ge as RouteFactory,pe as Router,be as SQLStorage,we as Server,z as Storage,Fr as createMiddleware,$ as createServerDB,Lr as expressAdapter,Ur as routeFactory,zr as router,wn as server};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@live-state/sync",
3
- "version": "0.0.7-canary-3",
3
+ "version": "0.0.7-canary-4",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"