@live-state/sync 0.0.7-pr-1 → 0.0.7-pr-3
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/client.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { B as BootstrapStatusChangeEvent, F as Client, A as ClientBootstrapStatus, E as ClientEvents, C as ClientOptions, a as ClientRouterConstraint, l as ClientState, p as ClientStorageLoadedEvent, o as ConnectionStateChangeEvent, q as DataLoadReplyEvent, D as DataLoadRequestedEvent, M as MessageReceivedEvent, s as MutationReceivedEvent, t as MutationRejectedEvent, r as MutationSentEvent, e as OptimisticHandlerContext, y as OptimisticMutationAppliedEvent, z as OptimisticMutationUndoneEvent, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, Q as QueryExecutedEvent, w as QuerySubscriptionTriggeredEvent, x as StoreStateUpdatedEvent, S as SubscriptionCreatedEvent, v as SubscriptionRemovedEvent, G as createClient, d as defineOptimisticMutations, m as useClientState, u as useLiveQuery, n as useLoadData } from './index-C0Qm5yHg.js';
|
|
2
2
|
import '@standard-schema/spec';
|
|
3
3
|
import 'zod';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,a,b,f as f$1,e,c}from'./chunk-LSAVBBUS.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z}from'zod';import {stringify}from'qs';import Se from'fast-deep-equal';import {openDB}from'idb';var f=p=>xxHash32(JSON.stringify(p)).toString(32);var S=(p,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>S(p,n,t));if(i==="$or")return s.some(n=>S(p,n,t));let r=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let o=p[i];return o===void 0?false:t?!s.$in.includes(o):s.$in.includes(o)}if(s.$not!==void 0&&!t)return S(p,{[i]:s.$not},true);if(s.$gt!==void 0){let o=p[i];return typeof o!="number"?false:t?o<=s.$gt:o>s.$gt}if(s.$gte!==void 0){let o=p[i];return typeof o!="number"?false:t?o<s.$gte:o>=s.$gte}if(s.$lt!==void 0){let o=p[i];return typeof o!="number"?false:t?o>=s.$lt:o<s.$lt}if(s.$lte!==void 0){let o=p[i];return typeof o!="number"?false:t?o>s.$lte:o<=s.$lte}let n=p[i];return !n||typeof n!="object"&&!Array.isArray(n)?false:Array.isArray(n)?t?!n.some(o=>S(o,s,false)):n.some(o=>S(o,s,false)):S(n,s,t)}return t?p[i]!==r:p[i]===r}),C=p=>{if(typeof p!="object"||p===null)return false;let e=p;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},E={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},U=class{level;prefix;constructor(e={}){this.level=e.level??E.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=E.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=E.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=E.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=E.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=E.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},F=p=>new U(p);var Q=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=f(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let s={subscribe:r=>{let n=this.subscriptions.get(i);return n.callbacks.add(r),n.unsubscribe||(n.unsubscribe=()=>{},n.unsubscribe=e.subscribe(()=>{n.callbacks.forEach(o=>{o();});})),()=>{var o;(o=this.subscriptions.get(i))==null||o.callbacks.delete(r),setTimeout(()=>{var c;let a=this.subscriptions.get(i);a&&a.callbacks.size===0&&((c=a.unsubscribe)==null||c.call(a),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,s),this.subscriptions.get(i).subscribe}},le=new Q,Ce=p=>useSyncExternalStore(le.getOrStoreSubscription(p),p.get),Ie=(p,e)=>{useEffect(()=>{let t=p.load(e.buildQueryRequest());return ()=>{t();}},[e,p.load]);};var J=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.coerce.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),_=z.record(z.string(),z.object({value:z.any().nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})),de=_.superRefine((p,e)=>{p.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),X=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),Z=z.object({timestamp:z.string().optional(),originMutationId:z.string().optional()}).optional(),N=X.extend({procedure:z.string(),payload:z.any().optional(),meta:Z}),W=X.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:de,meta:Z});z.union([W,N]);var ee=z.object({resource:z.string(),procedure:z.string(),input:z.any().optional()});var R=z.string(),q=z.union([ee,J]),pe=z.object({id:R,type:z.literal("SUBSCRIBE")}).and(q),he=z.object({id:R,type:z.literal("UNSUBSCRIBE")}).and(q),ye=z.object({id:R,type:z.literal("QUERY")}).and(q),me=z.object({id:R,type:z.literal("CUSTOM_QUERY"),resource:z.string(),procedure:z.string(),input:z.any().optional()}),te=W.extend({id:R}),ge=N.extend({id:R}),fe=z.union([ge,te]);z.union([pe,ye,me,fe,he]);var be=z.object({id:R,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),Me=z.object({id:R,type:z.literal("REPLY"),data:z.any()}),ie=z.union([be,Me,te]),se=z.object({resource:z.string(),data:z.array(_)});var x=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await c(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t);}removeEventListener(e,t){var i;this.eventListeners.has(e)&&((i=this.eventListeners.get(e))==null||i.delete(t));}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){var t,i;this.dispatchEvent("error",e),this.dispatchEvent("connectionChange",{open:false}),(i=(t=e.error)==null?void 0:t.message)!=null&&i.includes("non-101")&&(this.ws&&(this.ws.close(),this.ws=null),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect());}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){var i;(i=this.eventListeners.get(e))==null||i.forEach(s=>{s(t);});}};var k=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let r=s.referencedBy.get(i.type);r&&r instanceof Set?r.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let r=this.nodes.get(s);if(!r)return;let n=r.referencedBy.get(i.type);n&&(n instanceof Set?n.delete(e):r.referencedBy.delete(i.type),this.notifySubscribers(s)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,s])=>{(s instanceof Set?Array.from(s.values()):[s]).forEach(n=>{let o=this.nodes.get(n);!o||!o.references.get(i)||(o.references.delete(i),this.notifySubscribers(n));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(r){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var B="__meta",j="databases",L=class{db;async init(e,t){var c,d;if(typeof window>"u")return;let s=((c=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:c.version)??1,r=await f(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,l])=>[u,await f(l)]))),o=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(j)||u.createObjectStore(j);}}),a=(d=await this.getAll(o,j))==null?void 0:d[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),B].forEach(l=>{(a==null?void 0:a.objectHashes[l])!==n[l]&&u.objectStoreNames.contains(l)&&u.deleteObjectStore(l),u.objectStoreNames.contains(l)||u.createObjectStore(l);}),await o.put(j,{schemaHash:r,objectHashes:n},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var s;return (s=this.db)==null?void 0:s.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(B,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(B,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((r,n)=>[s[n],r]))}};var P=class{constructor(e,t,i,s,r,n){this.schema=e;this.logger=i,this.optimisticObjGraph=new k(i),this.kvStorage=new L,this.onQuerySubscriptionTriggered=n,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([o,a,c])=>{o&&Object.keys(o).length>0&&(this.optimisticMutationStack=o),a&&a.length>0&&(this.customMutationStack=a),c&&Object.keys(c).length>0&&(this.customMutationIndex=c),s==null||s(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([o])=>{this.kvStorage.get(o).then(a=>{if(!a||Object.keys(a).length===0){r==null||r(o,0);return}let c=Object.entries(a).map(([d,u])=>({...u,id:{value:d}}));r==null||r(o,c.length),this.loadConsolidatedState(o,c);});});}).catch(o=>{i.debug("Storage initialization failed (may not be available in this environment):",o);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var a;let s=t??f(e$1);if(this.querySnapshots[s]&&!i){let c=this.querySnapshots[s];if(c)return c}let r,n=(a=e$1.where)==null?void 0:a.id;n===void 0?r=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):typeof n=="string"?r=[n]:typeof n=="object"&&n!==null?"$in"in n&&Array.isArray(n.$in)?r=n.$in:"$eq"in n&&typeof n.$eq=="string"?r=[n.$eq]:r=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):r=Object.keys(this.optimisticRawObjPool[e$1.resource]??{});let o=r.flatMap(c=>{let d=f$1(this.materializeOneWithInclude(c,e$1.include));return d?[d]:[]});if(e$1.sort&&e$1.sort.length>0){let c=(d,u)=>{for(let l of e$1.sort){let m=d[l.key],g=u[l.key];if(m<g)return l.direction==="asc"?-1:1;if(m>g)return l.direction==="asc"?1:-1}return 0};o.sort(c);}if(e$1.where||e$1.limit){let c=e$1.where?d=>S(d,e$1.where):()=>true;o=e(o,c,e$1.limit);}return !i&&this.collectionSubscriptions.has(s)&&(this.querySnapshots[s]=o),o}subscribe(e,t){var r;let i=f(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var n,o;(n=this.collectionSubscriptions.get(i))==null||n.callbacks.delete(t),((o=this.collectionSubscriptions.get(i))==null?void 0:o.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,o,a,c,d,u,l;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let r=(n=this.optimisticRawObjPool[e])==null?void 0:n[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(o=this.optimisticMutationStack)==null?void 0:o[e])==null?void 0:a.filter(I=>I.id!==t.id))??[];let m=(c=t.meta)==null?void 0:c.originMutationId;if(this.logger.debug("Broadcast mutation received",{mutationId:t.id,resource:e,resourceId:t.resourceId,procedure:t.procedure,originMutationId:m??"(none)",customMutationIndexKeys:Object.keys(this.customMutationIndex),optimisticStackSize:((d=this.optimisticMutationStack[e])==null?void 0:d.length)??0}),m&&this.customMutationIndex[m]){let w=this.customMutationIndex[m].filter(M=>M.resource===e),T=false;for(let M of w){let O=(u=this.optimisticMutationStack[e])==null?void 0:u.find(A=>A.id===M.mutationId);if(O&&O.resourceId===t.resourceId&&O.procedure===t.procedure){this.logger.debug("Removing optimistic mutation (resourceId match)",{optimisticMutationId:M.mutationId,resourceId:t.resourceId}),this.undoMutation(e,M.mutationId),T=true;break}}if(!T)for(let M of w){let O=(l=this.optimisticMutationStack[e])==null?void 0:l.find(A=>A.id===M.mutationId&&A.procedure===t.procedure);if(O){this.logger.debug("Removing optimistic mutation (resource+procedure fallback)",{optimisticMutationId:M.mutationId,optimisticResourceId:O.resourceId,broadcastResourceId:t.resourceId}),this.undoMutation(e,M.mutationId),T=true;break}}}this.rawObjPool[e]??={};let g={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=g;let b=g.value;delete b.id,this.kvStorage.set(e,t.resourceId,b);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,r);}undoMutation(e,t){var n,o;if(!this.optimisticMutationStack[e])return;let i=(n=this.optimisticMutationStack[e])==null?void 0:n.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let r=(o=this.optimisticRawObjPool[e])==null?void 0:o[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),r);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){var i;let t=this.customMutationIndex[e];if(this.logger.debug("confirmCustomMutation called",{messageId:e,hasIndex:!!t,mutations:t??[]}),!!t){for(let{resource:s,mutationId:r}of t){let n=!!((i=this.optimisticMutationStack[s])!=null&&i.find(o=>o.id===r));this.logger.debug("confirmCustomMutation: undoing mutation",{resource:s,mutationId:r,stillInStack:n}),this.undoMutation(s,r);}delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(s=>s.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var s;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:r,mutationId:n}of t){let o=(s=this.optimisticMutationStack[r])==null?void 0:s.find(a=>a.id===n);this.undoMutation(r,n),o&&i.push({resource:r,mutationId:n,resourceId:o.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(r=>r.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var o;let s=(o=i.id)==null?void 0:o.value;if(!s)return;let{cleanedPayload:r,nestedMutations:n}=this.extractNestedRelations(e,i);n.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:r});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},r=[];return i!=null&&i.relations?(Object.entries(t).forEach(([n,o])=>{var u;let a=i.relations[n];if(!a)return;let c=a.entity.name,d=o==null?void 0:o.value;if(a.type==="one"){if(d&&typeof d=="object"&&!Array.isArray(d)&&((u=d.id)!=null&&u.value)){let l=d.id.value,m={...d},{cleanedPayload:g,nestedMutations:b}=this.extractNestedRelations(c,m);r.push(...b),r.push({id:l,type:"MUTATE",resource:c,resourceId:l,procedure:"INSERT",payload:g}),delete s[n];}}else a.type==="many"&&Array.isArray(d)&&(d.forEach(l=>{var m,g;if(l&&typeof l=="object"&&!Array.isArray(l)&&((g=(m=l.value)==null?void 0:m.id)!=null&&g.value)){let b=l.value.id.value,I={...l.value},{cleanedPayload:w,nestedMutations:T}=this.extractNestedRelations(c,I);r.push(...T),r.push({id:b,type:"MUTATE",resource:c,resourceId:b,procedure:"INSERT",payload:w});}}),delete s[n]);}),{cleanedPayload:s,nestedMutations:r}):{cleanedPayload:s,nestedMutations:r}}updateRawObjPool(e,t,i,s){var o;if(!this.schema[e])return;let r=(o=this.rawObjPool[e])==null?void 0:o[t],n=(this.optimisticMutationStack[e]??[]).reduce((a,c)=>c.resourceId!==t?a:this.schema[e].mergeMutation("set",c.payload,a)[0],r);if(this.optimisticRawObjPool[e]??={},n?this.optimisticRawObjPool[e][t]={value:{...n.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!n)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(a=>a.type==="many"?[a.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let a=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([c,d])=>d.type==="one"?[[d.relationalColumn,c]]:[]));Object.entries(i).forEach(([c,d])=>{let u=this.schema[e].relations[a[c]];if(!a[c])return;let l=s==null?void 0:s.value[c],[,m]=u.mergeMutation("set",d,l);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let g=u.entity.name;this.optimisticObjGraph.createNode(m.value,g,Object.values(this.schema[g].relations).flatMap(b=>b.type==="many"?[b.entity.name]:[]));}l!=null&&l.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,r=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!r)return;let[n,o]=Object.entries(t).reduce((c,[d,u])=>{let l=this.schema[s].relations[d];return l&&(l.type==="one"?c[0].push([d,l.entity.name,u??true]):l.type==="many"&&c[1].push([d,l.entity.name,u??true])),c},[[],[]]);return {value:{...r.value,...Object.fromEntries(n.map(([c,d,u])=>[c,this.materializeOneWithInclude(i.references.get(d),C(u)?u.include??{}:typeof u=="object"&&u!==null?u:{})])),...Object.fromEntries(o.map(([c,d,u])=>{let l=i.referencedBy.get(d),m=l instanceof Set;return [c,m?{value:Array.from(l.values()).map(g=>this.materializeOneWithInclude(g,C(u)?u.include??{}:typeof u=="object"&&u!==null?u:{}))}:this.materializeOneWithInclude(l,C(u)?u.include??{}:typeof u=="object"&&u!==null?u:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,s;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let r=f(t.query),n=this.querySnapshots[r],o=this.get(t.query,void 0,true);if(Se(o,n))return;this.querySnapshots[r]=o,(s=this.onQuerySubscriptionTriggered)==null||s.call(this,t.query),t.callbacks.forEach(a=>{a(o);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,r])=>{var a;let n=(a=this.schema[t])==null?void 0:a.relations[s];if(!n)return;let o=n.entity.name;if(i.push(o),typeof r=="object"&&r!==null){let c=C(r)?r.include??{}:r;i.push(...this.flattenIncludes(c,o));}}),Array.from(new Set(i))}};var re=p=>{if(p instanceof Error&&p.message.includes("Unknown procedure"))return true;if(p instanceof Error&&typeof p.cause=="object"&&p.cause!==null&&"message"in p.cause){let e=p.cause.message;return typeof e=="string"&&e.includes("Unknown procedure")}return false},D=class{constructor(e,t){this.client=e;this.query=t;}buildQueryRequest(){return this.query}then(e,t){return this.client.genericQuery(this.query.resource,this.query.procedure,this.query.input).then(e,t)}},$=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,r;this.url=e.url,this.logger=F({level:e.logLevel??E.INFO}),this.optimisticMutations=e.optimisticMutations,this.store=new P(e.schema,e.storage,this.logger,(n,o,a)=>{var d,u;let c=new Set;if(a)for(let l of Object.values(a))for(let{mutationId:m}of l)c.add(m);(u=(d=Object.values(n))==null?void 0:d.flat())==null||u.forEach(l=>{c.has(l.id)||this.sendWsMessage(l);}),this.replayCustomMutationStack();},(n,o)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:n,itemCount:o});},n=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:n});}),this.ws=new x({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",n=>{this.handleServerMessage(n.data);}),this.ws.addEventListener("connectionChange",n=>{if(this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:n.open}),n.open){Array.from(this.remoteSubscriptions.values()).forEach(({query:a})=>{this.sendWsMessage({id:b(),type:"SUBSCRIBE",...a});});let o=this.store.getCustomMutationMutationIds();Object.values(this.store.optimisticMutationStack).forEach(a=>{a&&a.forEach(c=>{o.has(c.id)||(this.emitEvent({type:"MUTATION_SENT",mutationId:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure??"UNKNOWN",optimistic:true}),this.sendWsMessage(c));});}),this.replayCustomMutationStack();}});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,s,r;try{this.logger.debug("Message received from the server:",e);let n=ie.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",n),this.emitEvent({type:"MESSAGE_RECEIVED",message:n}),n.type==="MUTATE"){let{resource:o,id:a,resourceId:c,procedure:d}=n;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:a,resource:o,resourceId:c,procedure:d??"UNKNOWN"});try{this.store.addMutation(o,n);}catch(u){this.logger.error("Error merging mutation from the server:",u);}}else if(n.type==="REJECT"){if(this.replyHandlers[n.id]){clearTimeout(this.replyHandlers[n.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(n.id));let c=n.message??"Mutation rejected";(i=(t=this.replyHandlers[n.id]).reject)==null||i.call(t,new Error(c)),delete this.replyHandlers[n.id];}let o=((s=this.store.optimisticMutationStack[n.resource])==null?void 0:s.length)??0,a=(r=this.store.optimisticMutationStack[n.resource])==null?void 0:r.find(c=>c.id===n.id);this.store.undoMutation(n.resource,n.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:n.id,resource:n.resource}),a&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n.id,resource:n.resource,resourceId:a.resourceId,pendingMutations:o-1});}else if(n.type==="REPLY"){let{id:o,data:a}=n;if(this.replyHandlers[o]){clearTimeout(this.replyHandlers[o].timeoutHandle),this.replyHandlers[o].handler(a);return}let c=se.parse(a);this.emitEvent({type:"DATA_LOAD_REPLY",resource:c.resource,itemCount:c.data.length}),this.store.loadConsolidatedState(c.resource,c.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:c.resource,itemCount:c.data.length});}}catch(n){this.logger.error("Error parsing message from the server:",n);}}load(e){let t=b(),i=f(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let s=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),s&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let r=this.remoteSubscriptions.get(i);r.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:b(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var o,a;let r={id:b(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i},n=(((o=this.store.optimisticMutationStack[e])==null?void 0:o.length)??0)+1;(a=this.store)==null||a.addMutation(e,r,true),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:r.id,resource:e,resourceId:t,procedure:i,pendingMutations:n}),this.emitEvent({type:"MUTATION_SENT",mutationId:r.id,resource:e,resourceId:t,procedure:i,optimistic:true}),this.sendWsMessage(r);}genericMutate(e,t,i){var o,a;let s=(o=this.ws)==null?void 0:o.connected(),r=(a=this.optimisticMutations)==null?void 0:a.getHandler(e,t);if(!s&&!r)throw new Error("WebSocket not connected");let n={id:b(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(r)try{let{proxy:c,getOperations:d}=a$1(this.store,this.store.schema);r({input:i,storage:c});let u=d(),l=this.applyOptimisticOperations(u);this.store.registerCustomMutation(n.id,l),this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(c){throw this.logger.error("Error executing optimistic handler:",c),this.emitUndoEvents(this.store.undoCustomMutation(n.id)),c}else this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:false});return s?(this.sendWsMessage(n),new Promise((c,d)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],this.emitUndoEvents(this.store.undoCustomMutation(n.id)),d(new Error("Reply timeout"));},5e3),handler:u=>{delete this.replyHandlers[n.id],this.store.confirmCustomMutation(n.id),c(u);},reject:d};})):(this.store.addCustomMutationMessage(n),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let s of e){let r=b(),n=new Date().toISOString(),o={id:r,type:"MUTATE",resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[s.resource].encodeMutation("set",s.data,n)},a=(((i=this.store.optimisticMutationStack[s.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(s.resource,o,!0),t.push({resource:s.resource,mutationId:r}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:r,resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",pendingMutations:a});}return t}catch(s){for(let{resource:r,mutationId:n}of t)this.store.undoMutation(r,n);throw s}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:s,resourceId:r}of e){let n=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s,resource:i,resourceId:r,pendingMutations:n});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:b(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(s),new Promise((r,n)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],n(new Error("Reply timeout"));},5e3),handler:o=>{delete this.replyHandlers[s.id],r(o);},reject:n};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},nt=p=>{let e=new $(p),t=(i,s)=>new Proxy(s,{get(r,n,o){if(n in r)return Reflect.get(r,n,o);if(typeof n=="string")return a=>new D(e,{resource:i,procedure:n,input:a})}});return {client:{ws:e.ws,load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,s){if(typeof s=="string")return Object.hasOwn(p.schema,s)?t(s,a._init(p.schema[s],e)):new Proxy({},{get(r,n){if(typeof n=="string")return o=>new D(e,{resource:s,procedure:n,input:o})}})},has(i,s){return typeof s=="string"}}),mutate:d(()=>{},{apply:(i,s,r)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[n,o]=s;if(o==="insert")return e.genericMutate(n,o,r[0]).catch(a=>{if(!re(a))throw a;let{id:c,...d}=r[0]??{};return e.mutate(n,c,"INSERT",d)});if(o==="update"){let a=r.length>1&&typeof r[0]=="string"&&typeof r[1]=="object"&&r[1]!==null?{id:r[0],...r[1]}:r[0];return e.genericMutate(n,o,a).catch(c=>{var l;if(!re(c))throw c;let[d,u]=r.length>1?r:[(l=r[0])==null?void 0:l.id,r[0]];return e.mutate(n,d,"UPDATE",u)})}return e.genericMutate(n,o,r[0])}})}}};export{nt as createClient,Ce as useLiveQuery,Ie as useLoadData};
|
|
1
|
+
import {d,a,b,f as f$1,e,c}from'./chunk-LSAVBBUS.js';import {a as a$1}from'./chunk-RSSRYEM3.js';export{b as defineOptimisticMutations}from'./chunk-RSSRYEM3.js';import {useSyncExternalStore,useMemo,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z}from'zod';import {stringify}from'qs';import Te from'fast-deep-equal';import {openDB}from'idb';var f=l=>xxHash32(JSON.stringify(l)).toString(32);var v=(l,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>v(l,n,t));if(i==="$or")return s.some(n=>v(l,n,t));let r=(s==null?void 0:s.$eq)!==void 0?s==null?void 0:s.$eq:s;if(typeof s=="object"&&s!==null&&(s==null?void 0:s.$eq)===void 0){if(s.$in!==void 0){let o=l[i];return o===void 0?false:t?!s.$in.includes(o):s.$in.includes(o)}if(s.$not!==void 0&&!t)return v(l,{[i]:s.$not},true);if(s.$gt!==void 0){let o=l[i];return typeof o!="number"?false:t?o<=s.$gt:o>s.$gt}if(s.$gte!==void 0){let o=l[i];return typeof o!="number"?false:t?o<s.$gte:o>=s.$gte}if(s.$lt!==void 0){let o=l[i];return typeof o!="number"?false:t?o>=s.$lt:o<s.$lt}if(s.$lte!==void 0){let o=l[i];return typeof o!="number"?false:t?o>s.$lte:o<=s.$lte}let n=l[i];return !n||typeof n!="object"&&!Array.isArray(n)?false:Array.isArray(n)?t?!n.some(o=>v(o,s,false)):n.some(o=>v(o,s,false)):v(n,s,t)}return t?l[i]!==r:l[i]===r}),C=l=>{if(typeof l!="object"||l===null)return false;let e=l;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},E={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},U=class{level;prefix;constructor(e={}){this.level=e.level??E.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=E.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=E.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=E.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=E.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=E.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},F=l=>new U(l);var _=class{subscriptions=new Map;getOrStoreSubscription(e){let t=e.buildQueryRequest(),i=f(t);if(this.subscriptions.has(i))return this.subscriptions.get(i).subscribe;let s={subscribe:r=>{let n=this.subscriptions.get(i);return n.callbacks.add(r),n.unsubscribe||(n.unsubscribe=()=>{},n.unsubscribe=e.subscribe(()=>{n.callbacks.forEach(o=>{o();});})),()=>{var o;(o=this.subscriptions.get(i))==null||o.callbacks.delete(r),setTimeout(()=>{var c;let a=this.subscriptions.get(i);a&&a.callbacks.size===0&&((c=a.unsubscribe)==null||c.call(a),this.subscriptions.delete(i));},10);}},callbacks:new Set,unsubscribe:void 0};return this.subscriptions.set(i,s),this.subscriptions.get(i).subscribe}},pe=new _,we=l=>useSyncExternalStore(pe.getOrStoreSubscription(l),l.get),Ae=l=>{let{subscribe:e,getSnapshot:t}=useMemo(()=>{let i={bootstrapStatus:l.bootstrapStatus,connected:l.ws.connected()},s=()=>{let r={bootstrapStatus:l.bootstrapStatus,connected:l.ws.connected()};(r.bootstrapStatus!==i.bootstrapStatus||r.connected!==i.connected)&&(i=r);};return {subscribe:r=>l.addEventListener(n=>{(n.type==="BOOTSTRAP_STATUS_CHANGE"||n.type==="CONNECTION_STATE_CHANGE")&&(s(),r());}),getSnapshot:()=>i}},[l]);return useSyncExternalStore(e,t,t)},xe=(l,e)=>{useEffect(()=>{let t=l.load(e.buildQueryRequest());return ()=>{t();}},[e,l.load]);};var X=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.coerce.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),Q=z.record(z.string(),z.object({value:z.any().nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})),he=Q.superRefine((l,e)=>{l.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Z=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),ee=z.object({timestamp:z.string().optional(),originMutationId:z.string().optional()}).optional(),N=Z.extend({procedure:z.string(),payload:z.any().optional(),meta:ee}),B=Z.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:he,meta:ee});z.union([B,N]);var te=z.object({resource:z.string(),procedure:z.string(),input:z.any().optional()});var T=z.string(),W=z.union([te,X]),ye=z.object({id:T,type:z.literal("SUBSCRIBE")}).and(W),me=z.object({id:T,type:z.literal("UNSUBSCRIBE")}).and(W),ge=z.object({id:T,type:z.literal("QUERY")}).and(W),fe=z.object({id:T,type:z.literal("CUSTOM_QUERY"),resource:z.string(),procedure:z.string(),input:z.any().optional()}),ie=B.extend({id:T}),be=N.extend({id:T}),Se=z.union([be,ie]);z.union([ye,ge,fe,Se,me]);var Me=z.object({id:T,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),ve=z.object({id:T,type:z.literal("REPLY"),data:z.any()}),se=z.union([Me,ve,ie]),ne=z.object({resource:z.string(),data:z.array(Q)});var x=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await c(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){var i;this.eventListeners.has(e)||this.eventListeners.set(e,new Set),(i=this.eventListeners.get(e))==null||i.add(t);}removeEventListener(e,t){var i;this.eventListeners.has(e)&&((i=this.eventListeners.get(e))==null||i.delete(t));}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){var t,i;this.dispatchEvent("error",e),this.dispatchEvent("connectionChange",{open:false}),(i=(t=e.error)==null?void 0:t.message)!=null&&i.includes("non-101")&&(this.ws&&(this.ws.close(),this.ws=null),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect());}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){var i;(i=this.eventListeners.get(e))==null||i.forEach(s=>{s(t);});}};var k=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let r=s.referencedBy.get(i.type);r&&r instanceof Set?r.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let r=this.nodes.get(s);if(!r)return;let n=r.referencedBy.get(i.type);n&&(n instanceof Set?n.delete(e):r.referencedBy.delete(i.type),this.notifySubscribers(s)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,s])=>{(s instanceof Set?Array.from(s.values()):[s]).forEach(n=>{let o=this.nodes.get(n);!o||!o.references.get(i)||(o.references.delete(i),this.notifySubscribers(n));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(r){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var q="__meta",j="databases",L=class{db;async init(e,t){var c,p;if(typeof window>"u")return;let s=((c=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:c.version)??1,r=await f(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,d])=>[u,await f(d)]))),o=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(j)||u.createObjectStore(j);}}),a=(p=await this.getAll(o,j))==null?void 0:p[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),q].forEach(d=>{(a==null?void 0:a.objectHashes[d])!==n[d]&&u.objectStoreNames.contains(d)&&u.deleteObjectStore(d),u.objectStoreNames.contains(d)||u.createObjectStore(d);}),await o.put(j,{schemaHash:r,objectHashes:n},t);},blocking(){window.location.reload();},blocked(){window.location.reload();}});}async get(e){return await this.getAll(this.db,e)??{}}getOne(e,t){return this.db?this.db.get(e,t):new Promise(i=>i(void 0))}set(e,t,i){var s;return (s=this.db)==null?void 0:s.put(e,i,t)}delete(e,t){var i;return (i=this.db)==null?void 0:i.delete(e,t)}getMeta(e){return this.db?this.db.get(q,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(q,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,s]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((r,n)=>[s[n],r]))}};var P=class{constructor(e,t,i,s,r,n){this.schema=e;this.logger=i,this.optimisticObjGraph=new k(i),this.kvStorage=new L,this.onQuerySubscriptionTriggered=n,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{Promise.all([this.kvStorage.getMeta("mutationStack"),this.kvStorage.getMeta("customMutationStack"),this.kvStorage.getMeta("customMutationIndex")]).then(([o,a,c])=>{o&&Object.keys(o).length>0&&(this.optimisticMutationStack=o),a&&a.length>0&&(this.customMutationStack=a),c&&Object.keys(c).length>0&&(this.customMutationIndex=c),s==null||s(this.optimisticMutationStack,this.customMutationStack,this.customMutationIndex);}).then(()=>{Object.entries(this.schema).forEach(([o])=>{this.kvStorage.get(o).then(a=>{if(!a||Object.keys(a).length===0){r==null||r(o,0);return}let c=Object.entries(a).map(([p,u])=>({...u,id:{value:p}}));r==null||r(o,c.length),this.loadConsolidatedState(o,c);});});}).catch(o=>{i.debug("Storage initialization failed (may not be available in this environment):",o);});});}rawObjPool={};optimisticMutationStack={};customMutationStack=[];optimisticObjGraph;optimisticRawObjPool={};logger;onQuerySubscriptionTriggered;customMutationIndex={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var a;let s=t??f(e$1);if(this.querySnapshots[s]&&!i){let c=this.querySnapshots[s];if(c)return c}let r,n=(a=e$1.where)==null?void 0:a.id;n===void 0?r=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):typeof n=="string"?r=[n]:typeof n=="object"&&n!==null?"$in"in n&&Array.isArray(n.$in)?r=n.$in:"$eq"in n&&typeof n.$eq=="string"?r=[n.$eq]:r=Object.keys(this.optimisticRawObjPool[e$1.resource]??{}):r=Object.keys(this.optimisticRawObjPool[e$1.resource]??{});let o=r.flatMap(c=>{let p=f$1(this.materializeOneWithInclude(c,e$1.include));return p?[p]:[]});if(e$1.sort&&e$1.sort.length>0){let c=(p,u)=>{for(let d of e$1.sort){let m=p[d.key],g=u[d.key];if(m<g)return d.direction==="asc"?-1:1;if(m>g)return d.direction==="asc"?1:-1}return 0};o.sort(c);}if(e$1.where||e$1.limit){let c=e$1.where?p=>v(p,e$1.where):()=>true;o=e(o,c,e$1.limit);}return !i&&this.collectionSubscriptions.has(s)&&(this.querySnapshots[s]=o),o}subscribe(e,t){var r;let i=f(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var n,o;(n=this.collectionSubscriptions.get(i))==null||n.callbacks.delete(t),((o=this.collectionSubscriptions.get(i))==null?void 0:o.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,o,a,c,p,u,d;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let r=(n=this.optimisticRawObjPool[e])==null?void 0:n[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(o=this.optimisticMutationStack)==null?void 0:o[e])==null?void 0:a.filter(I=>I.id!==t.id))??[];let m=(c=t.meta)==null?void 0:c.originMutationId;if(this.logger.debug("Broadcast mutation received",{mutationId:t.id,resource:e,resourceId:t.resourceId,procedure:t.procedure,originMutationId:m??"(none)",customMutationIndexKeys:Object.keys(this.customMutationIndex),optimisticStackSize:((p=this.optimisticMutationStack[e])==null?void 0:p.length)??0}),m&&this.customMutationIndex[m]){let w=this.customMutationIndex[m].filter(S=>S.resource===e),R=false;for(let S of w){let O=(u=this.optimisticMutationStack[e])==null?void 0:u.find(A=>A.id===S.mutationId);if(O&&O.resourceId===t.resourceId&&O.procedure===t.procedure){this.logger.debug("Removing optimistic mutation (resourceId match)",{optimisticMutationId:S.mutationId,resourceId:t.resourceId}),this.undoMutation(e,S.mutationId),R=true;break}}if(!R)for(let S of w){let O=(d=this.optimisticMutationStack[e])==null?void 0:d.find(A=>A.id===S.mutationId&&A.procedure===t.procedure);if(O){this.logger.debug("Removing optimistic mutation (resource+procedure fallback)",{optimisticMutationId:S.mutationId,optimisticResourceId:O.resourceId,broadcastResourceId:t.resourceId}),this.undoMutation(e,S.mutationId),R=true;break}}}this.rawObjPool[e]??={};let g={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=g;let b=g.value;delete b.id,this.kvStorage.set(e,t.resourceId,b);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,r);}undoMutation(e,t){var n,o;if(!this.optimisticMutationStack[e])return;let i=(n=this.optimisticMutationStack[e])==null?void 0:n.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let r=(o=this.optimisticRawObjPool[e])==null?void 0:o[s.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,s.resourceId,Object.fromEntries(Object.entries(s.payload).map(([a])=>[a,{value:null,_meta:{}}])),r);}addCustomMutationMessage(e){this.customMutationStack.push(e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}registerCustomMutation(e,t){this.customMutationIndex[e]=t,this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex);}confirmCustomMutation(e){var i;let t=this.customMutationIndex[e];if(this.logger.debug("confirmCustomMutation called",{messageId:e,hasIndex:!!t,mutations:t??[]}),!!t){for(let{resource:s,mutationId:r}of t){let n=!!((i=this.optimisticMutationStack[s])!=null&&i.find(o=>o.id===r));this.logger.debug("confirmCustomMutation: undoing mutation",{resource:s,mutationId:r,stillInStack:n}),this.undoMutation(s,r);}delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(s=>s.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack);}}undoCustomMutation(e){var s;let t=this.customMutationIndex[e];if(!t)return [];let i=[];for(let{resource:r,mutationId:n}of t){let o=(s=this.optimisticMutationStack[r])==null?void 0:s.find(a=>a.id===n);this.undoMutation(r,n),o&&i.push({resource:r,mutationId:n,resourceId:o.resourceId});}return delete this.customMutationIndex[e],this.kvStorage.setMeta("customMutationIndex",this.customMutationIndex),this.customMutationStack=this.customMutationStack.filter(r=>r.id!==e),this.kvStorage.setMeta("customMutationStack",this.customMutationStack),i}getCustomMutationMutationIds(){let e=new Set;for(let t of Object.values(this.customMutationIndex))for(let{mutationId:i}of t)e.add(i);return e}loadConsolidatedState(e,t){t.forEach(i=>{var o;let s=(o=i.id)==null?void 0:o.value;if(!s)return;let{cleanedPayload:r,nestedMutations:n}=this.extractNestedRelations(e,i);n.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:r});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},r=[];return i!=null&&i.relations?(Object.entries(t).forEach(([n,o])=>{var u;let a=i.relations[n];if(!a)return;let c=a.entity.name,p=o==null?void 0:o.value;if(a.type==="one"){if(p&&typeof p=="object"&&!Array.isArray(p)&&((u=p.id)!=null&&u.value)){let d=p.id.value,m={...p},{cleanedPayload:g,nestedMutations:b}=this.extractNestedRelations(c,m);r.push(...b),r.push({id:d,type:"MUTATE",resource:c,resourceId:d,procedure:"INSERT",payload:g}),delete s[n];}}else a.type==="many"&&Array.isArray(p)&&(p.forEach(d=>{var m,g;if(d&&typeof d=="object"&&!Array.isArray(d)&&((g=(m=d.value)==null?void 0:m.id)!=null&&g.value)){let b=d.value.id.value,I={...d.value},{cleanedPayload:w,nestedMutations:R}=this.extractNestedRelations(c,I);r.push(...R),r.push({id:b,type:"MUTATE",resource:c,resourceId:b,procedure:"INSERT",payload:w});}}),delete s[n]);}),{cleanedPayload:s,nestedMutations:r}):{cleanedPayload:s,nestedMutations:r}}updateRawObjPool(e,t,i,s){var o;if(!this.schema[e])return;let r=(o=this.rawObjPool[e])==null?void 0:o[t],n=(this.optimisticMutationStack[e]??[]).reduce((a,c)=>c.resourceId!==t?a:this.schema[e].mergeMutation("set",c.payload,a)[0],r);if(this.optimisticRawObjPool[e]??={},n?this.optimisticRawObjPool[e][t]={value:{...n.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!n)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(a=>a.type==="many"?[a.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let a=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([c,p])=>p.type==="one"?[[p.relationalColumn,c]]:[]));Object.entries(i).forEach(([c,p])=>{let u=this.schema[e].relations[a[c]];if(!a[c])return;let d=s==null?void 0:s.value[c],[,m]=u.mergeMutation("set",p,d);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let g=u.entity.name;this.optimisticObjGraph.createNode(m.value,g,Object.values(this.schema[g].relations).flatMap(b=>b.type==="many"?[b.entity.name]:[]));}d!=null&&d.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,m.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var a;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let s=i.type,r=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!r)return;let[n,o]=Object.entries(t).reduce((c,[p,u])=>{let d=this.schema[s].relations[p];return d&&(d.type==="one"?c[0].push([p,d.entity.name,u??true]):d.type==="many"&&c[1].push([p,d.entity.name,u??true])),c},[[],[]]);return {value:{...r.value,...Object.fromEntries(n.map(([c,p,u])=>[c,this.materializeOneWithInclude(i.references.get(p),C(u)?u.include??{}:typeof u=="object"&&u!==null?u:{})])),...Object.fromEntries(o.map(([c,p,u])=>{let d=i.referencedBy.get(p),m=d instanceof Set;return [c,m?{value:Array.from(d.values()).map(g=>this.materializeOneWithInclude(g,C(u)?u.include??{}:typeof u=="object"&&u!==null?u:{}))}:this.materializeOneWithInclude(d,C(u)?u.include??{}:typeof u=="object"&&u!==null?u:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{var i,s;if(t.query.resource===e||(i=t.flatInclude)!=null&&i.includes(e)){let r=f(t.query),n=this.querySnapshots[r],o=this.get(t.query,void 0,true);if(Te(o,n))return;this.querySnapshots[r]=o,(s=this.onQuerySubscriptionTriggered)==null||s.call(this,t.query),t.callbacks.forEach(a=>{a(o);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,r])=>{var a;let n=(a=this.schema[t])==null?void 0:a.relations[s];if(!n)return;let o=n.entity.name;if(i.push(o),typeof r=="object"&&r!==null){let c=C(r)?r.include??{}:r;i.push(...this.flattenIncludes(c,o));}}),Array.from(new Set(i))}};var oe=l=>{if(l instanceof Error&&l.message.includes("Unknown procedure"))return true;if(l instanceof Error&&typeof l.cause=="object"&&l.cause!==null&&"message"in l.cause){let e=l.cause.message;return typeof e=="string"&&e.includes("Unknown procedure")}return false},ae={pending:0,local:1,remote:2},D=class{constructor(e,t){this.client=e;this.query=t;}buildQueryRequest(){return this.query}then(e,t){return this.client.genericQuery(this.query.resource,this.query.procedure,this.query.input).then(e,t)}},$=class{url;ws;store;logger;optimisticMutations;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};_bootstrapStatus="pending";storageLoadedCount=0;expectedStorageLoads;constructor(e){var t,i,s,r;this.url=e.url,this.logger=F({level:e.logLevel??E.INFO}),this.optimisticMutations=e.optimisticMutations,this.expectedStorageLoads=e.storage===false?0:Object.keys(e.schema).length,this.store=new P(e.schema,e.storage,this.logger,(n,o,a)=>{var p,u;let c=new Set;if(a)for(let d of Object.values(a))for(let{mutationId:m}of d)c.add(m);(u=(p=Object.values(n))==null?void 0:p.flat())==null||u.forEach(d=>{c.has(d.id)||this.sendWsMessage(d);}),this.replayCustomMutationStack();},(n,o)=>{this.emitEvent({type:"CLIENT_STORAGE_LOADED",resource:n,itemCount:o}),this.storageLoadedCount+=1,this.expectedStorageLoads>0&&this.storageLoadedCount>=this.expectedStorageLoads&&this.setBootstrapStatus("local");},n=>{this.emitEvent({type:"QUERY_SUBSCRIPTION_TRIGGERED",query:n});}),this.ws=new x({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",n=>{this.handleServerMessage(n.data);}),this.ws.addEventListener("connectionChange",n=>{if(this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:n.open}),n.open){Array.from(this.remoteSubscriptions.values()).forEach(({query:a})=>{this.sendWsMessage({id:b(),type:"SUBSCRIBE",...a});});let o=this.store.getCustomMutationMutationIds();Object.values(this.store.optimisticMutationStack).forEach(a=>{a&&a.forEach(c=>{o.has(c.id)||(this.emitEvent({type:"MUTATION_SENT",mutationId:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure??"UNKNOWN",optimistic:true}),this.sendWsMessage(c));});}),this.replayCustomMutationStack();}});}get(e){let t=this.store.get(e);return this.emitEvent({type:"QUERY_EXECUTED",query:e,resultCount:Array.isArray(t)?t.length:t?1:0}),t}handleServerMessage(e){var t,i,s,r;try{this.logger.debug("Message received from the server:",e);let n=se.parse(JSON.parse(e));if(this.logger.debug("Parsed message:",n),this.emitEvent({type:"MESSAGE_RECEIVED",message:n}),n.type==="MUTATE"){let{resource:o,id:a,resourceId:c,procedure:p}=n;this.emitEvent({type:"MUTATION_RECEIVED",mutationId:a,resource:o,resourceId:c,procedure:p??"UNKNOWN"});try{this.store.addMutation(o,n);}catch(u){this.logger.error("Error merging mutation from the server:",u);}}else if(n.type==="REJECT"){if(this.replyHandlers[n.id]){clearTimeout(this.replyHandlers[n.id].timeoutHandle),this.emitUndoEvents(this.store.undoCustomMutation(n.id));let c=n.message??"Mutation rejected";(i=(t=this.replyHandlers[n.id]).reject)==null||i.call(t,new Error(c)),delete this.replyHandlers[n.id];}let o=((s=this.store.optimisticMutationStack[n.resource])==null?void 0:s.length)??0,a=(r=this.store.optimisticMutationStack[n.resource])==null?void 0:r.find(c=>c.id===n.id);this.store.undoMutation(n.resource,n.id),this.emitEvent({type:"MUTATION_REJECTED",mutationId:n.id,resource:n.resource}),a&&this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:n.id,resource:n.resource,resourceId:a.resourceId,pendingMutations:o-1});}else if(n.type==="REPLY"){let{id:o,data:a}=n;if(this.replyHandlers[o]){clearTimeout(this.replyHandlers[o].timeoutHandle),this.replyHandlers[o].handler(a);return}let c=ne.parse(a);this.emitEvent({type:"DATA_LOAD_REPLY",resource:c.resource,itemCount:c.data.length}),this.store.loadConsolidatedState(c.resource,c.data),this.emitEvent({type:"STORE_STATE_UPDATED",resource:c.resource,itemCount:c.data.length}),this.setBootstrapStatus("remote");}}catch(n){this.logger.error("Error parsing message from the server:",n);}}load(e){let t=b(),i=f(e);this.emitEvent({type:"DATA_LOAD_REQUESTED",query:e,subscriptionId:t}),this.sendWsMessage({id:t,type:"SUBSCRIBE",...e});let s=!this.remoteSubscriptions.has(i);return this.remoteSubscriptions.has(i)?this.remoteSubscriptions.get(i).subCounter+=1:this.remoteSubscriptions.set(i,{query:e,subCounter:1}),s&&this.emitEvent({type:"SUBSCRIPTION_CREATED",query:e,subscriptionKey:i,subscriberCount:1}),()=>{if(this.remoteSubscriptions.has(i)){let r=this.remoteSubscriptions.get(i);r.subCounter-=1,this.remoteSubscriptions.get(i).subCounter<=0&&(this.remoteSubscriptions.delete(i),this.sendWsMessage({id:b(),type:"UNSUBSCRIBE",...e}),this.emitEvent({type:"SUBSCRIPTION_REMOVED",query:e,subscriptionKey:i}));}}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var o,a;let r={id:b(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i},n=(((o=this.store.optimisticMutationStack[e])==null?void 0:o.length)??0)+1;(a=this.store)==null||a.addMutation(e,r,true),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:r.id,resource:e,resourceId:t,procedure:i,pendingMutations:n}),this.emitEvent({type:"MUTATION_SENT",mutationId:r.id,resource:e,resourceId:t,procedure:i,optimistic:true}),this.sendWsMessage(r);}genericMutate(e,t,i){var o,a;let s=(o=this.ws)==null?void 0:o.connected(),r=(a=this.optimisticMutations)==null?void 0:a.getHandler(e,t);if(!s&&!r)throw new Error("WebSocket not connected");let n={id:b(),type:"MUTATE",resource:e,procedure:t,payload:i,meta:{timestamp:new Date().toISOString()}};if(r)try{let{proxy:c,getOperations:p}=a$1(this.store,this.store.schema);r({input:i,storage:c});let u=p(),d=this.applyOptimisticOperations(u);this.store.registerCustomMutation(n.id,d),this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:!0});}catch(c){throw this.logger.error("Error executing optimistic handler:",c),this.emitUndoEvents(this.store.undoCustomMutation(n.id)),c}else this.emitEvent({type:"MUTATION_SENT",mutationId:n.id,resource:e,resourceId:"",procedure:t,optimistic:false});return s?(this.sendWsMessage(n),new Promise((c,p)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],this.emitUndoEvents(this.store.undoCustomMutation(n.id)),p(new Error("Reply timeout"));},5e3),handler:u=>{delete this.replyHandlers[n.id],this.store.confirmCustomMutation(n.id),c(u);},reject:p};})):(this.store.addCustomMutationMessage(n),Promise.resolve(void 0))}applyOptimisticOperations(e){var i;let t=[];try{for(let s of e){let r=b(),n=new Date().toISOString(),o={id:r,type:"MUTATE",resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",payload:this.store.schema[s.resource].encodeMutation("set",s.data,n)},a=(((i=this.store.optimisticMutationStack[s.resource])==null?void 0:i.length)??0)+1;this.store.addMutation(s.resource,o,!0),t.push({resource:s.resource,mutationId:r}),this.emitEvent({type:"OPTIMISTIC_MUTATION_APPLIED",mutationId:r,resource:s.resource,resourceId:s.id,procedure:s.type==="insert"?"INSERT":"UPDATE",pendingMutations:a});}return t}catch(s){for(let{resource:r,mutationId:n}of t)this.store.undoMutation(r,n);throw s}}emitUndoEvents(e){var t;for(let{resource:i,mutationId:s,resourceId:r}of e){let n=((t=this.store.optimisticMutationStack[i])==null?void 0:t.length)??0;this.emitEvent({type:"OPTIMISTIC_MUTATION_UNDONE",mutationId:s,resource:i,resourceId:r,pendingMutations:n});}}genericQuery(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:b(),type:"CUSTOM_QUERY",resource:e,procedure:t,input:i};return this.sendWsMessage(s),new Promise((r,n)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],n(new Error("Reply timeout"));},5e3),handler:o=>{delete this.replyHandlers[s.id],r(o);},reject:n};})}get bootstrapStatus(){return this._bootstrapStatus}setBootstrapStatus(e){ae[e]<=ae[this._bootstrapStatus]||(this._bootstrapStatus=e,this.emitEvent({type:"BOOTSTRAP_STATUS_CHANGE",bootstrapStatus:e}));}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}replayCustomMutationStack(){var e;if((e=this.ws)!=null&&e.connected())for(let t of this.store.customMutationStack)this.sendWsMessage(t),!this.replyHandlers[t.id]&&(this.replyHandlers[t.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[t.id],this.emitUndoEvents(this.store.undoCustomMutation(t.id));},5e3),handler:()=>{delete this.replyHandlers[t.id],this.store.confirmCustomMutation(t.id);}});}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},at=l=>{let e=new $(l),t=(i,s)=>new Proxy(s,{get(r,n,o){if(n in r)return Reflect.get(r,n,o);if(typeof n=="string")return a=>new D(e,{resource:i,procedure:n,input:a})}});return {client:{ws:e.ws,get bootstrapStatus(){return e.bootstrapStatus},load:i=>e.load(i),addEventListener:i=>e.addEventListener(i)},store:{query:new Proxy({},{get(i,s){if(typeof s=="string")return Object.hasOwn(l.schema,s)?t(s,a._init(l.schema[s],e)):new Proxy({},{get(r,n){if(typeof n=="string")return o=>new D(e,{resource:s,procedure:n,input:o})}})},has(i,s){return typeof s=="string"}}),mutate:d(()=>{},{apply:(i,s,r)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[n,o]=s;if(o==="insert")return e.genericMutate(n,o,r[0]).catch(a=>{if(!oe(a))throw a;let{id:c,...p}=r[0]??{};return e.mutate(n,c,"INSERT",p)});if(o==="update"){let a=r.length>1&&typeof r[0]=="string"&&typeof r[1]=="object"&&r[1]!==null?{id:r[0],...r[1]}:r[0];return e.genericMutate(n,o,a).catch(c=>{var d;if(!oe(c))throw c;let[p,u]=r.length>1?r:[(d=r[0])==null?void 0:d.id,r[0]];return e.mutate(n,p,"UPDATE",u)})}return e.genericMutate(n,o,r[0])}})}}};export{at as createClient,Ae as useClientState,we as useLiveQuery,xe as useLoadData};
|
package/dist/fetch-client.d.ts
CHANGED
|
@@ -858,14 +858,6 @@ declare const createOptimisticStorageProxy: <TSchema extends Schema<any>>(store:
|
|
|
858
858
|
*/
|
|
859
859
|
declare const defineOptimisticMutations: <TRouter extends ClientRouterConstraint, TSchema extends Schema<any>>(config: OptimisticMutationsConfig<TRouter, TSchema>) => OptimisticMutationsRegistry<TSchema>;
|
|
860
860
|
|
|
861
|
-
declare const useLiveQuery: <T extends {
|
|
862
|
-
get: () => U;
|
|
863
|
-
subscribe: (cb: (v: U) => void) => () => void;
|
|
864
|
-
}, U>(observable: T) => ReturnType<T["get"]>;
|
|
865
|
-
declare const useLoadData: (client: Client<ClientRouterConstraint>["client"], query: {
|
|
866
|
-
buildQueryRequest: () => RawQueryRequest | CustomQueryRequest;
|
|
867
|
-
}) => void;
|
|
868
|
-
|
|
869
861
|
type WebSocketClientEventMap = WebSocketEventMap & {
|
|
870
862
|
connectionChange: {
|
|
871
863
|
open: boolean;
|
|
@@ -997,10 +989,16 @@ type OptimisticMutationUndoneEvent = {
|
|
|
997
989
|
resourceId: string;
|
|
998
990
|
pendingMutations: number;
|
|
999
991
|
};
|
|
1000
|
-
type
|
|
992
|
+
type ClientBootstrapStatus = "pending" | "local" | "remote";
|
|
993
|
+
type BootstrapStatusChangeEvent = {
|
|
994
|
+
type: "BOOTSTRAP_STATUS_CHANGE";
|
|
995
|
+
bootstrapStatus: ClientBootstrapStatus;
|
|
996
|
+
};
|
|
997
|
+
type ClientEvents = ConnectionStateChangeEvent | MessageReceivedEvent | ClientStorageLoadedEvent | DataLoadRequestedEvent | DataLoadReplyEvent | MutationSentEvent | MutationReceivedEvent | MutationRejectedEvent | SubscriptionCreatedEvent | SubscriptionRemovedEvent | QueryExecutedEvent | QuerySubscriptionTriggeredEvent | StoreStateUpdatedEvent | OptimisticMutationAppliedEvent | OptimisticMutationUndoneEvent | BootstrapStatusChangeEvent;
|
|
1001
998
|
type Client<TRouter extends ClientRouterConstraint> = {
|
|
1002
999
|
client: {
|
|
1003
1000
|
ws: WebSocketClient;
|
|
1001
|
+
readonly bootstrapStatus: ClientBootstrapStatus;
|
|
1004
1002
|
addEventListener: (listener: (event: ClientEvents) => void) => () => void;
|
|
1005
1003
|
load: (query: RawQueryRequest | CustomQueryRequest) => () => void;
|
|
1006
1004
|
};
|
|
@@ -1008,6 +1006,19 @@ type Client<TRouter extends ClientRouterConstraint> = {
|
|
|
1008
1006
|
};
|
|
1009
1007
|
declare const createClient: <TRouter extends ClientRouterConstraint>(opts: WebSocketClientOptions) => Client<TRouter>;
|
|
1010
1008
|
|
|
1009
|
+
declare const useLiveQuery: <T extends {
|
|
1010
|
+
get: () => U;
|
|
1011
|
+
subscribe: (cb: (v: U) => void) => () => void;
|
|
1012
|
+
}, U>(observable: T) => ReturnType<T["get"]>;
|
|
1013
|
+
type ClientState = {
|
|
1014
|
+
bootstrapStatus: ClientBootstrapStatus;
|
|
1015
|
+
connected: boolean;
|
|
1016
|
+
};
|
|
1017
|
+
declare const useClientState: (client: Client<ClientRouterConstraint>["client"]) => ClientState;
|
|
1018
|
+
declare const useLoadData: (client: Client<ClientRouterConstraint>["client"], query: {
|
|
1019
|
+
buildQueryRequest: () => RawQueryRequest | CustomQueryRequest;
|
|
1020
|
+
}) => void;
|
|
1021
|
+
|
|
1011
1022
|
type ClientOptions<TSchema extends Schema<any> = Schema<any>> = {
|
|
1012
1023
|
url: string;
|
|
1013
1024
|
schema: TSchema;
|
|
@@ -1019,4 +1030,4 @@ type ClientOptions<TSchema extends Schema<any> = Schema<any>> = {
|
|
|
1019
1030
|
optimisticMutations?: OptimisticMutationsRegistry<any>;
|
|
1020
1031
|
};
|
|
1021
1032
|
|
|
1022
|
-
export {
|
|
1033
|
+
export { type ClientBootstrapStatus as A, type BootstrapStatusChangeEvent as B, type ClientOptions as C, type DataLoadRequestedEvent as D, type ClientEvents as E, type Client as F, createClient as G, type MessageReceivedEvent as M, type OptimisticMutationsConfig as O, type QueryExecutedEvent as Q, type SubscriptionCreatedEvent as S, type ClientRouterConstraint as a, type Client$1 as b, type OptimisticMutationsRegistry as c, defineOptimisticMutations as d, type OptimisticHandlerContext as e, type OptimisticStorageProxy as f, type OptimisticOperation as g, type OptimisticInsertOperation as h, type OptimisticUpdateOperation as i, type OptimisticMutationHandler as j, createOptimisticStorageProxy as k, type ClientState as l, useClientState as m, useLoadData as n, type ConnectionStateChangeEvent as o, type ClientStorageLoadedEvent as p, type DataLoadReplyEvent as q, type MutationSentEvent as r, type MutationReceivedEvent as s, type MutationRejectedEvent as t, useLiveQuery as u, type SubscriptionRemovedEvent as v, type QuerySubscriptionTriggeredEvent as w, type StoreStateUpdatedEvent as x, type OptimisticMutationAppliedEvent as y, type OptimisticMutationUndoneEvent as z };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { e as OptimisticHandlerContext, h as OptimisticInsertOperation, j as OptimisticMutationHandler, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, i as OptimisticUpdateOperation, k as createOptimisticStorageProxy, d as defineOptimisticMutations } from './index-
|
|
1
|
+
export { e as OptimisticHandlerContext, h as OptimisticInsertOperation, j as OptimisticMutationHandler, O as OptimisticMutationsConfig, c as OptimisticMutationsRegistry, g as OptimisticOperation, f as OptimisticStorageProxy, i as OptimisticUpdateOperation, k as createOptimisticStorageProxy, d as defineOptimisticMutations } from './index-C0Qm5yHg.js';
|
|
2
2
|
import '@standard-schema/spec';
|
|
3
3
|
import 'zod';
|
package/dist/server.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
'use strict';var ue=require('crypto'),jsXxhash=require('js-xxhash'),rn=require('qs'),zod=require('zod'),kysely=require('kysely'),mysql=require('kysely/helpers/mysql'),postgres=require('kysely/helpers/postgres'),sqlite=require('kysely/helpers/sqlite');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ue__default=/*#__PURE__*/_interopDefault(ue);var rn__default=/*#__PURE__*/_interopDefault(rn);var Tt=Object.create;var Fe=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var Rt=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,xt=Object.prototype.hasOwnProperty;var St=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var vt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Rt(e))!xt.call(i,r)&&r!==t&&Fe(i,r,{get:()=>e[r],enumerable:!(n=gt(e,r))||n.enumerable});return i};var Be=(i,e,t)=>(t=i!=null?Tt(bt(i)):{},vt(Fe(t,"default",{value:i,enumerable:true}),i));var Ce=St(me=>{Object.defineProperty(me,"__esModule",{value:true});me.parse=Zt;me.serialize=Yt;var Ut=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Kt=/^[\u0021-\u003A\u003C-\u007E]*$/,Ht=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Wt=/^[\u0020-\u003A\u003D-\u007E]*$/,Jt=Object.prototype.toString,Gt=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Zt(i,e){let t=new Gt,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||Xt,a=0;do{let u=i.indexOf("=",a);if(u===-1)break;let o=i.indexOf(";",a),s=o===-1?n:o;if(u>s){a=i.lastIndexOf(";",u-1)+1;continue}let c=Je(i,a,u),d=Ge(i,u,c),l=i.slice(c,d);if(t[l]===void 0){let p=Je(i,u+1,s),y=Ge(i,s,p),f=r(i.slice(p,y));t[l]=f;}a=s+1;}while(a<n);return t}function Je(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function Ge(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Yt(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Ut.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Kt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+r;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!Ht.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Wt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!en(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; 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":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return a}function Xt(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function en(i){return Jt.call(i)==="[object Date]"}});var Se=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),S=i=>i?Array.isArray(i.value)?i.value.map(t=>Se(t)?S(t):t):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([t,n])=>Array.isArray(n)?[t,n.map(r=>Se(r)?S(r):r)]:Se(n)?[t,S(n)]:[t,n])):void 0;var Ue="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Z=32;var Nt=16,Ke=10,ze=0xffffffffffff;var F;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(F||(F={}));var B=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Vt(i){let e=Math.floor(i()*Z);return e===Z&&(e=Z-1),Ue.charAt(e)}function kt(i){var n;let e=Qt(),t=e&&(e.crypto||e.msCrypto)||(typeof ue__default.default<"u"?ue__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=ue__default.default)!=null&&n.randomBytes)return ()=>ue__default.default.randomBytes(1).readUInt8()/255;throw new B(F.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Qt(){return Dt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function qt(i,e){let t="";for(;i>0;i--)t=Vt(e)+t;return t}function $t(i,e=Ke){if(isNaN(i))throw new B(F.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>ze)throw new B(F.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ze}: ${i}`);if(i<0)throw new B(F.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new B(F.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%Z,n=Ue.charAt(t)+n,i=(i-t)/Z;return n}function Dt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function He(i,e){let t=kt(),n=Date.now();return $t(n,Ke)+qt(Nt,t)}var le=()=>He().toLowerCase(),ce=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ce(n)}return ce(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ce(r)}throw n}}}),ve=i=>i instanceof Promise?i:ce(i);var W=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var de=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((a,u)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...r}),s={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:a,reject:u};this.queue.has(o)||this.queue.set(o,[]);let c=this.queue.get(o);c&&c.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}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(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var p;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:a,sort:u}=t,o=e.length===1?t.limit:void 0,s=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),c=r,d=(p=Object.entries(s[0]??{})[0])==null?void 0:p[0];if(s.length>0){let y=s.map(f=>f[d]).filter(f=>f!=null);y.length>0&&(c=W(r,{[d]:{$in:y}}));}let l=await this.storage.get({resource:n,where:c,include:a,sort:u,limit:o});for(let y of e){let f=l;if(y.uniqueWhere){let[m,T]=Object.entries(y.uniqueWhere)[0];f=l.filter(g=>{var h;return ((h=g.value[m])==null?void 0:h.value)===T});}y.resolve(f);}}};var Q=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),z=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let a=u=>{u.$and?u.$and.forEach(a):u.$or?u.$or.forEach(a):Object.entries(u).forEach(([o,s])=>{var c;if((c=r.relations)!=null&&c[o]&&(n[o]=true,typeof s=="object"&&s!==null&&!Array.isArray(s))){let d=z(s,r.relations[o].entity.name,t);Object.keys(d).length>0&&(n[o]={include:d});}});};return a(i),n},j=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>j(i,u,t));if(n==="$or")return r.some(u=>j(i,u,t));let a=(r==null?void 0:r.$eq)!==void 0?r==null?void 0:r.$eq:r;if(typeof r=="object"&&r!==null&&(r==null?void 0:r.$eq)===void 0){if(r.$in!==void 0){let o=i[n];return o===void 0?false:t?!r.$in.includes(o):r.$in.includes(o)}if(r.$not!==void 0&&!t)return j(i,{[n]:r.$not},true);if(r.$gt!==void 0){let o=i[n];return typeof o!="number"?false:t?o<=r.$gt:o>r.$gt}if(r.$gte!==void 0){let o=i[n];return typeof o!="number"?false:t?o<r.$gte:o>=r.$gte}if(r.$lt!==void 0){let o=i[n];return typeof o!="number"?false:t?o>=r.$lt:o<r.$lt}if(r.$lte!==void 0){let o=i[n];return typeof o!="number"?false:t?o>r.$lte:o<=r.$lte}let u=i[n];return !u||typeof u!="object"&&!Array.isArray(u)?false:Array.isArray(u)?t?!u.some(o=>j(o,r,false)):u.some(o=>j(o,r,false)):j(u,r,t)}return t?i[n]!==a:i[n]===a}),ye=i=>{if(typeof i!="object"||i===null)return false;let e=i;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},D={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},we=class{level;prefix;constructor(e={}){this.level=e.level??D.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=D.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=D.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=D.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=D.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=D.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},We=i=>new we(i);function Me(i){return Q({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var pe=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,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,a]of Object.entries(n.relations))a.type==="one"&&a.relationalColumn&&t.set(String(a.relationalColumn),{relationName:r,targetResource:a.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let a=this.objectNodes.get(e),u=this.objectNodes.get(t);if(a&&a.referencesObjects.set(n,t),u&&r){let o=u.referencedByObjects.get(r);o||(o=new Set,u.referencedByObjects.set(r,o)),o.add(e);}}removeRelation(e,t,n,r){let a=this.objectNodes.get(e),u=this.objectNodes.get(t);if(a&&a.referencesObjects.delete(n),u&&r){let o=u.referencedByObjects.get(r);o&&(o.delete(e),o.size===0&&u.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let a=r.relations[n];if(!a)return;let u=this.schema[t];if(u!=null&&u.relations){if(a.type==="many"&&a.foreignColumn){for(let[o,s]of Object.entries(u.relations))if(s.entity.name===e&&s.type==="one"&&s.relationalColumn===a.foreignColumn)return o}if(a.type==="one"&&a.relationalColumn){for(let[o,s]of Object.entries(u.relations))if(s.entity.name===e&&s.type==="many"&&s.foreignColumn===a.relationalColumn)return o}}}updateRelationsFromMutation(e,t,n,r){let a=this.getRelationalColumns(e),u=this.objectNodes.get(t);if(u)for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){if(!(r&&o in r))continue;let l=this.getInverseRelationName(e,c,s),p=u.referencesObjects.get(s),y=n[o];p!==y&&(p&&this.removeRelation(t,p,s,l),y&&(this.ensureObjectNode(y,c),this.storeRelation(t,y,s,l)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new de(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),a={},u=[];for(let o of r){this.logger.debug("[QueryEngine] Subscribing to step",o.stepPath.join("."));let s=Me(o),c=a[o.stepPath.at(-2)??""],d=o.stepPath.at(-1)??"",l=this.queryNodes.get(s);if(l)l.subscriptions.add(t);else if(l={hash:s,queryStep:o,relationName:d,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(l.hash,l),c){let p=this.queryNodes.get(c);p&&p.childQueries.add(l.hash);}a[d]=s,u.push(()=>{let p=this.queryNodes.get(s);p&&(p.subscriptions.delete(t),p.subscriptions.size===0&&this.queryNodes.delete(s));});}return ()=>{for(let o of u)o();}}breakdownQuery(e){var T;let{query:t,stepPath:n=[],context:r={},parentResource:a}=e,{include:u}=t,o=n.length===0,s=n.at(-1),c,d,l;if(!o&&a&&s){let g=this.schema[a],h=(T=g==null?void 0:g.relations)==null?void 0:T[s];h&&(l=h.type==="many",h.type==="one"?(c=R=>({id:R}),d=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x[h.relationalColumn])==null?void 0:w.value}).filter(b=>b!==void 0)):(c=R=>({[h.foreignColumn]:R}),d=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x.id)==null?void 0:w.value}).filter(b=>b!==void 0)));}let{include:p,...y}=t,m=[this.router.incrementQueryStep({query:y,stepPath:[...n],getWhere:c,referenceGetter:d,isMany:l,relationName:s},r)];if(u&&typeof u=="object"&&Object.keys(u).length>0){let g=this.schema[t.resource];if(!g)throw new Error(`Resource ${t.resource} not found`);m.push(...Object.entries(u).flatMap(([h,R])=>{let b=g.relations[h];if(!b)throw new Error(`Relation ${h} not found for resource ${t.resource}`);let x=b.entity.name,w=ye(R)?R:null;return this.breakdownQuery({query:{resource:x,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:[...n,h],context:r,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(a=>a.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(a=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",a.length),n[e[0].stepPath.join(".")]=[{data:a}];});for(let a=1;a<e.length;a++){let u=e[a],o=u.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var c,d;let s=n[o];if(!s){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let l=new Map;for(let f of s)for(let m of f.data){let T=(d=(c=m==null?void 0:m.value)==null?void 0:c.id)==null?void 0:d.value;if(!T)continue;let h=u.referenceGetter([m])[0];if(h){l.has(h)||l.set(h,new Set);let R=l.get(h);R&&R.add(T);}}let p=Array.from(l.keys());if(p.length===0){n[u.stepPath.join(".")]=[];return}let y=[];for(let f of p){let m=u.getWhere(f),T={...u,relationalWhere:m},g=await this.resolveStep(T,t),h=l.get(f);if(h)for(let R of Array.from(h))y.push({includedBy:R,data:g});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",y.reduce((f,m)=>f+m.data.length,0)),n[u.stepPath.join(".")]=y;}else {let l=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:l}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,o,s,c,d;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 n=new Map;for(let l of e){let p=l.stepPath.join("."),y=t[p]??[],f=Object.keys(l.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${p}"`,{resource:l.query.resource,includedRelations:f,resultGroups:y.length,isMany:l.isMany,relationName:l.relationName});for(let m of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${p}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let T of m.data){let g=(o=(u=T==null?void 0:T.value)==null?void 0:u.id)==null?void 0:o.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${p}"`);continue}let h=p?`${p}.${g}`:g,R=[];if(l.stepPath.length>0&&m.includedBy){let x=l.stepPath.slice(0,-1).join(".");R=[x?`${x}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${h}" has parent keys:`,R,{stepPath:p,parentStepPath:x,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${h}" (no parent)`);let b=n.get(h);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${h}" already exists, adding parent keys:`,R);for(let x of R)b.includedBy.add(x);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${h}"`,{resource:l.query.resource,path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,includedRelations:f,parentKeys:R}),n.set(h,{data:T,includedBy:new Set(R),path:l.stepPath.at(-1)??"",isMany:l.isMany??false,relationName:l.relationName,resourceName:l.query.resource,includedRelations:f});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),a=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let l=r.length-1;l>=0;l--){let[p,y]=r[l],f=this.schema[y.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${p}"`,{resource:y.resourceName,path:y.path,isMany:y.isMany,relationName:y.relationName,includedRelations:y.includedRelations,parentKeys:Array.from(y.includedBy)});for(let m of y.includedRelations){let T=(c=(s=f==null?void 0:f.relations)==null?void 0:s[m])==null?void 0:c.type,g=!!y.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${p}"`,{relationType:T,hasRelation:g,resourceHasRelation:!!((d=f==null?void 0:f.relations)!=null&&d[m])}),y.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${p}"`,y.data.value[m]);else {let h=T==="many"?{value:[]}:{value:null};y.data.value[m]=h,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${p}" with`,h);}}if(y.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${p}" to resultData`),a.unshift(y.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to ${y.includedBy.size} parent(s)`);for(let m of Array.from(y.includedBy)){let T=n.get(m);if(!T){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${p}"`);continue}let g=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${p}" to parent "${m}" via relation "${g}"`,{isMany:y.isMany,parentHasRelation:!!T.data.value[g]}),y.isMany?(T.data.value[g]??={value:[]},T.data.value[g].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${p}" to many relation "${g}" on parent "${m}"`,{arrayLength:T.data.value[g].value.length})):(T.data.value[g]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${m}" to "${p}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${a.length} root items`),a}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:n,relationalWhere:r}=e,a=n.where&&r?W(n.where,r):r??n.where,u=a?{...n,where:a}:n;return ve(this.router.get(u,t)).then(o=>(this.loadStepResults(e,o),o))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Me(e),r=this.queryNodes.get(n),a=e.query.resource;if(!r)return;let u=this.getRelationalColumns(a);for(let o of t){let s=S(o),c=s.id;this.ensureObjectNode(c,a,n),r.trackedObjects.add(c);for(let[d,{relationName:l,targetResource:p}]of Array.from(u)){let y=s[d];if(y){this.ensureObjectNode(y,p);let f=this.getInverseRelationName(a,p,l);this.storeRelation(c,y,l,f);}}this.loadNestedRelations(a,c,s),this.logger.debug("[QueryEngine] Loaded nested relations for",c);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[a,u]of Object.entries(r.relations)){let o=n[a];if(!o)continue;let s=u.entity.name,c=this.getInverseRelationName(e,s,a);if(u.type==="one")o&&typeof o=="object"&&o.id&&(this.ensureObjectNode(o.id,s),this.storeRelation(t,o.id,a,c),this.loadNestedRelations(s,o.id,o));else if(u.type==="many"&&Array.isArray(o)){for(let d of o)if(d&&typeof d=="object"&&d.id){this.ensureObjectNode(d.id,s);let l=this.getInverseRelationName(s,e,a);l&&this.storeRelation(d.id,t,l,a),this.loadNestedRelations(s,d.id,d);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let a=this.queryNodes.get(r);if(!a||!a.relationName)continue;let u=this.buildIncludeFromChildQueries(r);n[a.relationName]=Object.keys(u).length>0?u:true;}return n}sendInsertsForTree(e,t,n){var o,s;let r=(s=(o=t==null?void 0:t.value)==null?void 0:o.id)==null?void 0:s.value;if(!r)return;let a={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let c of Array.from(e.subscriptions))try{c(a);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:d,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let c of Array.from(e.childQueries)){let d=this.queryNodes.get(c);if(!d||!d.relationName)continue;let l=d.relationName,p=d.queryStep.query.resource,y=t.value[l];if(!y)continue;let f=y.value;if(Array.isArray(f))for(let m of f)this.sendInsertsForTree(d,m,p);else f&&typeof f=="object"&&this.sendInsertsForTree(d,f,p);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=S(t);if(!n)return;let r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,r);let a=this.getRelationalColumns(e.resource);for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){let d=n[o];if(d){this.ensureObjectNode(d,c);let l=this.getInverseRelationName(e.resource,c,s);this.storeRelation(e.resourceId,d,s,l);}}let u=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(o=>{for(let s of o){let c=this.queryNodes.get(s);if(c){c.trackedObjects.add(e.resourceId),u&&u.matchedQueries.add(s);for(let d of Array.from(c.subscriptions))try{d(e);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:l,queryHash:c.hash,resource:e.resource,resourceId:e.resourceId,stepPath:c.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=S(t);if(!n)return;let r=this.objectNodes.get(e.resourceId),a=new Set((r==null?void 0:r.matchedQueries)??[]);r||(r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,r)),this.updateRelationsFromMutation(e.resource,e.resourceId,n,e.payload),this.getMatchingQueries(e,n).then(u=>{let o=new Set(u),s=[],c=[],d=[];for(let p of u)a.has(p)?d.push(p):s.push(p);for(let p of Array.from(a))o.has(p)||c.push(p);for(let p of s){let y=this.queryNodes.get(p);y&&y.trackedObjects.add(e.resourceId);}for(let p of c){let y=this.queryNodes.get(p);y&&y.trackedObjects.delete(e.resourceId);}let l=this.objectNodes.get(e.resourceId);if(l){for(let p of s)l.matchedQueries.add(p);for(let p of c)l.matchedQueries.delete(p);}for(let p of [...c,...d]){let y=this.queryNodes.get(p);if(y)for(let f of Array.from(y.subscriptions))try{f(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(s.length>0)for(let p of s){let y=this.queryNodes.get(p);if(!y)continue;let f=this.buildIncludeFromChildQueries(p);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(y,m[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?ve([]):Promise.all(n.map(async r=>{let a=r.queryStep.query.where,u=r.queryStep.query.resource,o=e.resourceId,s=this.objectNodes.get(o);if(!s)return {hash:r.hash,matches:false};if(r.relationName){let y=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,f=y==null?void 0:y.queryStep.query.resource,m=f?this.getInverseRelationName(f,u,r.relationName):void 0,T=m?s.referencesObjects.get(m):void 0;if(!T)return {hash:r.hash,matches:false};let g=this.objectNodes.get(T);return !g||!y||!g.matchedQueries.has(y.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!a)return {hash:r.hash,matches:true};let c=z(a,u,this.schema),d=Object.keys(c).length>0;if(!d&&t!==void 0)return {hash:r.hash,matches:j(t,a)};let l=await this.storage.get({resource:u,where:{id:o},include:d?c:void 0});if(!l||l.length===0)return {hash:r.hash,matches:false};let p=S(l[0]);return p?{hash:r.hash,matches:j(p,a)}:{hash:r.hash,matches:false}})).then(r=>r.filter(a=>a.matches).map(a=>a.hash))}};var Rr=i=>i,Ft=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],Bt=i=>i.length===1?i[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let a of i){let u=await a({...e,value:n,rawValue:t});u&&(t=u,n=S(t),n.id=e.value.id,r=true);}return r?t:void 0}),zt=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),Ie=i=>{let e=i.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of Ft){let r=e.map(a=>a[n]).filter(a=>a!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=zt(r):t[n]=Bt(r));}return t},br=(...i)=>{let e={},t=new Set;for(let n of i)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=i.map(u=>u[n]),a=Ie(r);a&&(e[n]=a);}return e};var tt=Be(Ce());var fe=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),Le=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.any().nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),tn=Le.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ze=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),Ye=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),J=Ze.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:Ye}),Y=Ze.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:tn,meta:Ye});zod.z.union([Y,J]);var Xe=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var et=fe.omit({resource:true}),he=J.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:J.shape.meta}),Ae=Y.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([Ae,he]);var je=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(je);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=je(n);return e}return i},nt=i=>{let e=i.logger;return async t=>{var n;try{let r=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,a={headers:r,cookies:r.cookie?tt.default.parse(r.cookie):{}},u=new URL(t.url),o=u.pathname.split("/"),s=u.searchParams,c=je(rn__default.default.parse(s.toString())),d=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:a.headers,cookies:a.cookies,queryParams:c}))??{};if(t.method==="GET"){let l=o[o.length-1],{success:p,data:y,error:f}=et.safeParse(c);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:f},{status:400});let m=await i.handleQuery({req:{...a,...y,type:"QUERY",resource:l,context:d,queryParams:c}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.data)}if(t.method==="POST")try{let l=o[o.length-1],p=o[o.length-2];if(p==="query"){if(o.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let h=o[o.length-3],R=t.body?await t.json():{};if(!h||h.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let b=await i.handleCustomQuery({req:{...a,type:"CUSTOM_QUERY",resource:h,procedure:l,input:R.input,context:d,queryParams:c}});return Response.json(b)}let y=p,f=t.body?await t.json():{},m,T=l;if(l==="insert"||l==="update"){let h=Ae.safeParse(f);if(h.success)m=h.data,T=l.toUpperCase();else {if(!(typeof f=="object"&&f!==null&&"payload"in f&&"meta"in f))return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:h.error},{status:400});let b=he.safeParse(f);if(!b.success)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b.error},{status:400});m=b.data;}}else {let{success:h,data:R,error:b}=he.safeParse(f);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});m=R;}let g=await i.handleMutation({req:{...a,type:"MUTATE",resource:y,input:m.payload,context:d,resourceId:m.resourceId,procedure:T,queryParams:{},meta:m.meta}});return Response.json(g)}catch(l){return e.error("Error parsing mutation from the client:",l),l instanceof Error&&l.message.includes("Unknown procedure")?Response.json({message:l.message,code:"UNKNOWN_PROCEDURE"},{status:400}):Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(r){return e.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var at=Be(Ce());var _=zod.z.string(),Ee=zod.z.union([Xe,fe]),an=zod.z.object({id:_,type:zod.z.literal("SUBSCRIBE")}).and(Ee),sn=zod.z.object({id:_,type:zod.z.literal("UNSUBSCRIBE")}).and(Ee),on=zod.z.object({id:_,type:zod.z.literal("QUERY")}).and(Ee),un=zod.z.object({id:_,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),rt=Y.extend({id:_}),cn=J.extend({id:_}),ln=zod.z.union([cn,rt]),it=zod.z.union([an,on,un,ln,sn]),dn=zod.z.object({id:_,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),yn=zod.z.object({id:_,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([dn,yn,rt]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Le)});var st=i=>{let e={},t=i.logger;return (n,r)=>{var l;let a=p=>{n.send(JSON.stringify(p));},u=le(),o=new Map,s={headers:r.headers,cookies:typeof r.headers.cookie=="string"?at.default.parse(r.headers.cookie):{}},c=rn.parse(r.url.split("?")[1]),d=(l=i.contextProvider)==null?void 0:l.call(i,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),n.on("message",async p=>{try{t.debug("Message received from the client:",p);let y=it.parse(JSON.parse(p.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:f,id:m,...T}=y,g=f==="SUBSCRIBE";if("procedure"in T){let h=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:T.resource,procedure:T.procedure,input:T.input,context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(g){if(!h||!h.data||!h.query)throw new Error("Invalid resource");h.unsubscribe&&o.set(Q(T),h.unsubscribe),a({id:m,type:"REPLY",data:{resource:h.query.resource,data:(h.data??[]).map(R=>R.value)}});}else a({id:m,type:"REPLY",data:h});}else {let h=await i.handleQuery({req:{...s,...T,type:"QUERY",context:await d??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(!h||!h.data)throw new Error("Invalid resource");g&&h.unsubscribe&&o.set(Q(T),h.unsubscribe),a({id:m,type:"REPLY",data:{resource:T.resource,data:(h.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:f,id:m,...T}=y,g=o.get(Q(T));g&&(g(),o.delete(Q(T)));}else if(y.type==="CUSTOM_QUERY"){let{resource:f,procedure:m,input:T,id:g}=y;t.debug("Received custom query from client:",y);try{let h=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:f,procedure:m,input:T,context:await d??{},queryParams:c}});a({id:g,type:"REPLY",data:h});}catch(h){a({id:g,type:"REJECT",resource:f,message:h.message}),t.error("Error handling custom query from the client:",h);}}else if(y.type==="MUTATE"){let{resource:f}=y;t.debug("Received mutation from client:",y);try{let m=await i.handleMutation({req:{...s,type:"MUTATE",resource:f,input:y.payload,context:{messageId:y.id,...await d??{}},resourceId:y.resourceId,procedure:y.procedure,queryParams:c,meta:y.meta}});y.procedure&&y.procedure!=="INSERT"&&y.procedure!=="UPDATE"&&a({id:y.id,type:"REPLY",data:m});}catch(m){a({id:y.id,type:"REJECT",resource:f,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}catch(y){t.error("Error handling message from the client:",y);}}),n.on("close",()=>{t.info("Connection closed",u),delete e[u];for(let p of Array.from(o.values()))p();});}};function ot(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Hr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,st(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{nt(e)(ot(n)).then(u=>u.json().then(o=>r.status(u.status).send(o)));});};var Te=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,a,u,o,s){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=a,this._single=u,this._sort=o,this._shouldAwait=s,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new i(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new i(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new i(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 i(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new i(this._collection,this._client,this._where,this._include,this._limit,this._single,n,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,n){return new i(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var mn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Oe=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>mn(n)?S(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function U(i,e,t){let n=new Oe(i),r=u=>{let o=Te._init(u,n,true);return Object.assign(Object.create(o),{insert:async c=>{let d=i._getTimestamp(),l=await i.rawInsert(u.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([p,y])=>[p,{value:y,_meta:{timestamp:d}}]))},void 0,t);return S(l.data)},update:async(c,d)=>{let l=i._getTimestamp(),{id:p,...y}=d,f=await i.rawUpdate(u.name,c,{value:Object.fromEntries(Object.entries(y).map(([g,h])=>[g,{value:h,_meta:{timestamp:l}}]))},void 0,t),m=S(f.data),T={};for(let g of Object.keys(y))g in m&&(T[g]=m[g]);return T}})},a={get(u,o){if(o==="findOne")return i.findOne.bind(i);if(o==="find")return i.find.bind(i);if(o==="insert")return (s,c)=>{let d=i._getTimestamp();return i.rawInsert(s.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([l,p])=>[l,{value:p,_meta:{timestamp:d}}]))},void 0,t).then(l=>S(l.data))};if(o==="update")return (s,c,d)=>{let l=i._getTimestamp(),{id:p,...y}=d;return i.rawUpdate(s.name,c,{value:Object.fromEntries(Object.entries(y).map(([f,m])=>[f,{value:m,_meta:{timestamp:l}}]))},void 0,t).then(f=>{let m=S(f.data),T={};for(let g of Object.keys(y))g in m&&(T[g]=m[g]);return T})};if(o==="transaction")return async s=>i.transaction(async({trx:c,commit:d,rollback:l})=>{let p=U(c,e,t);return s({trx:p,commit:d,rollback:l})});if(o in e){let s=e[o];return r(s)}}};return new Proxy({},a)}var Pe=class i{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 n=t;n.hooks&&this.hooksRegistry.set(n.resourceSchema.name,n.hooks);}}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}},ri=i=>Pe.create({...i}),ct=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),lt=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Ne=class i{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,n,r,a){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=n??{},this.authorization=r,this.hooks=a;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:lt,query:ct}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=u;return new i(this.resourceSchema,n,r,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new i(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},a=Q(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:a}})(e);handleMutation=async({req:e,db:t,schema:n})=>{var o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),a=t._setMutationTimestamp(r),u=U(a,n,e.context);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let c=s.procedure==="INSERT"?"insert":s.procedure==="UPDATE"?"update":void 0,d=this.customMutations[s.procedure]?s.procedure:c&&this.customMutations[c]?c:s.procedure,l=this.customMutations[d];if(l){s.procedure=d;let p=l.inputValidator["~standard"].validate(s.input),y=p instanceof Promise?await p:p;if(y.issues){let f=y.issues.map(m=>{var g;let T=(g=m.path)==null?void 0:g.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return T?`${T}: ${m.message}`:m.message}).join(", ");throw new Error(`Validation failed: ${f}`)}return s.input=y.value,l.handler({req:s,db:u})}else {if(s.procedure==="INSERT"||s.procedure==="UPDATE")return this.handleSet({req:s,db:a,operation:s.procedure,schema:n});throw new Error(`Unknown procedure: ${s.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=U(t,n,e.context);return await this.wrapInMiddlewares(async a=>{let u=this.customQueries[a.procedure];if(!u)throw new Error(`Unknown query procedure: ${a.procedure}`);let o=u.inputValidator["~standard"].validate(a.input),s=o instanceof Promise?await o:o;if(s.issues){let c=s.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return a.input=s.value,u.handler({req:a,db:r})})(e)};getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&a)throw new Error("Resource already exists");if(n==="UPDATE"&&!a)throw new Error("Resource not found");let u={value:e.input};return t.transaction(async({trx:o})=>{var d,l,p,y,f,m,T;if(n==="INSERT"){let{data:g,acceptedValues:h}=await o.rawInsert(e.resource,e.resourceId,u,(d=e.context)==null?void 0:d.messageId,e.context);if(!h)throw new Error("Mutation rejected");let R=S(g);if(R.id=R.id??e.resourceId,(l=this.authorization)!=null&&l.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let x=z(b,e.resource,r),w=Object.keys(x).length>0?await o.rawFindById(e.resource,e.resourceId,x):g,O=S(w);if(O.id=O.id??e.resourceId,!j(O,b))throw new Error("Not authorized")}}return {data:g,acceptedValues:h}}if((y=(p=this.authorization)==null?void 0:p.update)!=null&&y.preMutation){let g=S(a);g.id=g.id??e.resourceId;let h=this.authorization.update.preMutation({ctx:e.context,value:g});if(typeof h=="boolean"){if(!h)throw new Error("Not authorized")}else {let R=z(h,e.resource,r),b=Object.keys(R).length>0?await o.rawFindById(e.resource,e.resourceId,R):a,x=S(b);if(x.id=x.id??e.resourceId,!j(x,h))throw new Error("Not authorized")}}let{data:s,acceptedValues:c}=await o.rawUpdate(e.resource,e.resourceId,u,(f=e.context)==null?void 0:f.messageId,e.context);if(!c)throw new Error("Mutation rejected");if((T=(m=this.authorization)==null?void 0:m.update)!=null&&T.postMutation){let g=S(s);g.id=g.id??e.resourceId;let h=this.authorization.update.postMutation({ctx:e.context,value:g});if(typeof h=="boolean"){if(!h)throw new Error("Not authorized")}else {let R=z(h,e.resource,r),b=Object.keys(R).length>0?await o.rawFindById(e.resource,e.resourceId,R):s,x=S(b);if(x.id=x.id??e.resourceId,!j(x,h))throw new Error("Not authorized")}}return {data:s,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}},Ve=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:n})=>{var o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),a=t._setMutationTimestamp(r),u=U(a,n,e.context);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[s.procedure];if(c){let d=c.inputValidator["~standard"].validate(s.input),l=d instanceof Promise?await d:d;if(l.issues){let p=l.issues.map(y=>{var m;let f=(m=y.path)==null?void 0:m.map(T=>typeof T=="object"&&"key"in T?String(T.key):String(T)).join(".");return f?`${f}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return s.input=l.value,c.handler({req:s,db:u})}throw new Error(`Unknown procedure: ${s.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=U(t,n,e.context);return await this.wrapInMiddlewares(async a=>{let u=this.customQueries[a.procedure];if(!u)throw new Error(`Unknown query procedure: ${a.procedure}`);let o=u.inputValidator["~standard"].validate(a.input),s=o instanceof Promise?await o:o;if(s.issues){let c=s.issues.map(d=>{var p;let l=(p=d.path)==null?void 0:p.map(y=>typeof y=="object"&&"key"in y?String(y.key):String(y)).join(".");return l?`${l}: ${d.message}`:d.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return a.input=s.value,u.handler({req:a,db:r})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}};function ii(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var ke=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Ne(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:lt,query:ct}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=u;return new Ve(n,r).use(...this.middlewares)}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new i([...this.middlewares,...t])}static create(){return new i}},ai=ke.create;var X=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 n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([a,u])=>[a,{value:u,_meta:{timestamp:n}}]))});return S(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:a,...u}=n,o=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(u).map(([d,l])=>[d,{value:l,_meta:{timestamp:r}}]))}),s=S(o.data),c={};for(let d of Object.keys(u))d in s&&(c[d]=s[d]);return c}};var xn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function q(i){var r,a,u;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((u=(a=t.constructor)==null?void 0:a.name)==null?void 0:u.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function dt(i){let e=q(i);return xn[e]}var Sn="42701";function ee(i){var t;if(i.code===Sn)return true;let e=((t=i.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function qe(i,e){let{type:t,enumValues:n,enumName:r}=i;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function vn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let a of Object.values(e))for(let u of Object.values(a.fields)){let o=u.getStorageFieldType();o.enumValues&&o.enumName&&r.set(o.enumName,{name:o.enumName,values:o.enumValues});}for(let a of Array.from(r.values())){let{name:u,values:o}=a;try{let s=o.map(c=>`'${c}'`).join(", ");await kysely.sql`
|
|
1
|
+
'use strict';var ue=require('crypto'),jsXxhash=require('js-xxhash'),un=require('qs'),zod=require('zod'),kysely=require('kysely'),mysql=require('kysely/helpers/mysql'),postgres=require('kysely/helpers/postgres'),sqlite=require('kysely/helpers/sqlite');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ue__default=/*#__PURE__*/_interopDefault(ue);var un__default=/*#__PURE__*/_interopDefault(un);var xt=Object.create;var Ke=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty;var It=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Ct=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vt(e))!Mt.call(i,r)&&r!==t&&Ke(i,r,{get:()=>e[r],enumerable:!(n=St(e,r))||n.enumerable});return i};var He=(i,e,t)=>(t=i!=null?xt(wt(i)):{},Ct(Ke(t,"default",{value:i,enumerable:true}),i));var je=It(me=>{Object.defineProperty(me,"__esModule",{value:true});me.parse=tn;me.serialize=nn;var Jt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Gt=/^[\u0021-\u003A\u003C-\u007E]*$/,Zt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Yt=/^[\u0020-\u003A\u003D-\u007E]*$/,Xt=Object.prototype.toString,en=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function tn(i,e){let t=new en,n=i.length;if(n<2)return t;let r=(e==null?void 0:e.decode)||rn,a=0;do{let u=i.indexOf("=",a);if(u===-1)break;let o=i.indexOf(";",a),s=o===-1?n:o;if(u>s){a=i.lastIndexOf(";",u-1)+1;continue}let c=Xe(i,a,u),l=et(i,u,c),d=i.slice(c,l);if(t[d]===void 0){let y=Xe(i,u+1,s),p=et(i,s,y),h=r(i.slice(y,p));t[d]=h;}a=s+1;}while(a<n);return t}function Xe(i,e,t){do{let n=i.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function et(i,e,t){for(;e>t;){let n=i.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function nn(i,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Jt.test(i))throw new TypeError(`argument name is invalid: ${i}`);let r=n(e);if(!Gt.test(r))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+r;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!Zt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Yt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!an(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; 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":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return a}function rn(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function an(i){return Xt.call(i)==="[object Date]"}});var Me=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),S=i=>i?Array.isArray(i.value)?i.value.map(t=>Me(t)?S(t):t):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([t,n])=>Array.isArray(n)?[t,n.map(r=>Me(r)?S(r):r)]:Me(n)?[t,S(n)]:[t,n])):void 0;var Je="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Z=32;var qt=16,Ge=10,We=0xffffffffffff;var B;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(B||(B={}));var z=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function $t(i){let e=Math.floor(i()*Z);return e===Z&&(e=Z-1),Je.charAt(e)}function Dt(i){var n;let e=_t(),t=e&&(e.crypto||e.msCrypto)||(typeof ue__default.default<"u"?ue__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let r=new Uint8Array(1);return t.getRandomValues(r),r[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=ue__default.default)!=null&&n.randomBytes)return ()=>ue__default.default.randomBytes(1).readUInt8()/255;throw new z(B.PRNGDetectFailure,"Failed to find a reliable PRNG")}function _t(){return zt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ft(i,e){let t="";for(;i>0;i--)t=$t(e)+t;return t}function Bt(i,e=Ge){if(isNaN(i))throw new z(B.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>We)throw new z(B.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${We}: ${i}`);if(i<0)throw new z(B.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new z(B.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,n="";for(let r=e;r>0;r--)t=i%Z,n=Je.charAt(t)+n,i=(i-t)/Z;return n}function zt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Ze(i,e){let t=Dt(),n=Date.now();return Bt(n,Ge)+Ft(qt,t)}var le=()=>Ze().toLowerCase(),ce=i=>({then(e,t){try{if(e){let n=e(i);return n instanceof Promise?n:ce(n)}return ce(i)}catch(n){if(t){let r=t(n);return r instanceof Promise?r:ce(r)}throw n}}}),Ie=i=>i instanceof Promise?i:ce(i);var J=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var de=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...r}){return new Promise((a,u)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...r}),s={resource:e,commonWhere:t,uniqueWhere:n,...r,resolve:a,reject:u};this.queue.has(o)||this.queue.set(o,[]);let c=this.queue.get(o);c&&c.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...r}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(r??{})}`}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(n){t.forEach(r=>{r.reject(n);});}}async executeBatchedRequests(e){var y;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:r,include:a,sort:u}=t,o=e.length===1?t.limit:void 0,s=e.map(p=>p.uniqueWhere).filter(p=>p!==void 0),c=r,l=(y=Object.entries(s[0]??{})[0])==null?void 0:y[0];if(s.length>0){let p=s.map(h=>h[l]).filter(h=>h!=null);p.length>0&&(c=J(r,{[l]:{$in:p}}));}let d=await this.storage.get({resource:n,where:c,include:a,sort:u,limit:o});for(let p of e){let h=d;if(p.uniqueWhere){let[f,m]=Object.entries(p.uniqueWhere)[0];h=d.filter(g=>{var T;return ((T=g.value[f])==null?void 0:T.value)===m});}p.resolve(h);}}};var $=i=>jsXxhash.xxHash32(JSON.stringify(i)).toString(32),U=(i,e,t)=>{let n={},r=t[e];if(!r)return n;let a=u=>{u.$and?u.$and.forEach(a):u.$or?u.$or.forEach(a):Object.entries(u).forEach(([o,s])=>{var c;if((c=r.relations)!=null&&c[o]&&(n[o]=true,typeof s=="object"&&s!==null&&!Array.isArray(s))){let l=U(s,r.relations[o].entity.name,t);Object.keys(l).length>0&&(n[o]={include:l});}});};return a(i),n},P=(i,e,t=false)=>Object.entries(e).every(([n,r])=>{if(n==="$and")return r.every(u=>P(i,u,t));if(n==="$or")return r.some(u=>P(i,u,t));let a=(r==null?void 0:r.$eq)!==void 0?r==null?void 0:r.$eq:r;if(typeof r=="object"&&r!==null&&(r==null?void 0:r.$eq)===void 0){if(r.$in!==void 0){let o=i[n];return o===void 0?false:t?!r.$in.includes(o):r.$in.includes(o)}if(r.$not!==void 0&&!t)return P(i,{[n]:r.$not},true);if(r.$gt!==void 0){let o=i[n];return typeof o!="number"?false:t?o<=r.$gt:o>r.$gt}if(r.$gte!==void 0){let o=i[n];return typeof o!="number"?false:t?o<r.$gte:o>=r.$gte}if(r.$lt!==void 0){let o=i[n];return typeof o!="number"?false:t?o>=r.$lt:o<r.$lt}if(r.$lte!==void 0){let o=i[n];return typeof o!="number"?false:t?o>r.$lte:o<=r.$lte}let u=i[n];return !u||typeof u!="object"&&!Array.isArray(u)?false:Array.isArray(u)?t?!u.some(o=>P(o,r,false)):u.some(o=>P(o,r,false)):P(u,r,t)}return t?i[n]!==a:i[n]===a}),ye=i=>{if(typeof i!="object"||i===null)return false;let e=i;return "where"in e||"limit"in e||"orderBy"in e||"include"in e},_={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},Ce=class{level;prefix;constructor(e={}){this.level=e.level??_.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=_.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=_.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=_.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=_.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=_.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},Ye=i=>new Ce(i);function Le(i){return $({resource:i.query.resource,where:i.query.where,include:i.query.include,stepPath:i.stepPath,isMany:i.isMany,relationName:i.relationName})}var pe=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,n=this.schema[e];if(!(n!=null&&n.relations))return t;for(let[r,a]of Object.entries(n.relations))a.type==="one"&&a.relationalColumn&&t.set(String(a.relationalColumn),{relationName:r,targetResource:a.entity.name});return t}ensureObjectNode(e,t,n){let r=this.objectNodes.get(e);return r?n&&r.matchedQueries.add(n):(r={id:e,type:t,matchedQueries:new Set(n?[n]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,r)),r}storeRelation(e,t,n,r){let a=this.objectNodes.get(e),u=this.objectNodes.get(t);if(a&&a.referencesObjects.set(n,t),u&&r){let o=u.referencedByObjects.get(r);o||(o=new Set,u.referencedByObjects.set(r,o)),o.add(e);}}removeRelation(e,t,n,r){let a=this.objectNodes.get(e),u=this.objectNodes.get(t);if(a&&a.referencesObjects.delete(n),u&&r){let o=u.referencedByObjects.get(r);o&&(o.delete(e),o.size===0&&u.referencedByObjects.delete(r));}}getInverseRelationName(e,t,n){let r=this.schema[e];if(!(r!=null&&r.relations))return;let a=r.relations[n];if(!a)return;let u=this.schema[t];if(u!=null&&u.relations){if(a.type==="many"&&a.foreignColumn){for(let[o,s]of Object.entries(u.relations))if(s.entity.name===e&&s.type==="one"&&s.relationalColumn===a.foreignColumn)return o}if(a.type==="one"&&a.relationalColumn){for(let[o,s]of Object.entries(u.relations))if(s.entity.name===e&&s.type==="many"&&s.foreignColumn===a.relationalColumn)return o}}}updateRelationsFromMutation(e,t,n,r){let a=this.getRelationalColumns(e),u=this.objectNodes.get(t);if(u)for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){if(!(r&&o in r))continue;let d=this.getInverseRelationName(e,c,s),y=u.referencesObjects.get(s),p=n[o];y!==p&&(y&&this.removeRelation(t,y,s,d),p&&(this.ensureObjectNode(p,c),this.storeRelation(t,p,s,d)));}}get(e,t){let n=this.breakdownQuery({query:e,context:(t==null?void 0:t.context)??{}});return this.resolveQuery(n,{context:(t==null?void 0:t.context)??{},batcher:(t==null?void 0:t.batcher)??new de(this.storage)})}subscribe(e,t,n={}){let r=this.breakdownQuery({query:e,context:n}),a={},u=[];for(let o of r){this.logger.debug("[QueryEngine] Subscribing to step",o.stepPath.join("."));let s=Le(o),c=a[o.stepPath.at(-2)??""],l=o.stepPath.at(-1)??"",d=this.queryNodes.get(s);if(d)d.subscriptions.add(t);else if(d={hash:s,queryStep:o,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:c,childQueries:new Set},this.queryNodes.set(d.hash,d),c){let y=this.queryNodes.get(c);y&&y.childQueries.add(d.hash);}a[l]=s,u.push(()=>{let y=this.queryNodes.get(s);y&&(y.subscriptions.delete(t),y.subscriptions.size===0&&this.queryNodes.delete(s));});}return ()=>{for(let o of u)o();}}breakdownQuery(e){var m;let{query:t,stepPath:n=[],context:r={},parentResource:a}=e,{include:u}=t,o=n.length===0,s=n.at(-1),c,l,d;if(!o&&a&&s){let g=this.schema[a],T=(m=g==null?void 0:g.relations)==null?void 0:m[s];T&&(d=T.type==="many",T.type==="one"?(c=R=>({id:R}),l=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x[T.relationalColumn])==null?void 0:w.value}).filter(b=>b!==void 0)):(c=R=>({[T.foreignColumn]:R}),l=R=>R.map(b=>{var x,w;return (w=(x=b.value)==null?void 0:x.id)==null?void 0:w.value}).filter(b=>b!==void 0)));}let{include:y,...p}=t,f=[this.router.incrementQueryStep({query:p,stepPath:[...n],getWhere:c,referenceGetter:l,isMany:d,relationName:s},r)];if(u&&typeof u=="object"&&Object.keys(u).length>0){let g=this.schema[t.resource];if(!g)throw new Error(`Resource ${t.resource} not found`);f.push(...Object.entries(u).flatMap(([T,R])=>{let b=g.relations[T];if(!b)throw new Error(`Relation ${T} not found for resource ${t.resource}`);let x=b.entity.name,w=ye(R)?R:null;return this.breakdownQuery({query:{resource:x,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:[...n,T],context:r,parentResource:t.resource})}));}return f}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(a=>a.stepPath.join(".")).join(" -> "));let n={},r=this.resolveStep(e[0],t).then(a=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",a.length),n[e[0].stepPath.join(".")]=[{data:a}];});for(let a=1;a<e.length;a++){let u=e[a],o=u.stepPath.slice(0,-1).join(".");r=r.then(async()=>{var c,l;let s=n[o];if(!s){n[u.stepPath.join(".")]=[];return}if(u.referenceGetter&&u.getWhere){let d=new Map;for(let h of s)for(let f of h.data){let m=(l=(c=f==null?void 0:f.value)==null?void 0:c.id)==null?void 0:l.value;if(!m)continue;let T=u.referenceGetter([f])[0];if(T){d.has(T)||d.set(T,new Set);let R=d.get(T);R&&R.add(m);}}let y=Array.from(d.keys());if(y.length===0){n[u.stepPath.join(".")]=[];return}let p=[];for(let h of y){let f=u.getWhere(h),m={...u,relationalWhere:f},g=await this.resolveStep(m,t),T=d.get(h);if(T)for(let R of Array.from(T))p.push({includedBy:R,data:g});}this.logger.debug("[QueryEngine] Resolved step",u.stepPath.join("."),"with results count:",p.reduce((h,f)=>h+f.data.length,0)),n[u.stepPath.join(".")]=p;}else {let d=await this.resolveStep(u,t);n[u.stepPath.join(".")]=[{data:d}];}});}return r=r.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,n)))),r}assembleResults(e,t){var u,o,s,c,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 n=new Map;for(let d of e){let y=d.stepPath.join("."),p=t[y]??[],h=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${y}"`,{resource:d.query.resource,includedRelations:h,resultGroups:p.length,isMany:d.isMany,relationName:d.relationName});for(let f of p){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${y}"`,{dataCount:f.data.length,includedBy:f.includedBy});for(let m of f.data){let g=(o=(u=m==null?void 0:m.value)==null?void 0:u.id)==null?void 0:o.value;if(!g){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${y}"`);continue}let T=y?`${y}.${g}`:g,R=[];if(d.stepPath.length>0&&f.includedBy){let x=d.stepPath.slice(0,-1).join(".");R=[x?`${x}.${f.includedBy}`:f.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${T}" has parent keys:`,R,{stepPath:y,parentStepPath:x,includedBy:f.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${T}" (no parent)`);let b=n.get(T);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${T}" already exists, adding parent keys:`,R);for(let x of R)b.includedBy.add(x);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${T}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:h,parentKeys:R}),n.set(T,{data:m,includedBy:new Set(R),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:h});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${n.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(n.keys()));let r=Array.from(n.entries()),a=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${r.length} entries`);for(let d=r.length-1;d>=0;d--){let[y,p]=r[d],h=this.schema[p.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${y}"`,{resource:p.resourceName,path:p.path,isMany:p.isMany,relationName:p.relationName,includedRelations:p.includedRelations,parentKeys:Array.from(p.includedBy)});for(let f of p.includedRelations){let m=(c=(s=h==null?void 0:h.relations)==null?void 0:s[f])==null?void 0:c.type,g=!!p.data.value[f];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${f}" for "${y}"`,{relationType:m,hasRelation:g,resourceHasRelation:!!((l=h==null?void 0:h.relations)!=null&&l[f])}),p.data.value[f])this.logger.debug(`[QueryEngine] assembleResults: Relation "${f}" already exists for "${y}"`,p.data.value[f]);else {let T=m==="many"?{value:[]}:{value:null};p.data.value[f]=T,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${f}" for "${y}" with`,T);}}if(p.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${y}" to resultData`),a.unshift(p.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to ${p.includedBy.size} parent(s)`);for(let f of Array.from(p.includedBy)){let m=n.get(f);if(!m){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${f}" not found in entriesMap for child "${y}"`);continue}let g=p.relationName??p.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to parent "${f}" via relation "${g}"`,{isMany:p.isMany,parentHasRelation:!!m.data.value[g]}),p.isMany?(m.data.value[g]??={value:[]},m.data.value[g].value.push(p.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${y}" to many relation "${g}" on parent "${f}"`,{arrayLength:m.data.value[g].value.length})):(m.data.value[g]=p.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${g}" on parent "${f}" to "${y}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${a.length} root items`),a}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:n,relationalWhere:r}=e,a=n.where&&r?J(n.where,r):r??n.where,u=a?{...n,where:a}:n;return Ie(this.router.get(u,t)).then(o=>(this.loadStepResults(e,o),o))}loadStepResults(e,t){this.logger.debug("[QueryEngine] Loading step results",e.stepPath.join("."),"with results",JSON.stringify(t,null,2));let n=Le(e),r=this.queryNodes.get(n),a=e.query.resource;if(!r)return;let u=this.getRelationalColumns(a);for(let o of t){let s=S(o),c=s.id;this.ensureObjectNode(c,a,n),r.trackedObjects.add(c);for(let[l,{relationName:d,targetResource:y}]of Array.from(u)){let p=s[l];if(p){this.ensureObjectNode(p,y);let h=this.getInverseRelationName(a,y,d);this.storeRelation(c,p,d,h);}}this.loadNestedRelations(a,c,s),this.logger.debug("[QueryEngine] Loaded nested relations for",c);}}loadNestedRelations(e,t,n){let r=this.schema[e];if(r!=null&&r.relations)for(let[a,u]of Object.entries(r.relations)){let o=n[a];if(!o)continue;let s=u.entity.name,c=this.getInverseRelationName(e,s,a);if(u.type==="one")o&&typeof o=="object"&&o.id&&(this.ensureObjectNode(o.id,s),this.storeRelation(t,o.id,a,c),this.loadNestedRelations(s,o.id,o));else if(u.type==="many"&&Array.isArray(o)){for(let l of o)if(l&&typeof l=="object"&&l.id){this.ensureObjectNode(l.id,s);let d=this.getInverseRelationName(s,e,a);d&&this.storeRelation(l.id,t,d,a),this.loadNestedRelations(s,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let n={};for(let r of Array.from(t.childQueries)){let a=this.queryNodes.get(r);if(!a||!a.relationName)continue;let u=this.buildIncludeFromChildQueries(r);n[a.relationName]=Object.keys(u).length>0?u:true;}return n}sendInsertsForTree(e,t,n){var o,s;let r=(s=(o=t==null?void 0:t.value)==null?void 0:o.id)==null?void 0:s.value;if(!r)return;let a={procedure:"INSERT",resource:n,resourceId:r,type:"MUTATE",payload:t.value};for(let c of Array.from(e.subscriptions))try{c(a);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:n,resourceId:r,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(r),this.ensureObjectNode(r,n,e.hash).matchedQueries.add(e.hash);for(let c of Array.from(e.childQueries)){let l=this.queryNodes.get(c);if(!l||!l.relationName)continue;let d=l.relationName,y=l.queryStep.query.resource,p=t.value[d];if(!p)continue;let h=p.value;if(Array.isArray(h))for(let f of h)this.sendInsertsForTree(l,f,y);else h&&typeof h=="object"&&this.sendInsertsForTree(l,h,y);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let n=S(t);if(!n)return;let r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,r);let a=this.getRelationalColumns(e.resource);for(let[o,{relationName:s,targetResource:c}]of Array.from(a)){let l=n[o];if(l){this.ensureObjectNode(l,c);let d=this.getInverseRelationName(e.resource,c,s);this.storeRelation(e.resourceId,l,s,d);}}let u=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,n).then(o=>{for(let s of o){let c=this.queryNodes.get(s);if(c){c.trackedObjects.add(e.resourceId),u&&u.matchedQueries.add(s);for(let l of Array.from(c.subscriptions))try{l(e);}catch(d){this.logger.error("[QueryEngine] Error in subscription callback during INSERT mutation",{error:d,queryHash:c.hash,resource:e.resource,resourceId:e.resourceId,stepPath:c.queryStep.stepPath.join(".")});}}}});return}if(e.procedure==="UPDATE"){let n=S(t);if(!n)return;let r=this.objectNodes.get(e.resourceId),a=new Set((r==null?void 0:r.matchedQueries)??[]);r||(r={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,r)),this.updateRelationsFromMutation(e.resource,e.resourceId,n,e.payload),this.getMatchingQueries(e,n).then(u=>{let o=new Set(u),s=[],c=[],l=[];for(let y of u)a.has(y)?l.push(y):s.push(y);for(let y of Array.from(a))o.has(y)||c.push(y);for(let y of s){let p=this.queryNodes.get(y);p&&p.trackedObjects.add(e.resourceId);}for(let y of c){let p=this.queryNodes.get(y);p&&p.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let y of s)d.matchedQueries.add(y);for(let y of c)d.matchedQueries.delete(y);}for(let y of [...c,...l]){let p=this.queryNodes.get(y);if(p)for(let h of Array.from(p.subscriptions))try{h(e);}catch(f){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:f,queryHash:p.hash,resource:e.resource,resourceId:e.resourceId,stepPath:p.queryStep.stepPath.join(".")});}}if(s.length>0)for(let y of s){let p=this.queryNodes.get(y);if(!p)continue;let h=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(h).length>0?h:void 0}).then(f=>{!f||f.length===0||this.sendInsertsForTree(p,f[0],e.resource);});}});return}}getMatchingQueries(e,t){let n=[];for(let r of Array.from(this.queryNodes.values()))r.queryStep.query.resource===e.resource&&n.push(r);return n.length===0?Ie([]):Promise.all(n.map(async r=>{let a=r.queryStep.query.where,u=r.queryStep.query.resource,o=e.resourceId,s=this.objectNodes.get(o);if(!s)return {hash:r.hash,matches:false};if(r.relationName){let p=r.parentQuery?this.queryNodes.get(r.parentQuery):void 0,h=p==null?void 0:p.queryStep.query.resource,f=h?this.getInverseRelationName(h,u,r.relationName):void 0,m=f?s.referencesObjects.get(f):void 0;if(!m)return {hash:r.hash,matches:false};let g=this.objectNodes.get(m);return !g||!p||!g.matchedQueries.has(p.hash)?{hash:r.hash,matches:false}:{hash:r.hash,matches:true}}if(!a)return {hash:r.hash,matches:true};let c=U(a,u,this.schema),l=Object.keys(c).length>0;if(!l&&t!==void 0)return {hash:r.hash,matches:P(t,a)};let d=await this.storage.get({resource:u,where:{id:o},include:l?c:void 0});if(!d||d.length===0)return {hash:r.hash,matches:false};let y=S(d[0]);return y?{hash:r.hash,matches:P(y,a)}:{hash:r.hash,matches:false}})).then(r=>r.filter(a=>a.matches).map(a=>a.hash))}};var vr=i=>i,Kt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],Ht=i=>i.length===1?i[0]:(async e=>{let t=e.rawValue,n=e.value,r=false;for(let a of i){let u=await a({...e,value:n,rawValue:t});u&&(t=u,n=S(t),n.id=e.value.id,r=true);}return r?t:void 0}),Wt=i=>i.length===1?i[0]:(async e=>{for(let t of i)await t(e);}),Ae=i=>{let e=i.filter(n=>n!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let n of Kt){let r=e.map(a=>a[n]).filter(a=>a!=null);r.length!==0&&(n==="afterInsert"||n==="afterUpdate"?t[n]=Wt(r):t[n]=Ht(r));}return t},wr=(...i)=>{let e={},t=new Set;for(let n of i)for(let r of Object.keys(n))t.add(r);for(let n of Array.from(t)){let r=i.map(u=>u[n]),a=Ae(r);a&&(e[n]=a);}return e};var at=He(je());var fe=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),Ee=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.any().nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),sn=Ee.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),tt=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),nt=zod.z.object({timestamp:zod.z.string().optional(),originMutationId:zod.z.string().optional()}).optional(),G=tt.extend({procedure:zod.z.string(),payload:zod.z.any().optional(),meta:nt}),Y=tt.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:sn,meta:nt});zod.z.union([Y,G]);var rt=zod.z.object({resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()});var it=fe.omit({resource:true}),he=G.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:G.shape.meta}),Oe=Y.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([Oe,he]);var Pe=i=>{if(i==null)return i;if(i==="null")return null;if(Array.isArray(i))return i.map(Pe);if(typeof i=="object"&&i.constructor===Object){let e={};for(let[t,n]of Object.entries(i))e[t]=Pe(n);return e}return i},st=i=>{let e=i.logger;return async t=>{var n,r,a,u,o,s;try{let c=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,l={headers:c,cookies:c.cookie?at.default.parse(c.cookie):{}},d=new URL(t.url),y=d.pathname.split("/"),p=d.searchParams,h=Pe(un__default.default.parse(p.toString())),f=await((n=i.contextProvider)==null?void 0:n.call(i,{transport:"HTTP",headers:l.headers,cookies:l.cookies,queryParams:h}))??{};if(t.method==="GET"){let m=y[y.length-1],{success:g,data:T,error:R}=it.safeParse(h);if(!g)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:R},{status:400});let b=await i.handleQuery({req:{...l,...T,type:"QUERY",resource:m,context:f,queryParams:h}});return !b||!b.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(b.data)}if(t.method==="POST")try{let m=y[y.length-1],g=y[y.length-2];if(g==="query"){if(y.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let E=y[y.length-3],C=t.body?await t.json():{};if(!E||E.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let M=await i.handleCustomQuery({req:{...l,type:"CUSTOM_QUERY",resource:E,procedure:m,input:C.input,context:f,queryParams:h}});return Response.json(M)}let T=g,R=t.body?await t.json():{},b,x=m,w,j;if(m==="insert"||m==="update"){let E=Oe.safeParse(R);if(x=m.toUpperCase(),E.success)b=E.data;else {if(!(typeof R=="object"&&R!==null&&"payload"in R&&"meta"in R))return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:E.error},{status:400});let M=he.safeParse(R);if(!M.success)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:M.error},{status:400});b=M.data;let L=(a=(r=i.router)==null?void 0:r.routes)==null?void 0:a[T],A=m==="insert"?"insert":"update";if(!!!((u=L==null?void 0:L.customMutations)!=null&&u[A])){let Se=b.payload??{},{id:ve,...Ue}=Se;if(m==="update"&&typeof ve!="string")return Response.json({message:"Invalid mutation: payload.id is required for update",code:"INVALID_REQUEST"},{status:400});w=typeof ve=="string"?ve:void 0;let we=(o=i.schema)==null?void 0:o[T];if(we&&typeof we.encodeMutation=="function"){let bt=((s=b.meta)==null?void 0:s.timestamp)??new Date().toISOString();j=we.encodeMutation("set",Ue,bt);}else j=Ue;}}}else {let{success:E,data:C,error:M}=he.safeParse(R);if(!E)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:M},{status:400});b=C;}let V=await i.handleMutation({req:{...l,type:"MUTATE",resource:T,input:j??b.payload,context:f,resourceId:w??b.resourceId,procedure:x,queryParams:{},meta:b.meta}});return Response.json(V)}catch(m){return e.error("Error parsing mutation from the client:",m),m instanceof Error&&m.message.includes("Unknown procedure")?Response.json({message:m.message,code:"UNKNOWN_PROCEDURE"},{status:400}):Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(c){return e.error("Unexpected error:",c),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var ct=He(je());var F=zod.z.string(),Ne=zod.z.union([rt,fe]),cn=zod.z.object({id:F,type:zod.z.literal("SUBSCRIBE")}).and(Ne),ln=zod.z.object({id:F,type:zod.z.literal("UNSUBSCRIBE")}).and(Ne),dn=zod.z.object({id:F,type:zod.z.literal("QUERY")}).and(Ne),yn=zod.z.object({id:F,type:zod.z.literal("CUSTOM_QUERY"),resource:zod.z.string(),procedure:zod.z.string(),input:zod.z.any().optional()}),ot=Y.extend({id:F}),pn=G.extend({id:F}),mn=zod.z.union([pn,ot]),ut=zod.z.union([cn,dn,yn,mn,ln]),fn=zod.z.object({id:F,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),hn=zod.z.object({id:F,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([fn,hn,ot]);zod.z.object({resource:zod.z.string(),data:zod.z.array(Ee)});var lt=i=>{let e={},t=i.logger;return (n,r)=>{var d;let a=y=>{n.send(JSON.stringify(y));},u=le(),o=new Map,s={headers:r.headers,cookies:typeof r.headers.cookie=="string"?ct.default.parse(r.headers.cookie):{}},c=un.parse(r.url.split("?")[1]),l=(d=i.contextProvider)==null?void 0:d.call(i,{transport:"WEBSOCKET",headers:s.headers,cookies:s.cookies,queryParams:c});e[u]=n,t.info("Client connected:",u),n.on("message",async y=>{try{t.debug("Message received from the client:",y);let p=ut.parse(JSON.parse(y.toString()));if(p.type==="SUBSCRIBE"||p.type==="QUERY"){let{type:h,id:f,...m}=p,g=h==="SUBSCRIBE";if("procedure"in m){let T=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:m.resource,procedure:m.procedure,input:m.input,context:await l??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(g){if(!T||!T.data||!T.query)throw new Error("Invalid resource");T.unsubscribe&&o.set($(m),T.unsubscribe),a({id:f,type:"REPLY",data:{resource:T.query.resource,data:(T.data??[]).map(R=>R.value)}});}else a({id:f,type:"REPLY",data:T});}else {let T=await i.handleQuery({req:{...s,...m,type:"QUERY",context:await l??{},queryParams:c},subscription:g?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[u])==null||b.send(JSON.stringify(R));}:void 0});if(!T||!T.data)throw new Error("Invalid resource");g&&T.unsubscribe&&o.set($(m),T.unsubscribe),a({id:f,type:"REPLY",data:{resource:m.resource,data:(T.data??[]).map(R=>R.value)}});}}else if(p.type==="UNSUBSCRIBE"){let{type:h,id:f,...m}=p,g=o.get($(m));g&&(g(),o.delete($(m)));}else if(p.type==="CUSTOM_QUERY"){let{resource:h,procedure:f,input:m,id:g}=p;t.debug("Received custom query from client:",p);try{let T=await i.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:h,procedure:f,input:m,context:await l??{},queryParams:c}});a({id:g,type:"REPLY",data:T});}catch(T){a({id:g,type:"REJECT",resource:h,message:T.message}),t.error("Error handling custom query from the client:",T);}}else if(p.type==="MUTATE"){let{resource:h}=p;t.debug("Received mutation from client:",p);try{let f=await i.handleMutation({req:{...s,type:"MUTATE",resource:h,input:p.payload,context:{messageId:p.id,...await l??{}},resourceId:p.resourceId,procedure:p.procedure,queryParams:c,meta:p.meta}});p.procedure&&p.procedure!=="INSERT"&&p.procedure!=="UPDATE"&&a({id:p.id,type:"REPLY",data:f});}catch(f){a({id:p.id,type:"REJECT",resource:h,message:f.message}),t.error("Error parsing mutation from the client:",f);}}}catch(p){t.error("Error handling message from the client:",p);}}),n.on("close",()=>{t.info("Connection closed",u),delete e[u];for(let y of Array.from(o.values()))y();});}};function dt(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([n,r])=>{r&&t.set(n,Array.isArray(r)?r.join(","):r);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Zr=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,lt(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(n,r)=>{st(e)(dt(n)).then(u=>u.json().then(o=>r.status(u.status).send(o)));});};var Te=class i{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,n,r,a,u,o,s){this._collection=e,this._client=t,this._where=n??{},this._include=r??{},this._limit=a,this._single=u,this._sort=o,this._shouldAwait=s,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new i(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new i(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}limit(e){return new i(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 i(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,t="asc"){let n=[...this._sort??[],{key:e,direction:t}];return new i(this._collection,this._client,this._where,this._include,this._limit,this._single,n,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,n){return new i(e,t,void 0,void 0,void 0,void 0,void 0,n??false)}};var gn=i=>typeof i=="object"&&i!==null&&"value"in i&&!Array.isArray(i),Ve=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(n=>gn(n)?S(n):n))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function K(i,e,t){let n=new Ve(i),r=u=>{let o=Te._init(u,n,true);return Object.assign(Object.create(o),{insert:async c=>{let l=i._getTimestamp(),d=await i.rawInsert(u.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([y,p])=>[y,{value:p,_meta:{timestamp:l}}]))},void 0,t);return S(d.data)},update:async(c,l)=>{let d=i._getTimestamp(),{id:y,...p}=l,h=await i.rawUpdate(u.name,c,{value:Object.fromEntries(Object.entries(p).map(([g,T])=>[g,{value:T,_meta:{timestamp:d}}]))},void 0,t),f=S(h.data),m={};for(let g of Object.keys(p))g in f&&(m[g]=f[g]);return m}})},a={get(u,o){if(o==="findOne")return i.findOne.bind(i);if(o==="find")return i.find.bind(i);if(o==="insert")return (s,c)=>{let l=i._getTimestamp();return i.rawInsert(s.name,c.id,{value:Object.fromEntries(Object.entries(c).map(([d,y])=>[d,{value:y,_meta:{timestamp:l}}]))},void 0,t).then(d=>S(d.data))};if(o==="update")return (s,c,l)=>{let d=i._getTimestamp(),{id:y,...p}=l;return i.rawUpdate(s.name,c,{value:Object.fromEntries(Object.entries(p).map(([h,f])=>[h,{value:f,_meta:{timestamp:d}}]))},void 0,t).then(h=>{let f=S(h.data),m={};for(let g of Object.keys(p))g in f&&(m[g]=f[g]);return m})};if(o==="transaction")return async s=>i.transaction(async({trx:c,commit:l,rollback:d})=>{let y=K(c,e,t);return s({trx:y,commit:l,rollback:d})});if(o in e){let s=e[o];return r(s)}}};return new Proxy({},a)}var ke=class i{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 n=t;n.hooks&&this.hooksRegistry.set(n.resourceSchema.name,n.hooks);}}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}},oi=i=>ke.create({...i}),pt=(i=>({handler:e=>({_type:"query",inputValidator:i??zod.z.undefined(),handler:e})})),mt=(i=>({handler:e=>({_type:"mutation",inputValidator:i??zod.z.undefined(),handler:e})})),Qe=class i{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,n,r,a){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=n??{},this.authorization=r,this.hooks=a;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:mt,query:pt}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=u;return new i(this.resourceSchema,n,r,this.authorization,this.hooks)}withMutations(e){return this.withProcedures(({mutation:t})=>e({mutation:t}))}withHooks(e){return new i(this.resourceSchema,this.customMutations,this.customQueries,this.authorization,e)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{let r={resource:n.resource,where:n.where,include:n.include,lastSyncedAt:n.lastSyncedAt,limit:n.limit,sort:n.sort},a=$(r);return {data:await t.rawFind({resource:n.resource,commonWhere:n.where,uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort}),unsubscribe:void 0,queryHash:a}})(e);handleMutation=async({req:e,db:t,schema:n})=>{var o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),a=t._setMutationTimestamp(r),u=K(a,n,e.context);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let c=s.procedure==="INSERT"?"insert":s.procedure==="UPDATE"?"update":void 0,l=this.customMutations[s.procedure]?s.procedure:c&&this.customMutations[c]?c:s.procedure,d=this.customMutations[l];if(d){s.procedure=l;let y=d.inputValidator["~standard"].validate(s.input),p=y instanceof Promise?await y:y;if(p.issues){let h=p.issues.map(f=>{var g;let m=(g=f.path)==null?void 0:g.map(T=>typeof T=="object"&&"key"in T?String(T.key):String(T)).join(".");return m?`${m}: ${f.message}`:f.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return s.input=p.value,d.handler({req:s,db:u})}else {if(s.procedure==="INSERT"||s.procedure==="UPDATE")return this.handleSet({req:s,db:a,operation:s.procedure,schema:n});throw new Error(`Unknown procedure: ${s.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=K(t,n,e.context);return await this.wrapInMiddlewares(async a=>{let u=this.customQueries[a.procedure];if(!u)throw new Error(`Unknown query procedure: ${a.procedure}`);let o=u.inputValidator["~standard"].validate(a.input),s=o instanceof Promise?await o:o;if(s.issues){let c=s.issues.map(l=>{var y;let d=(y=l.path)==null?void 0:y.map(p=>typeof p=="object"&&"key"in p?String(p.key):String(p)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return a.input=s.value,u.handler({req:a,db:r})})(e)};getAuthorizationClause(e){var t,n;return (n=(t=this.authorization)==null?void 0:t.read)==null?void 0:n.call(t,{ctx:e.context})}handleSet=async({req:e,db:t,operation:n,schema:r})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&a)throw new Error("Resource already exists");if(n==="UPDATE"&&!a)throw new Error("Resource not found");let u={value:e.input};return t.transaction(async({trx:o})=>{var l,d,y,p,h,f,m;if(n==="INSERT"){let{data:g,acceptedValues:T}=await o.rawInsert(e.resource,e.resourceId,u,(l=e.context)==null?void 0:l.messageId,e.context);if(!T)throw new Error("Mutation rejected");let R=S(g);if(R.id=R.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let x=U(b,e.resource,r),w=Object.keys(x).length>0?await o.rawFindById(e.resource,e.resourceId,x):g,j=S(w);if(j.id=j.id??e.resourceId,!P(j,b))throw new Error("Not authorized")}}return {data:g,acceptedValues:T}}if((p=(y=this.authorization)==null?void 0:y.update)!=null&&p.preMutation){let g=S(a);g.id=g.id??e.resourceId;let T=this.authorization.update.preMutation({ctx:e.context,value:g});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let R=U(T,e.resource,r),b=Object.keys(R).length>0?await o.rawFindById(e.resource,e.resourceId,R):a,x=S(b);if(x.id=x.id??e.resourceId,!P(x,T))throw new Error("Not authorized")}}let{data:s,acceptedValues:c}=await o.rawUpdate(e.resource,e.resourceId,u,(h=e.context)==null?void 0:h.messageId,e.context);if(!c)throw new Error("Mutation rejected");if((m=(f=this.authorization)==null?void 0:f.update)!=null&&m.postMutation){let g=S(s);g.id=g.id??e.resourceId;let T=this.authorization.update.postMutation({ctx:e.context,value:g});if(typeof T=="boolean"){if(!T)throw new Error("Not authorized")}else {let R=U(T,e.resource,r),b=Object.keys(R).length>0?await o.rawFindById(e.resource,e.resourceId,R):s,x=S(b);if(x.id=x.id??e.resourceId,!P(x,T))throw new Error("Not authorized")}}return {data:s,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}},qe=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:n})=>{var o;let r=((o=e.meta)==null?void 0:o.timestamp)??new Date().toISOString(),a=t._setMutationTimestamp(r),u=K(a,n,e.context);return await this.wrapInMiddlewares(async s=>{if(!s.procedure)throw new Error("Procedure is required for mutations");let c=this.customMutations[s.procedure];if(c){let l=c.inputValidator["~standard"].validate(s.input),d=l instanceof Promise?await l:l;if(d.issues){let y=d.issues.map(p=>{var f;let h=(f=p.path)==null?void 0:f.map(m=>typeof m=="object"&&"key"in m?String(m.key):String(m)).join(".");return h?`${h}: ${p.message}`:p.message}).join(", ");throw new Error(`Validation failed: ${y}`)}return s.input=d.value,c.handler({req:s,db:u})}throw new Error(`Unknown procedure: ${s.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:n})=>{let r=K(t,n,e.context);return await this.wrapInMiddlewares(async a=>{let u=this.customQueries[a.procedure];if(!u)throw new Error(`Unknown query procedure: ${a.procedure}`);let o=u.inputValidator["~standard"].validate(a.input),s=o instanceof Promise?await o:o;if(s.issues){let c=s.issues.map(l=>{var y;let d=(y=l.path)==null?void 0:y.map(p=>typeof p=="object"&&"key"in p?String(p.key):String(p)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${c}`)}return a.input=s.value,u.handler({req:a,db:r})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,r)=>a=>r({req:a,next:n}),e)(t)}};function ui(i){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:n})=>i({ctx:t.context,req:t,next:r=>(t.context=r,n(t))})}}var $e=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Qe(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:mt,query:pt}),n={},r={};for(let[a,u]of Object.entries(t))u._type==="mutation"?n[a]=u:r[a]=u;return new qe(n,r).use(...this.middlewares)}use(...e){let t=e.map(n=>n&&n._brand==="TypedMiddleware"?n._rawMiddleware:n);return new i([...this.middlewares,...t])}static create(){return new i}},ci=$e.create;var X=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 n=this._getTimestamp(),r=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([a,u])=>[a,{value:u,_meta:{timestamp:n}}]))});return S(r.data)}async update(e,t,n){let r=this._getTimestamp(),{id:a,...u}=n,o=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(u).map(([l,d])=>[l,{value:d,_meta:{timestamp:r}}]))}),s=S(o.data),c={};for(let l of Object.keys(u))l in s&&(c[l]=s[l]);return c}};var Mn={postgres:{jsonObjectFrom:postgres.jsonObjectFrom,jsonArrayFrom:postgres.jsonArrayFrom},mysql:{jsonObjectFrom:mysql.jsonObjectFrom,jsonArrayFrom:mysql.jsonArrayFrom},sqlite:{jsonObjectFrom:sqlite.jsonObjectFrom,jsonArrayFrom:sqlite.jsonArrayFrom}};function D(i){var r,a,u;let e=(r=i.getExecutor)==null?void 0:r.call(i),t=e==null?void 0:e.adapter;if(!t)return "postgres";let n=((u=(a=t.constructor)==null?void 0:a.name)==null?void 0:u.toLowerCase())??"";return n.includes("postgres")?"postgres":n.includes("mysql")?"mysql":n.includes("sqlite")?"sqlite":"postgres"}function ft(i){let e=D(i);return Mn[e]}var In="42701";function ee(i){var t;if(i.code===In)return true;let e=((t=i.message)==null?void 0:t.toLowerCase())||"";return e.includes("already exists")||e.includes("duplicate")||e.includes("already defined")}function _e(i,e){let{type:t,enumValues:n,enumName:r}=i;if(n&&n.length>0)return e==="postgres"&&r?r:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Cn(i,e,t,n){if(t!=="postgres")return;let r=new Map;for(let a of Object.values(e))for(let u of Object.values(a.fields)){let o=u.getStorageFieldType();o.enumValues&&o.enumName&&r.set(o.enumName,{name:o.enumName,values:o.enumValues});}for(let a of Array.from(r.values())){let{name:u,values:o}=a;try{let s=o.map(c=>`'${c}'`).join(", ");await kysely.sql`
|
|
2
2
|
DO $$ BEGIN
|
|
3
3
|
CREATE TYPE ${kysely.sql.id(u)} AS ENUM (${kysely.sql.raw(s)});
|
|
4
4
|
EXCEPTION
|
|
5
5
|
WHEN duplicate_object THEN null;
|
|
6
6
|
END $$;
|
|
7
|
-
`.execute(i);}catch(s){n==null||n.warn("Could not create enum type",u,s);}}}function te(i,e){return i.some(t=>t.name===e)}function
|
|
7
|
+
`.execute(i);}catch(s){n==null||n.warn("Could not create enum type",u,s);}}}function te(i,e){return i.some(t=>t.name===e)}function Ln(i,e){return (i==null?void 0:i.columns.some(t=>t.name===e))??false}function Fe(i,e){let[t]=e.split(".");return te(i,t)}function De(i,e,t,n=false){let r=i;return e.unique&&(r=r.unique()),e.nullable||(r=r.notNull()),e.primary&&(r=r.primaryKey()),e.default!==void 0&&(r=r.defaultTo(e.default)),!n&&e.references&&Fe(t,e.references)&&(r=r.references(e.references)),r}function An(i,e,t,n,r){let a=[];for(let[u,o]of Object.entries(i.fields)){let s=e==null?void 0:e.columns.find(l=>l.name===u),c=o.getStorageFieldType();s?(s.dataType,c.type):(a.push({name:u,storageFieldType:c}),c.references&&!Fe(t,c.references)&&n.push({tableName:r,columnName:u,references:c.references}));}return a}function ht(i,e){return e==="postgres"&&!!i.enumValues&&i.enumValues.length>0&&!!i.enumName}async function jn(i,e,t,n,r,a){if(t.length===0)return;let u=i.schema.createTable(e);for(let{name:o,storageFieldType:s}of t)if(ht(s,r))u=u.addColumn(o,kysely.sql.raw(s.enumName),c=>De(c,s,n));else {let c=_e(s,r);u=u.addColumn(o,c,l=>De(l,s,n));}await u.execute().catch(o=>{if(!ee(o))throw a==null||a.error("Error creating table",e,o),o});}async function En(i,e,t,n,r,a,u){for(let{name:o,storageFieldType:s}of t){let c=s.references?Fe(n,s.references):false,l=ht(s,a)?kysely.sql.raw(s.enumName):_e(s,a);await i.schema.alterTable(e).addColumn(o,l,d=>De(d,s,n,!c)).execute().catch(d=>{if(!ee(d))throw u==null||u.error("Error adding column",o,d),d}),s.references&&!c&&!r.some(d=>d.tableName===e&&d.columnName===o)&&r.push({tableName:e,columnName:o,references:s.references}),s.index&&await i.schema.createIndex(`${e}_${o}_index`).on(e).column(o).execute().catch(()=>{});}}async function On(i,e,t,n,r,a){let u=`${e}_meta`,o=[];for(let[s,c]of Object.entries(t.fields)){let l=c.getStorageFieldType();Ln(n,s)||o.push({name:s,storageFieldType:l});}if(!n&&o.length>0){let s=i.schema.createTable(u);for(let{name:c,storageFieldType:l}of o)s=s.addColumn(c,"varchar",d=>{let y=d;return l.primary&&(y=y.primaryKey(),te(r,e)&&(y=y.references(`${e}.${c}`))),y});await s.execute().catch(c=>{if(!ee(c))throw a==null||a.error("Error creating meta table",u,c),c});}else if(n)for(let{name:s,storageFieldType:c}of o)await i.schema.alterTable(u).addColumn(s,"varchar",l=>{let d=l;return c.primary&&(d=d.primaryKey(),te(r,e)&&(d=d.references(`${e}.${s}`))),d}).execute().catch(l=>{if(!ee(l))throw a==null||a.error("Error adding meta column",s,l),l});}async function Tt(i,e,t,n,r){let[a,u]=n.split("."),o=`${e}_${t}_fk`;try{await kysely.sql`
|
|
8
8
|
ALTER TABLE ${kysely.sql.id(e)}
|
|
9
9
|
ADD CONSTRAINT ${kysely.sql.id(o)}
|
|
10
10
|
FOREIGN KEY (${kysely.sql.id(t)})
|
|
11
11
|
REFERENCES ${kysely.sql.id(a)} (${kysely.sql.id(u)})
|
|
12
|
-
`.execute(i);}catch(s){ee(s)||r==null||r.warn("Could not add foreign key constraint",e,t,n,s);}}async function An(i,e,t,n){for(let{tableName:r,columnName:a,references:u}of e){let o=t.find(d=>d.name===r),s=o==null?void 0:o.columns.find(d=>d.name===a),[c]=u.split(".");o&&s&&te(t,c)&&await pt(i,r,a,u,n);}}async function jn(i,e,t,n){for(let[r,a]of Object.entries(e)){let u=`${r}_meta`,o=t.find(s=>s.name===u);if(o)for(let[s,c]of Object.entries(a.fields)){let d=c.getStorageFieldType(),l=o.columns.find(p=>p.name===s);d.primary&&l&&te(t,r)&&await pt(i,u,s,`${r}.${s}`,n);}}}async function mt(i,e,t){let n=q(i),r=await i.introspection.getTables(),a=[];await vn(i,e,n,t);for(let[o,s]of Object.entries(e)){let c=r.find(p=>p.name===o),d=r.find(p=>p.name===`${o}_meta`),l=Mn(s,c,r,a,o);if(c)for(let[p,y]of Object.entries(s.fields)){let f=c.columns.find(g=>g.name===p),m=y.getStorageFieldType(),T=qe(m,n);f&&f.dataType!==T&&(t==null||t.warn("Column type mismatch:",p,"expected to have type:",T,"but has type:",f.dataType));}!c&&l.length>0?await In(i,o,l,r,n,t):c&&await Cn(i,o,l,r,a,n,t),await Ln(i,o,s,d,r,t);}let u=await i.introspection.getTables();await An(i,a,u,t),await jn(i,e,u,t);}function ge(i,e,t,n){if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error("Resource not found");let a=n.$or,u=n.$and;return (a?t.or:t.and)(a?n.$or.map(o=>ge(i,e,t,o)):u?n.$and.map(o=>ge(i,e,t,o)):Object.entries(n).map(([o,s])=>{var c,d;if(r.fields[o])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${o}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${o}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((c=s==null?void 0:s.$not)==null?void 0:c.$in)!==void 0?t(`${e}.${o}`,"not in",s.$not.$in):((d=s==null?void 0:s.$not)==null?void 0:d.$eq)!==void 0?t(`${e}.${o}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${o}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${o}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${o}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${o}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${o}`,"<=",s.$lte):t(`${e}.${o}`,s===null?"is":"=",s);if(r.relations[o]){let l=r.relations[o],p=l.entity.name;return l.type==="many"?t.exists(be(i,p,t.selectFrom(p).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),s)):ge(i,p,t,s)}return null}).filter(Boolean))}function Re(i,e,t,n){let r=i[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let a of n.$and)t=Re(i,e,t,a);return t}else if(n.$or){for(let a of n.$or)t=Re(i,e,t,a);return t}for(let[a,u]of Object.entries(n)){if(!r.relations[a])continue;let o=r.relations[a],s=o.entity.name,c=o.type==="one"?"id":o.foreignColumn,d=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(s,`${s}.${c}`,`${e}.${d}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=Re(i,s,t,u));}return t}function be(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=Re(i,e,t,n),t.where(r=>ge(i,e,r,n)))}function En(i,e,t,n,r){let a=q(r),u=e[t];if(a==="sqlite"&&(u!=null&&u.fields)){let o=Object.keys(u.fields),s=i.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return i.selectFrom(n).selectAll(n)}function On(i,e,t,n,r){let a=q(r),u=e[t];if(a==="sqlite"&&(u!=null&&u.fields)){let o=Object.keys(u.fields),s=i.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return i.selectFrom(n).selectAll(n)}function xe(i,e,t,n,r,a){if(!n)return t;if(!i)throw new Error("Schema not initialized");let u=i[e];if(!u)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:o,jsonArrayFrom:s}=r;for(let c of Object.keys(n)){if(!u.relations[c])throw new Error(`Relation ${c} not found in resource ${e}`);let d=u.relations[c],l=d.entity.name,p=n[c],y=d.type==="one"?"id":d.foreignColumn,f=d.type==="one"?d.relationalColumn:"id",m=d.type==="one"?o:s,T=ye(p)?p:null,g=T==null?void 0:T.include;t=t.select(h=>{let R=`${l}_meta`,b=On(h,i,l,l,a).whereRef(`${l}.${y}`,"=",`${e}.${f}`).select(x=>o(En(x,i,l,R,a).whereRef(`${R}.id`,"=",`${l}.id`)).as("_meta"));if(T!=null&&T.where&&(b=be(i,l,b,T.where)),T!=null&&T.orderBy)for(let x of T.orderBy)b=b.orderBy(`${l}.${x.key}`,x.direction);return (T==null?void 0:T.limit)!==void 0&&(b=b.limit(T.limit)),g&&Object.keys(g).length>0&&(b=xe(i,l,b,g,r,a)),m(b).as(c)});}return t}var De=class i extends X{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.dialectHelpers=dt(this.db),this.schema=t,this.logger=n,this.server=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){this.schema=e,this.logger=t,this.server=n,await mt(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=q(this.db),a=(u=this.schema)==null?void 0:u[t];if(r==="sqlite"&&(a!=null&&a.fields)){let o=Object.keys(a.fields),s=e.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,a=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(s,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));a=xe(this.schema,e,a,n,this.dialectHelpers,this.db);let u=await a.executeTakeFirst();if(!u)return;let o=this.parseRelationalJsonStrings(u,e);return this.convertToMaterializedLiveType(o,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return S(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:a,sort:u}=e,o=`${t}_meta`,s=this.db.selectFrom(t).selectAll(t).select(d=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(d,t,o).whereRef(`${o}.id`,"=",`${t}.id`)).as("_meta"));s=be(this.schema,t,s,n),s=xe(this.schema,t,s,r,this.dialectHelpers,this.db),a!==void 0&&(s=s.limit(a)),u!==void 0&&u.forEach(d=>{s=s.orderBy(d.key,d.direction);});let c=await s.execute();return c.length===0?[]:c.map(d=>{let l=this.parseRelationalJsonStrings(d,t);return this.convertToMaterializedLiveType(l,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(r=>S(r))}async rawInsert(e,t,n,r,a){var m,T,g,h,R,b,x,w,O,$,G;let u=(m=this.server)==null?void 0:m.getHooks(e),o=(T=this.schema)==null?void 0:T[e],[s,c]=((g=o==null?void 0:o.mergeMutation)==null?void 0:g.call(o,"set",n.value,void 0))??[n,n.value];if(!c)return {data:n,acceptedValues:null};let d=s,l={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let L=S(l);L.id=t;let M=await u.beforeInsert({ctx:a,value:L,rawValue:l,db:this});M&&(d=M);}let p={},y={};for(let[L,M]of Object.entries(d.value)){let A=(h=M._meta)==null?void 0:h.timestamp;if(!A)continue;let C=(b=(R=o==null?void 0:o.fields[L])==null?void 0:R.getStorageFieldType)==null?void 0:b.call(R);(C==null?void 0:C.type)==="jsonb"||(C==null?void 0:C.type)==="json"?p[L]=JSON.stringify(M.value):p[L]=M.value,y[L]=A;}await this.db.insertInto(e).values({...p,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(w=(x=this.logger)==null?void 0:x.debug)==null||w.call(x,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(a==null?void 0:a.messageId)??"(none)",hasContext:!!a,contextKeys:a?Object.keys(a):[]});let f=this.buildMutation(e,t,"INSERT",d,r,a==null?void 0:a.messageId);if(f&&((G=(O=this.logger)==null?void 0:O.debug)==null||G.call(O,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:(($=f.meta)==null?void 0:$.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,d)),u!=null&&u.afterInsert){let L={...d,value:{...d.value,id:{value:t}}},M=S(L);M.id=t,await u.afterInsert({ctx:a,value:M,rawValue:L,db:this});}return {data:d,acceptedValues:c}}async rawUpdate(e,t,n,r,a){var T,g,h,R,b,x,w,O,$,G,L;let u=(T=this.server)==null?void 0:T.getHooks(e),o=(g=this.schema)==null?void 0:g[e],s=await this.rawFindById(e,t),[c,d]=((h=o==null?void 0:o.mergeMutation)==null?void 0:h.call(o,"set",n.value,s))??[n,n.value];if(!d)return {data:n,acceptedValues:null};let l=c,p={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let M=S(p);M.id=t;let A;if(s){let E={...s,value:{...s.value,id:{value:t}}};A=S(E),A.id=t;}let C=await u.beforeUpdate({ctx:a,value:M,rawValue:p,previousValue:A,previousRawValue:s,db:this});C&&(l=C);}let y={},f={};for(let[M,A]of Object.entries(l.value)){let C=(R=A._meta)==null?void 0:R.timestamp;if(!C)continue;let E=(x=(b=o==null?void 0:o.fields[M])==null?void 0:b.getStorageFieldType)==null?void 0:x.call(b);(E==null?void 0:E.type)==="jsonb"||(E==null?void 0:E.type)==="json"?y[M]=JSON.stringify(A.value):y[M]=A.value,f[M]=C;}if(Object.keys(y).length===0)return {data:l,acceptedValues:d};await Promise.all([this.db.updateTable(e).set(y).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(M=>M.column("id").doUpdateSet(f)).execute()]),(O=(w=this.logger)==null?void 0:w.debug)==null||O.call(w,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(a==null?void 0:a.messageId)??"(none)",hasContext:!!a,contextKeys:a?Object.keys(a):[]});let m=this.buildMutation(e,t,"UPDATE",l,r,a==null?void 0:a.messageId);if(m){(L=($=this.logger)==null?void 0:$.debug)==null||L.call($,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((G=m.meta)==null?void 0:G.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let M=await this.rawFindById(e,t);M&&this.trackMutation(m,M);}if(u!=null&&u.afterUpdate){let M=await this.rawFindById(e,t);if(M){let A={...M,value:{...M.value,id:{value:t}}},C=S(A);C.id=t;let E;if(s){let ht={...s,value:{...s.value,id:{value:t}}};E=S(ht),E.id=t;}await u.afterUpdate({ctx:a,value:C,rawValue:A,previousValue:E,previousRawValue:s,db:this});}}return {data:l,acceptedValues:d}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let a=Math.random().toString(36).substring(2,15),u=this.mutationStack,o=[];this.mutationStack=o;let s=await this.db.savepoint(a).execute(),c=false,d=false;try{return await e({trx:this,commit:async()=>{await s.releaseSavepoint(a).execute(),c=!0,u.push(...o);},rollback:async()=>{await s.rollbackToSavepoint(a).execute(),d=!0,o.length=0;}}).then(l=>s.isCommitted||s.isRolledBack||c||d?l:s.releaseSavepoint(a).execute().then(()=>(u.push(...o),l)))}catch(l){throw d||await s.rollbackToSavepoint(a).execute().catch(()=>{}),o.length=0,l}finally{this.mutationStack=u;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let a=new i(r,this.schema,this.logger,this.server);return a.mutationStack=t,await e({trx:a,commit:async()=>{var u,o;await r.commit().execute(),(o=(u=this.logger)==null?void 0:u.debug)==null||o.call(u,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:s})=>{var c;return {id:s.id,resource:s.resource,resourceId:s.resourceId,procedure:s.procedure,hasMeta:!!s.meta,originMutationId:((c=s.meta)==null?void 0:c.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(u=>r.isCommitted||r.isRolledBack?u:r.commit().execute().then(()=>{var o,s;return (s=(o=this.logger)==null?void 0:o.debug)==null||s.call(o,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:c})=>{var d;return {id:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure,hasMeta:!!c.meta,originMutationId:((d=c.meta)==null?void 0:d.originMutationId)??"(none)"}})}),this.notifyMutations(t),u}))}catch(a){throw await r.rollback().execute(),t.length=0,a}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var a,u;if(q(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(o=>this.parseRelationalJsonStrings(o,t));let r={};for(let[o,s]of Object.entries(e))if(o==="_meta"&&typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{r[o]=JSON.parse(s);}catch{r[o]=s;}else r[o]=s;else if(this.isRelationalField(t,o))if(typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{let c=JSON.parse(s);if(this.schema){let d=this.schema[t],l=(a=d==null?void 0:d.relations)==null?void 0:a[o];if(l){let p=l.entity.name;r[o]=this.parseRelationalJsonStrings(c,p);}else r[o]=c;}else r[o]=c;}catch{r[o]=s;}else r[o]=s;else if(typeof s=="object"&&s!==null&&!Array.isArray(s))if(this.schema){let c=this.schema[t],d=(u=c==null?void 0:c.relations)==null?void 0:u[o];if(d){let l=d.entity.name;r[o]=this.parseRelationalJsonStrings(s,l);}else r[o]=s;}else r[o]=s;else Array.isArray(s)?r[o]=s.map(c=>{var d,l;if(typeof c=="string")try{let p=JSON.parse(c);if(this.schema){let y=this.schema[t],f=(d=y==null?void 0:y.relations)==null?void 0:d[o];if(f){let m=f.entity.name;return this.parseRelationalJsonStrings(p,m)}}return p}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let p=this.schema[t],y=(l=p==null?void 0:p.relations)==null?void 0:l[o];if(y){let f=y.entity.name;return this.parseRelationalJsonStrings(c,f)}}return c}):r[o]=s;else r[o]=s;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((a,[u,o])=>{var l,p,y,f,m,T,g,h,R;if(u==="_meta")return a;let s=(p=(l=n==null?void 0:n.fields[u])==null?void 0:l.getStorageFieldType)==null?void 0:p.call(l),c=(s==null?void 0:s.type)==="jsonb"||(s==null?void 0:s.type)==="json",d=(n==null?void 0:n.relations)&&u in n.relations;if(u==="id")a[u]={value:o};else if(c)a[u]={value:o,_meta:{timestamp:(y=e==null?void 0:e._meta)==null?void 0:y[u]}};else if(d){let b=n.relations[u].entity,x=(b==null?void 0:b.name)??t;Array.isArray(o)?a[u]={value:o.map(w=>this.convertToMaterializedLiveType(w,x)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[u],relation:true}}:o!==null&&typeof o=="object"?a[u]={...this.convertToMaterializedLiveType(o,x),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[u],relation:true}}:a[u]={value:o,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[u],relation:true}};}else Array.isArray(o)?a[u]={value:o,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[u]}}:typeof o=="object"&&o!==null&&!(o instanceof Date)?a[u]={value:o,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[u]}}:a[u]={value:o,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[u]}};return a},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",u=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||a&&u}buildMutation(e,t,n,r,a,u){var s;let o={};for(let[c,d]of Object.entries(r.value)){if(c==="id")continue;let l=(s=d._meta)==null?void 0:s.timestamp;l&&(o[c]={value:d.value,_meta:{timestamp:l}});}return Object.keys(o).length===0?null:{id:a??le(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:o,meta:u?{originMutationId:u}:void 0}}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 n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:a}of n)this.server.notifySubscribers(r,a);}}};var _e=class i{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var r;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=We({level:e.logLevel??D.INFO}),(r=e.middlewares)==null||r.forEach(a=>{this.middlewares.add(a);});let t=this.router.hooksRegistry,n=new Set;if(t&&t.forEach((a,u)=>{n.add(u);}),e.hooks)for(let a of Object.keys(e.hooks))n.add(a);n.forEach(a=>{var c;let u=t==null?void 0:t.get(a),o=(c=e.hooks)==null?void 0:c[a],s=Ie([u,o]);s&&this.hooksRegistry.set(a,s);}),this.initPromise=this.storage.init(this.schema,this.logger,this).catch(a=>{this.initError=a;}),this.contextProvider=e.contextProvider,this.queryEngine=new pe({router:{get:async(a,u)=>{var y;let{headers:o,cookies:s,queryParams:c,context:d}=(u==null?void 0:u.context)??{};if(!(u!=null&&u.batcher))throw new Error("Batcher is required");let l={...a,type:"QUERY",headers:o,cookies:s,queryParams:c,context:d},p=await((y=this.router.routes[a.resource])==null?void 0:y.handleQuery({req:l,batcher:u.batcher}));return (p==null?void 0:p.data)??[]},incrementQueryStep:(a,u={})=>{var c;let o=(c=this.router.routes[a.query.resource])==null?void 0:c.getAuthorizationClause({...a.query,type:"QUERY",headers:u.headers,cookies:u.cookies,queryParams:u.queryParams,context:u.context});if(typeof o=="boolean"&&!o)throw new Error("Not authorized");let s=W(a.query.where,typeof o=="object"?o:void 0);return {...a,query:{...a.query,where:s}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleQuery(e){return await this.ensureInitialized(),this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:a,context:u,...o}=t,s={headers:n,cookies:r,queryParams:a,context:u},c=e.subscription?this.queryEngine.subscribe(o,l=>{var p;(p=e.subscription)==null||p.call(e,l);},s):void 0;return {data:await this.queryEngine.get(o,{context:s}),unsubscribe:c}})(e.req)}async handleMutation(e){return await this.ensureInitialized(),await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async p=>{let y=this.router.routes[p.resource];if(!y)throw new Error("Invalid resource");return y.handleCustomQuery({req:p,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:r,cookies:a,queryParams:u,context:o}=e.req,s={headers:r,cookies:a,queryParams:u,context:o},c=t.buildQueryRequest(),d=e.subscription?this.queryEngine.subscribe(c,p=>{var y;(y=e.subscription)==null||y.call(e,p);},s):void 0,l=await this.queryEngine.get(c,{context:s});return e.subscription?{data:l,unsubscribe:d,query:c}:l.map(p=>S(p))}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((n,r)=>a=>r({req:a,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},ki=_e.create;exports.ProcedureRoute=Ve;exports.Route=Ne;exports.RouteFactory=ke;exports.Router=Pe;exports.SQLStorage=De;exports.Server=_e;exports.Storage=X;exports.createMiddleware=ii;exports.createServerDB=U;exports.defineHooks=Rr;exports.expressAdapter=Hr;exports.mergeEntityHooks=Ie;exports.mergeHooks=br;exports.routeFactory=ai;exports.router=ri;exports.server=ki;
|
|
12
|
+
`.execute(i);}catch(s){ee(s)||r==null||r.warn("Could not add foreign key constraint",e,t,n,s);}}async function Pn(i,e,t,n){for(let{tableName:r,columnName:a,references:u}of e){let o=t.find(l=>l.name===r),s=o==null?void 0:o.columns.find(l=>l.name===a),[c]=u.split(".");o&&s&&te(t,c)&&await Tt(i,r,a,u,n);}}async function Nn(i,e,t,n){for(let[r,a]of Object.entries(e)){let u=`${r}_meta`,o=t.find(s=>s.name===u);if(o)for(let[s,c]of Object.entries(a.fields)){let l=c.getStorageFieldType(),d=o.columns.find(y=>y.name===s);l.primary&&d&&te(t,r)&&await Tt(i,u,s,`${r}.${s}`,n);}}}async function gt(i,e,t){let n=D(i),r=await i.introspection.getTables(),a=[];await Cn(i,e,n,t);for(let[o,s]of Object.entries(e)){let c=r.find(y=>y.name===o),l=r.find(y=>y.name===`${o}_meta`),d=An(s,c,r,a,o);if(c)for(let[y,p]of Object.entries(s.fields)){let h=c.columns.find(g=>g.name===y),f=p.getStorageFieldType(),m=_e(f,n);h&&h.dataType!==m&&(t==null||t.warn("Column type mismatch:",y,"expected to have type:",m,"but has type:",h.dataType));}!c&&d.length>0?await jn(i,o,d,r,n,t):c&&await En(i,o,d,r,a,n,t),await On(i,o,s,l,r,t);}let u=await i.introspection.getTables();await Pn(i,a,u,t),await Nn(i,e,u,t);}function ge(i,e,t,n){if(!i)throw new Error("Schema not initialized");let r=i[e];if(!r)throw new Error("Resource not found");let a=n.$or,u=n.$and;return (a?t.or:t.and)(a?n.$or.map(o=>ge(i,e,t,o)):u?n.$and.map(o=>ge(i,e,t,o)):Object.entries(n).map(([o,s])=>{var c,l;if(r.fields[o])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${o}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${o}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((c=s==null?void 0:s.$not)==null?void 0:c.$in)!==void 0?t(`${e}.${o}`,"not in",s.$not.$in):((l=s==null?void 0:s.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${o}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${o}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${o}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${o}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${o}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${o}`,"<=",s.$lte):t(`${e}.${o}`,s===null?"is":"=",s);if(r.relations[o]){let d=r.relations[o],y=d.entity.name;return d.type==="many"?t.exists(be(i,y,t.selectFrom(y).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),s)):ge(i,y,t,s)}return null}).filter(Boolean))}function Re(i,e,t,n){let r=i[e];if(!r)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let a of n.$and)t=Re(i,e,t,a);return t}else if(n.$or){for(let a of n.$or)t=Re(i,e,t,a);return t}for(let[a,u]of Object.entries(n)){if(!r.relations[a])continue;let o=r.relations[a],s=o.entity.name,c=o.type==="one"?"id":o.foreignColumn,l=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(s,`${s}.${c}`,`${e}.${l}`),u instanceof Object&&!Array.isArray(u)&&u!==null&&(t=Re(i,s,t,u));}return t}function be(i,e,t,n){return !n||Object.keys(n).length===0?t:(t=Re(i,e,t,n),t.where(r=>ge(i,e,r,n)))}function Vn(i,e,t,n,r){let a=D(r),u=e[t];if(a==="sqlite"&&(u!=null&&u.fields)){let o=Object.keys(u.fields),s=i.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return i.selectFrom(n).selectAll(n)}function kn(i,e,t,n,r){let a=D(r),u=e[t];if(a==="sqlite"&&(u!=null&&u.fields)){let o=Object.keys(u.fields),s=i.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return i.selectFrom(n).selectAll(n)}function xe(i,e,t,n,r,a){if(!n)return t;if(!i)throw new Error("Schema not initialized");let u=i[e];if(!u)throw new Error(`Resource not found: ${e}`);let{jsonObjectFrom:o,jsonArrayFrom:s}=r;for(let c of Object.keys(n)){if(!u.relations[c])throw new Error(`Relation ${c} not found in resource ${e}`);let l=u.relations[c],d=l.entity.name,y=n[c],p=l.type==="one"?"id":l.foreignColumn,h=l.type==="one"?l.relationalColumn:"id",f=l.type==="one"?o:s,m=ye(y)?y:null,g=m==null?void 0:m.include;t=t.select(T=>{let R=`${d}_meta`,b=kn(T,i,d,d,a).whereRef(`${d}.${p}`,"=",`${e}.${h}`).select(x=>o(Vn(x,i,d,R,a).whereRef(`${R}.id`,"=",`${d}.id`)).as("_meta"));if(m!=null&&m.where&&(b=be(i,d,b,m.where)),m!=null&&m.orderBy)for(let x of m.orderBy)b=b.orderBy(`${d}.${x.key}`,x.direction);return (m==null?void 0:m.limit)!==void 0&&(b=b.limit(m.limit)),g&&Object.keys(g).length>0&&(b=xe(i,d,b,g,r,a)),f(b).as(c)});}return t}var Be=class i extends X{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,n,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.dialectHelpers=ft(this.db),this.schema=t,this.logger=n,this.server=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t,n){this.schema=e,this.logger=t,this.server=n,await gt(this.db,e,t);}selectMetaColumns(e,t,n){var u;let r=D(this.db),a=(u=this.schema)==null?void 0:u[t];if(r==="sqlite"&&(a!=null&&a.fields)){let o=Object.keys(a.fields),s=e.selectFrom(n);for(let c of o)s=s.select(`${n}.${c}`);return s}return e.selectFrom(n).selectAll(n)}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let r=`${e}_meta`,a=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(s,e,r).whereRef(`${r}.id`,"=",`${e}.id`)).as("_meta"));a=xe(this.schema,e,a,n,this.dialectHelpers,this.db);let u=await a.executeTakeFirst();if(!u)return;let o=this.parseRelationalJsonStrings(u,e);return this.convertToMaterializedLiveType(o,e)}async findOne(e,t,n){let r=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(r)return S(r)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:r,limit:a,sort:u}=e,o=`${t}_meta`,s=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,o).whereRef(`${o}.id`,"=",`${t}.id`)).as("_meta"));s=be(this.schema,t,s,n),s=xe(this.schema,t,s,r,this.dialectHelpers,this.db),a!==void 0&&(s=s.limit(a)),u!==void 0&&u.forEach(l=>{s=s.orderBy(l.key,l.direction);});let c=await s.execute();return c.length===0?[]:c.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(r=>S(r))}async rawInsert(e,t,n,r,a){var f,m,g,T,R,b,x,w,j,V,E;let u=(f=this.server)==null?void 0:f.getHooks(e),o=(m=this.schema)==null?void 0:m[e],[s,c]=((g=o==null?void 0:o.mergeMutation)==null?void 0:g.call(o,"set",n.value,void 0))??[n,n.value];if(!c)return {data:n,acceptedValues:null};let l=s,d={...l,value:{...l.value,id:{value:t}}};if(u!=null&&u.beforeInsert){let C=S(d);C.id=t;let M=await u.beforeInsert({ctx:a,value:C,rawValue:d,db:this});M&&(l=M);}let y={},p={};for(let[C,M]of Object.entries(l.value)){let L=(T=M._meta)==null?void 0:T.timestamp;if(!L)continue;let A=(b=(R=o==null?void 0:o.fields[C])==null?void 0:R.getStorageFieldType)==null?void 0:b.call(R);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[C]=JSON.stringify(M.value):y[C]=M.value,p[C]=L;}await this.db.insertInto(e).values({...y,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...p,id:t}).execute(),(w=(x=this.logger)==null?void 0:x.debug)==null||w.call(x,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(a==null?void 0:a.messageId)??"(none)",hasContext:!!a,contextKeys:a?Object.keys(a):[]});let h=this.buildMutation(e,t,"INSERT",l,r,a==null?void 0:a.messageId);if(h&&((E=(j=this.logger)==null?void 0:j.debug)==null||E.call(j,"[rawInsert] Mutation built, tracking",{mutationId:h.id,hasMeta:!!h.meta,originMutationId:((V=h.meta)==null?void 0:V.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(h,l)),u!=null&&u.afterInsert){let C={...l,value:{...l.value,id:{value:t}}},M=S(C);M.id=t,await u.afterInsert({ctx:a,value:M,rawValue:C,db:this});}return {data:l,acceptedValues:c}}async rawUpdate(e,t,n,r,a){var m,g,T,R,b,x,w,j,V,E,C;let u=(m=this.server)==null?void 0:m.getHooks(e),o=(g=this.schema)==null?void 0:g[e],s=await this.rawFindById(e,t),[c,l]=((T=o==null?void 0:o.mergeMutation)==null?void 0:T.call(o,"set",n.value,s))??[n,n.value];if(!l)return {data:n,acceptedValues:null};let d=c,y={...d,value:{...d.value,id:{value:t}}};if(u!=null&&u.beforeUpdate){let M=S(y);M.id=t;let L;if(s){let O={...s,value:{...s.value,id:{value:t}}};L=S(O),L.id=t;}let A=await u.beforeUpdate({ctx:a,value:M,rawValue:y,previousValue:L,previousRawValue:s,db:this});A&&(d=A);}let p={},h={};for(let[M,L]of Object.entries(d.value)){let A=(R=L._meta)==null?void 0:R.timestamp;if(!A)continue;let O=(x=(b=o==null?void 0:o.fields[M])==null?void 0:b.getStorageFieldType)==null?void 0:x.call(b);(O==null?void 0:O.type)==="jsonb"||(O==null?void 0:O.type)==="json"?p[M]=JSON.stringify(L.value):p[M]=L.value,h[M]=A;}if(Object.keys(p).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(p).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...h,id:t}).onConflict(M=>M.column("id").doUpdateSet(h)).execute()]),(j=(w=this.logger)==null?void 0:w.debug)==null||j.call(w,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:r??"(auto-generated)",contextMessageId:(a==null?void 0:a.messageId)??"(none)",hasContext:!!a,contextKeys:a?Object.keys(a):[]});let f=this.buildMutation(e,t,"UPDATE",d,r,a==null?void 0:a.messageId);if(f){(C=(V=this.logger)==null?void 0:V.debug)==null||C.call(V,"[rawUpdate] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((E=f.meta)==null?void 0:E.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let M=await this.rawFindById(e,t);M&&this.trackMutation(f,M);}if(u!=null&&u.afterUpdate){let M=await this.rawFindById(e,t);if(M){let L={...M,value:{...M.value,id:{value:t}}},A=S(L);A.id=t;let O;if(s){let Se={...s,value:{...s.value,id:{value:t}}};O=S(Se),O.id=t;}await u.afterUpdate({ctx:a,value:A,rawValue:L,previousValue:O,previousRawValue:s,db:this});}}return {data:d,acceptedValues:l}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let a=Math.random().toString(36).substring(2,15),u=this.mutationStack,o=[];this.mutationStack=o;let s=await this.db.savepoint(a).execute(),c=false,l=false;try{return await e({trx:this,commit:async()=>{await s.releaseSavepoint(a).execute(),c=!0,u.push(...o);},rollback:async()=>{await s.rollbackToSavepoint(a).execute(),l=!0,o.length=0;}}).then(d=>s.isCommitted||s.isRolledBack||c||l?d:s.releaseSavepoint(a).execute().then(()=>(u.push(...o),d)))}catch(d){throw l||await s.rollbackToSavepoint(a).execute().catch(()=>{}),o.length=0,d}finally{this.mutationStack=u;}}let t=[],n=this.mutationStack;this.mutationStack=t;let r=await this.db.startTransaction().execute();try{let a=new i(r,this.schema,this.logger,this.server);return a.mutationStack=t,await e({trx:a,commit:async()=>{var u,o;await r.commit().execute(),(o=(u=this.logger)==null?void 0:u.debug)==null||o.call(u,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:s})=>{var c;return {id:s.id,resource:s.resource,resourceId:s.resourceId,procedure:s.procedure,hasMeta:!!s.meta,originMutationId:((c=s.meta)==null?void 0:c.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await r.rollback().execute(),t.length=0;}}).then(u=>r.isCommitted||r.isRolledBack?u:r.commit().execute().then(()=>{var o,s;return (s=(o=this.logger)==null?void 0:o.debug)==null||s.call(o,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:c})=>{var l;return {id:c.id,resource:c.resource,resourceId:c.resourceId,procedure:c.procedure,hasMeta:!!c.meta,originMutationId:((l=c.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t),u}))}catch(a){throw await r.rollback().execute(),t.length=0,a}finally{this.mutationStack=n;}}get internalDB(){return this.db}isRelationalField(e,t){var r;if(!this.schema)return false;let n=this.schema[e];return !!((r=n==null?void 0:n.relations)!=null&&r[t])}parseRelationalJsonStrings(e,t){var a,u;if(D(this.db)!=="sqlite"||typeof e!="object"||e===null||e instanceof Date)return e;if(Array.isArray(e))return e.map(o=>this.parseRelationalJsonStrings(o,t));let r={};for(let[o,s]of Object.entries(e))if(o==="_meta"&&typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{r[o]=JSON.parse(s);}catch{r[o]=s;}else r[o]=s;else if(this.isRelationalField(t,o))if(typeof s=="string")if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{let c=JSON.parse(s);if(this.schema){let l=this.schema[t],d=(a=l==null?void 0:l.relations)==null?void 0:a[o];if(d){let y=d.entity.name;r[o]=this.parseRelationalJsonStrings(c,y);}else r[o]=c;}else r[o]=c;}catch{r[o]=s;}else r[o]=s;else if(typeof s=="object"&&s!==null&&!Array.isArray(s))if(this.schema){let c=this.schema[t],l=(u=c==null?void 0:c.relations)==null?void 0:u[o];if(l){let d=l.entity.name;r[o]=this.parseRelationalJsonStrings(s,d);}else r[o]=s;}else r[o]=s;else Array.isArray(s)?r[o]=s.map(c=>{var l,d;if(typeof c=="string")try{let y=JSON.parse(c);if(this.schema){let p=this.schema[t],h=(l=p==null?void 0:p.relations)==null?void 0:l[o];if(h){let f=h.entity.name;return this.parseRelationalJsonStrings(y,f)}}return y}catch{return c}if(typeof c=="object"&&c!==null&&this.schema){let y=this.schema[t],p=(d=y==null?void 0:y.relations)==null?void 0:d[o];if(p){let h=p.entity.name;return this.parseRelationalJsonStrings(c,h)}}return c}):r[o]=s;else r[o]=s;return r}convertToMaterializedLiveType(e,t){var r;let n=(r=this.schema)==null?void 0:r[t];return {value:Object.entries(e).reduce((a,[u,o])=>{var d,y,p,h,f,m,g,T,R;if(u==="_meta")return a;let s=(y=(d=n==null?void 0:n.fields[u])==null?void 0:d.getStorageFieldType)==null?void 0:y.call(d),c=(s==null?void 0:s.type)==="jsonb"||(s==null?void 0:s.type)==="json",l=(n==null?void 0:n.relations)&&u in n.relations;if(u==="id")a[u]={value:o};else if(c)a[u]={value:o,_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[u]}};else if(l){let b=n.relations[u].entity,x=(b==null?void 0:b.name)??t;Array.isArray(o)?a[u]={value:o.map(w=>this.convertToMaterializedLiveType(w,x)),_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[u],relation:true}}:o!==null&&typeof o=="object"?a[u]={...this.convertToMaterializedLiveType(o,x),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[u],relation:true}}:a[u]={value:o,_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[u],relation:true}};}else Array.isArray(o)?a[u]={value:o,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[u]}}:typeof o=="object"&&o!==null&&!(o instanceof Date)?a[u]={value:o,_meta:{timestamp:(T=e==null?void 0:e._meta)==null?void 0:T[u]}}:a[u]={value:o,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[u]}};return a},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",r=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",u=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&r||a&&u}buildMutation(e,t,n,r,a,u){var s;let o={};for(let[c,l]of Object.entries(r.value)){if(c==="id")continue;let d=(s=l._meta)==null?void 0:s.timestamp;d&&(o[c]={value:l.value,_meta:{timestamp:d}});}return Object.keys(o).length===0?null:{id:a??le(),type:"MUTATE",resource:e,resourceId:t,procedure:n,payload:o,meta:u?{originMutationId:u}:void 0}}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 n=e;for(let r of n)this.server.notifySubscribers(r,t);}else {let n=e;for(let{mutation:r,entityData:a}of n)this.server.notifySubscribers(r,a);}}};var ze=class i{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var r;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=Ye({level:e.logLevel??_.INFO}),(r=e.middlewares)==null||r.forEach(a=>{this.middlewares.add(a);});let t=this.router.hooksRegistry,n=new Set;if(t&&t.forEach((a,u)=>{n.add(u);}),e.hooks)for(let a of Object.keys(e.hooks))n.add(a);n.forEach(a=>{var c;let u=t==null?void 0:t.get(a),o=(c=e.hooks)==null?void 0:c[a],s=Ae([u,o]);s&&this.hooksRegistry.set(a,s);}),this.initPromise=this.storage.init(this.schema,this.logger,this).catch(a=>{this.initError=a;}),this.contextProvider=e.contextProvider,this.queryEngine=new pe({router:{get:async(a,u)=>{var p;let{headers:o,cookies:s,queryParams:c,context:l}=(u==null?void 0:u.context)??{};if(!(u!=null&&u.batcher))throw new Error("Batcher is required");let d={...a,type:"QUERY",headers:o,cookies:s,queryParams:c,context:l},y=await((p=this.router.routes[a.resource])==null?void 0:p.handleQuery({req:d,batcher:u.batcher}));return (y==null?void 0:y.data)??[]},incrementQueryStep:(a,u={})=>{var c;let o=(c=this.router.routes[a.query.resource])==null?void 0:c.getAuthorizationClause({...a.query,type:"QUERY",headers:u.headers,cookies:u.cookies,queryParams:u.queryParams,context:u.context});if(typeof o=="boolean"&&!o)throw new Error("Not authorized");let s=J(a.query.where,typeof o=="object"?o:void 0);return {...a,query:{...a.query,where:s}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new i(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleQuery(e){return await this.ensureInitialized(),this.wrapInMiddlewares(async t=>{let{headers:n,cookies:r,queryParams:a,context:u,...o}=t,s={headers:n,cookies:r,queryParams:a,context:u},c=e.subscription?this.queryEngine.subscribe(o,d=>{var y;(y=e.subscription)==null||y.call(e,d);},s):void 0;return {data:await this.queryEngine.get(o,{context:s}),unsubscribe:c}})(e.req)}async handleMutation(e){return await this.ensureInitialized(),await this.wrapInMiddlewares(async n=>{let r=this.router.routes[n.resource];if(!r)throw new Error("Invalid resource");return r.handleMutation({req:n,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async y=>{let p=this.router.routes[y.resource];if(!p)throw new Error("Invalid resource");return p.handleCustomQuery({req:y,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:r,cookies:a,queryParams:u,context:o}=e.req,s={headers:r,cookies:a,queryParams:u,context:o},c=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(c,y=>{var p;(p=e.subscription)==null||p.call(e,y);},s):void 0,d=await this.queryEngine.get(c,{context:s});return e.subscription?{data:d,unsubscribe:l,query:c}:d.map(y=>S(y))}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((n,r)=>a=>r({req:a,next:n}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},Di=ze.create;exports.ProcedureRoute=qe;exports.Route=Qe;exports.RouteFactory=$e;exports.Router=ke;exports.SQLStorage=Be;exports.Server=ze;exports.Storage=X;exports.createMiddleware=ui;exports.createServerDB=K;exports.defineHooks=vr;exports.expressAdapter=Zr;exports.mergeEntityHooks=Ae;exports.mergeHooks=wr;exports.routeFactory=ci;exports.router=oi;exports.server=Di;
|
package/dist/server.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {a,b,B as B$1,z as z$2,C,D as D$1,G,F,E}from'./chunk-3XEJ2M4E.js';import Z from'crypto';import Mt,{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 he=a(re=>{Object.defineProperty(re,"__esModule",{value:true});re.parse=bt;re.serialize=St;var mt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,pt=/^[\u0021-\u003A\u003C-\u007E]*$/,ft=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,gt=/^[\u0020-\u003A\u003D-\u007E]*$/,Tt=Object.prototype.toString,Rt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function bt(c,e){let t=new Rt,r=c.length;if(r<2)return t;let i=(e==null?void 0:e.decode)||wt,s=0;do{let o=c.indexOf("=",s);if(o===-1)break;let a=c.indexOf(";",s),n=a===-1?r:a;if(o>n){s=c.lastIndexOf(";",o-1)+1;continue}let u=Qe(c,s,o),l=Ne(c,o,u),d=c.slice(u,l);if(t[d]===void 0){let h=Qe(c,o+1,n),y=Ne(c,n,h),p=i(c.slice(h,y));t[d]=p;}s=n+1;}while(s<r);return t}function Qe(c,e,t){do{let r=c.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Ne(c,e,t){for(;e>t;){let r=c.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function St(c,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!mt.test(c))throw new TypeError(`argument name is invalid: ${c}`);let i=r(e);if(!pt.test(i))throw new TypeError(`argument val is invalid: ${e}`);let s=c+"="+i;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(!ft.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);s+="; Domain="+t.domain;}if(t.path){if(!gt.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);s+="; Path="+t.path;}if(t.expires){if(!xt(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 wt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function xt(c){return Tt.call(c)==="[object Date]"}});var Pe="0123456789ABCDEFGHJKMNPQRSTVWXYZ",H=32;var it=16,Le=10,Ee=0xffffffffffff;var q;(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";})(q||(q={}));var _=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function st(c){let e=Math.floor(c()*H);return e===H&&(e=H-1),Pe.charAt(e)}function at(c){var r;let e=ot(),t=e&&(e.crypto||e.msCrypto)||(typeof Z<"u"?Z:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return t.getRandomValues(i),i[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=Z)!=null&&r.randomBytes)return ()=>Z.randomBytes(1).readUInt8()/255;throw new _(q.PRNGDetectFailure,"Failed to find a reliable PRNG")}function ot(){return dt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function ct(c,e){let t="";for(;c>0;c--)t=st(e)+t;return t}function ut(c,e=Le){if(isNaN(c))throw new _(q.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>Ee)throw new _(q.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Ee}: ${c}`);if(c<0)throw new _(q.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new _(q.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,r="";for(let i=e;i>0;i--)t=c%H,r=Pe.charAt(t)+r,c=(c-t)/H;return r}function dt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ke(c,e){let t=at(),r=Date.now();return ut(r,Le)+ct(it,t)}var X=()=>ke().toLowerCase(),Y=c=>({then(e,t){try{if(e){let r=e(c);return r instanceof Promise?r:Y(r)}return Y(c)}catch(r){if(t){let i=t(r);return i instanceof Promise?i:Y(i)}throw r}}}),de=c=>c instanceof Promise?c:Y(c);var z=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var ee=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...i}){return new Promise((s,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...i}),n={resource:e,commonWhere:t,uniqueWhere:r,...i,resolve:s,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(n),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...i}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(i??{})}`}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(i=>{i.reject(r);});}}async executeBatchedRequests(e){var h;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:i,include:s,sort:o}=t,a=e.length===1?t.limit:void 0,n=e.map(y=>y.uniqueWhere).filter(y=>y!==void 0),u=i,l=(h=Object.entries(n[0]??{})[0])==null?void 0:h[0];if(n.length>0){let y=n.map(p=>p[l]).filter(p=>p!=null);y.length>0&&(u=z(i,{[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 p=d;if(y.uniqueWhere){let[m,g]=Object.entries(y.uniqueWhere)[0];p=d.filter(T=>{var f;return ((f=T.value[m])==null?void 0:f.value)===g});}y.resolve(p);}}};function le(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 te=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[i,s]of Object.entries(r.relations))s.type==="one"&&s.relationalColumn&&t.set(String(s.relationalColumn),{relationName:i,targetResource:s.entity.name});return t}ensureObjectNode(e,t,r){let i=this.objectNodes.get(e);return i?r&&i.matchedQueries.add(r):(i={id:e,type:t,matchedQueries:new Set(r?[r]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,i)),i}storeRelation(e,t,r,i){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.set(r,t),o&&i){let a=o.referencedByObjects.get(i);a||(a=new Set,o.referencedByObjects.set(i,a)),a.add(e);}}removeRelation(e,t,r,i){let s=this.objectNodes.get(e),o=this.objectNodes.get(t);if(s&&s.referencesObjects.delete(r),o&&i){let a=o.referencedByObjects.get(i);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(i));}}getInverseRelationName(e,t,r){let i=this.schema[e];if(!(i!=null&&i.relations))return;let s=i.relations[r];if(!s)return;let o=this.schema[t];if(o!=null&&o.relations){if(s.type==="many"&&s.foreignColumn){for(let[a,n]of Object.entries(o.relations))if(n.entity.name===e&&n.type==="one"&&n.relationalColumn===s.foreignColumn)return a}if(s.type==="one"&&s.relationalColumn){for(let[a,n]of Object.entries(o.relations))if(n.entity.name===e&&n.type==="many"&&n.foreignColumn===s.relationalColumn)return a}}}updateRelationsFromMutation(e,t,r,i){let s=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:n,targetResource:u}]of Array.from(s)){if(!(i&&a in i))continue;let d=this.getInverseRelationName(e,u,n),h=o.referencesObjects.get(n),y=r[a];h!==y&&(h&&this.removeRelation(t,h,n,d),y&&(this.ensureObjectNode(y,u),this.storeRelation(t,y,n,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 ee(this.storage)})}subscribe(e,t,r={}){let i=this.breakdownQuery({query:e,context:r}),s={},o=[];for(let a of i){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let n=le(a),u=s[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",d=this.queryNodes.get(n);if(d)d.subscriptions.add(t);else if(d={hash:n,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]=n,o.push(()=>{let h=this.queryNodes.get(n);h&&(h.subscriptions.delete(t),h.subscriptions.size===0&&this.queryNodes.delete(n));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var g;let{query:t,stepPath:r=[],context:i={},parentResource:s}=e,{include:o}=t,a=r.length===0,n=r.at(-1),u,l,d;if(!a&&s&&n){let T=this.schema[s],f=(g=T==null?void 0:T.relations)==null?void 0:g[n];f&&(d=f.type==="many",f.type==="one"?(u=R=>({id:R}),l=R=>R.map(b=>{var S,v;return (v=(S=b.value)==null?void 0:S[f.relationalColumn])==null?void 0:v.value}).filter(b=>b!==void 0)):(u=R=>({[f.foreignColumn]:R}),l=R=>R.map(b=>{var S,v;return (v=(S=b.value)==null?void 0:S.id)==null?void 0:v.value}).filter(b=>b!==void 0)));}let{include:h,...y}=t,m=[this.router.incrementQueryStep({query:y,stepPath:[...r],getWhere:u,referenceGetter:l,isMany:d,relationName:n},i)];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`);m.push(...Object.entries(o).flatMap(([f,R])=>{let b=T.relations[f];if(!b)throw new Error(`Relation ${f} not found for resource ${t.resource}`);let S=b.entity.name,v=E(R)?R:null;return this.breakdownQuery({query:{resource:S,include:v?v.include:typeof R=="object"?R:void 0,where:v==null?void 0:v.where,limit:v==null?void 0:v.limit,sort:v==null?void 0:v.orderBy},stepPath:[...r,f],context:i,parentResource:t.resource})}));}return m}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(s=>s.stepPath.join(".")).join(" -> "));let r={},i=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(".");i=i.then(async()=>{var u,l;let n=r[a];if(!n){r[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let d=new Map;for(let p of n)for(let m of p.data){let g=(l=(u=m==null?void 0:m.value)==null?void 0:u.id)==null?void 0:l.value;if(!g)continue;let f=o.referenceGetter([m])[0];if(f){d.has(f)||d.set(f,new Set);let R=d.get(f);R&&R.add(g);}}let h=Array.from(d.keys());if(h.length===0){r[o.stepPath.join(".")]=[];return}let y=[];for(let p of h){let m=o.getWhere(p),g={...o,relationalWhere:m},T=await this.resolveStep(g,t),f=d.get(p);if(f)for(let R of Array.from(f))y.push({includedBy:R,data:T});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",y.reduce((p,m)=>p+m.data.length,0)),r[o.stepPath.join(".")]=y;}else {let d=await this.resolveStep(o,t);r[o.stepPath.join(".")]=[{data:d}];}});}return i=i.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,r)))),i}assembleResults(e,t){var o,a,n,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]??[],p=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${h}"`,{resource:d.query.resource,includedRelations:p,resultGroups:y.length,isMany:d.isMany,relationName:d.relationName});for(let m of y){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${h}"`,{dataCount:m.data.length,includedBy:m.includedBy});for(let g of m.data){let T=(a=(o=g==null?void 0:g.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 f=h?`${h}.${T}`:T,R=[];if(d.stepPath.length>0&&m.includedBy){let S=d.stepPath.slice(0,-1).join(".");R=[S?`${S}.${m.includedBy}`:m.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${f}" has parent keys:`,R,{stepPath:h,parentStepPath:S,includedBy:m.includedBy});}else this.logger.debug(`[QueryEngine] assembleResults: Root entity "${f}" (no parent)`);let b=r.get(f);if(b){this.logger.debug(`[QueryEngine] assembleResults: Entity "${f}" already exists, adding parent keys:`,R);for(let S of R)b.includedBy.add(S);}else this.logger.debug(`[QueryEngine] assembleResults: Adding new entity "${f}"`,{resource:d.query.resource,path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,includedRelations:p,parentKeys:R}),r.set(f,{data:g,includedBy:new Set(R),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:p});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${r.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(r.keys()));let i=Array.from(r.entries()),s=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${i.length} entries`);for(let d=i.length-1;d>=0;d--){let[h,y]=i[d],p=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 m of y.includedRelations){let g=(u=(n=p==null?void 0:p.relations)==null?void 0:n[m])==null?void 0:u.type,T=!!y.data.value[m];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${m}" for "${h}"`,{relationType:g,hasRelation:T,resourceHasRelation:!!((l=p==null?void 0:p.relations)!=null&&l[m])}),y.data.value[m])this.logger.debug(`[QueryEngine] assembleResults: Relation "${m}" already exists for "${h}"`,y.data.value[m]);else {let f=g==="many"?{value:[]}:{value:null};y.data.value[m]=f,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${m}" for "${h}" with`,f);}}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 m of Array.from(y.includedBy)){let g=r.get(m);if(!g){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${m}" not found in entriesMap for child "${h}"`);continue}let T=y.relationName??y.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${h}" to parent "${m}" via relation "${T}"`,{isMany:y.isMany,parentHasRelation:!!g.data.value[T]}),y.isMany?(g.data.value[T]??={value:[]},g.data.value[T].value.push(y.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${h}" to many relation "${T}" on parent "${m}"`,{arrayLength:g.data.value[T].value.length})):(g.data.value[T]=y.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${m}" 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:i}=e,s=r.where&&i?z(r.where,i):i??r.where,o=s?{...r,where:s}:r;return de(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=le(e),i=this.queryNodes.get(r),s=e.query.resource;if(!i)return;let o=this.getRelationalColumns(s);for(let a of t){let n=z$2(a),u=n.id;this.ensureObjectNode(u,s,r),i.trackedObjects.add(u);for(let[l,{relationName:d,targetResource:h}]of Array.from(o)){let y=n[l];if(y){this.ensureObjectNode(y,h);let p=this.getInverseRelationName(s,h,d);this.storeRelation(u,y,d,p);}}this.loadNestedRelations(s,u,n),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,r){let i=this.schema[e];if(i!=null&&i.relations)for(let[s,o]of Object.entries(i.relations)){let a=r[s];if(!a)continue;let n=o.entity.name,u=this.getInverseRelationName(e,n,s);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,n),this.storeRelation(t,a.id,s,u),this.loadNestedRelations(n,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,n);let d=this.getInverseRelationName(n,e,s);d&&this.storeRelation(l.id,t,d,s),this.loadNestedRelations(n,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let r={};for(let i of Array.from(t.childQueries)){let s=this.queryNodes.get(i);if(!s||!s.relationName)continue;let o=this.buildIncludeFromChildQueries(i);r[s.relationName]=Object.keys(o).length>0?o:true;}return r}sendInsertsForTree(e,t,r){var a,n;let i=(n=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:n.value;if(!i)return;let s={procedure:"INSERT",resource:r,resourceId:i,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:i,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(i),this.ensureObjectNode(i,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 p=y.value;if(Array.isArray(p))for(let m of p)this.sendInsertsForTree(l,m,h);else p&&typeof p=="object"&&this.sendInsertsForTree(l,p,h);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let r=z$2(t);if(!r)return;let i={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,i);let s=this.getRelationalColumns(e.resource);for(let[a,{relationName:n,targetResource:u}]of Array.from(s)){let l=r[a];if(l){this.ensureObjectNode(l,u);let d=this.getInverseRelationName(e.resource,u,n);this.storeRelation(e.resourceId,l,n,d);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,r).then(a=>{for(let n of a){let u=this.queryNodes.get(n);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(n);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 i=this.objectNodes.get(e.resourceId),s=new Set((i==null?void 0:i.matchedQueries)??[]);i||(i={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,i)),this.updateRelationsFromMutation(e.resource,e.resourceId,r,e.payload),this.getMatchingQueries(e,r).then(o=>{let a=new Set(o),n=[],u=[],l=[];for(let h of o)s.has(h)?l.push(h):n.push(h);for(let h of Array.from(s))a.has(h)||u.push(h);for(let h of n){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 n)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 p of Array.from(y.subscriptions))try{p(e);}catch(m){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:m,queryHash:y.hash,resource:e.resource,resourceId:e.resourceId,stepPath:y.queryStep.stepPath.join(".")});}}if(n.length>0)for(let h of n){let y=this.queryNodes.get(h);if(!y)continue;let p=this.buildIncludeFromChildQueries(h);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(p).length>0?p:void 0}).then(m=>{!m||m.length===0||this.sendInsertsForTree(y,m[0],e.resource);});}});return}}getMatchingQueries(e,t){let r=[];for(let i of Array.from(this.queryNodes.values()))i.queryStep.query.resource===e.resource&&r.push(i);return r.length===0?de([]):Promise.all(r.map(async i=>{let s=i.queryStep.query.where,o=i.queryStep.query.resource,a=e.resourceId,n=this.objectNodes.get(a);if(!n)return {hash:i.hash,matches:false};if(i.relationName){let y=i.parentQuery?this.queryNodes.get(i.parentQuery):void 0,p=y==null?void 0:y.queryStep.query.resource,m=p?this.getInverseRelationName(p,o,i.relationName):void 0,g=m?n.referencesObjects.get(m):void 0;if(!g)return {hash:i.hash,matches:false};let T=this.objectNodes.get(g);return !T||!y||!T.matchedQueries.has(y.hash)?{hash:i.hash,matches:false}:{hash:i.hash,matches:true}}if(!s)return {hash:i.hash,matches:true};let u=C(s,o,this.schema),l=Object.keys(u).length>0;if(!l&&t!==void 0)return {hash:i.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:i.hash,matches:false};let h=z$2(d[0]);return h?{hash:i.hash,matches:D$1(h,s)}:{hash:i.hash,matches:false}})).then(i=>i.filter(s=>s.matches).map(s=>s.hash))}};var gr=c=>c,lt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],yt=c=>c.length===1?c[0]:(async e=>{let t=e.rawValue,r=e.value,i=false;for(let s of c){let o=await s({...e,value:r,rawValue:t});o&&(t=o,r=z$2(t),r.id=e.value.id,i=true);}return i?t:void 0}),ht=c=>c.length===1?c[0]:(async e=>{for(let t of c)await t(e);}),ye=c=>{let e=c.filter(r=>r!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let r of lt){let i=e.map(s=>s[r]).filter(s=>s!=null);i.length!==0&&(r==="afterInsert"||r==="afterUpdate"?t[r]=ht(i):t[r]=yt(i));}return t},Tr=(...c)=>{let e={},t=new Set;for(let r of c)for(let i of Object.keys(r))t.add(i);for(let r of Array.from(t)){let i=c.map(o=>o[r]),s=ye(i);s&&(e[r]=s);}return e};var Ve=b(he(),1);var ne=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()}),me=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()})),vt=me.superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),$e=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),qe=z$1.object({timestamp:z$1.string().optional(),originMutationId:z$1.string().optional()}).optional(),B=$e.extend({procedure:z$1.string(),payload:z$1.any().optional(),meta:qe}),U=$e.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:vt,meta:qe});z$1.union([U,B]);var _e=z$1.object({resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()});var De=ne.omit({resource:true}),ie=B.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:B.shape.meta}),pe=U.omit({id:true,type:true,resource:true,procedure:true});z$1.union([pe,ie]);var fe=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(fe);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,r]of Object.entries(c))e[t]=fe(r);return e}return c},ze=c=>{let e=c.logger;return async t=>{var r;try{let i=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,s={headers:i,cookies:i.cookie?Ve.default.parse(i.cookie):{}},o=new URL(t.url),a=o.pathname.split("/"),n=o.searchParams,u=fe(Mt.parse(n.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:p}=De.safeParse(u);if(!h)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let m=await c.handleQuery({req:{...s,...y,type:"QUERY",resource:d,context:l,queryParams:u}});return !m||!m.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(m.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 f=a[a.length-3],R=t.body?await t.json():{};if(!f||f.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let b=await c.handleCustomQuery({req:{...s,type:"CUSTOM_QUERY",resource:f,procedure:d,input:R.input,context:l,queryParams:u}});return Response.json(b)}let y=h,p=t.body?await t.json():{},m,g=d;if(d==="insert"||d==="update"){let f=pe.safeParse(p);if(f.success)m=f.data,g=d.toUpperCase();else {if(!(typeof p=="object"&&p!==null&&"payload"in p&&"meta"in p))return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:f.error},{status:400});let b=ie.safeParse(p);if(!b.success)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b.error},{status:400});m=b.data;}}else {let{success:f,data:R,error:b}=ie.safeParse(p);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});m=R;}let T=await c.handleMutation({req:{...s,type:"MUTATE",resource:y,input:m.payload,context:l,resourceId:m.resourceId,procedure:g,queryParams:{},meta:m.meta}});return Response.json(T)}catch(d){return e.error("Error parsing mutation from the client:",d),d instanceof Error&&d.message.includes("Unknown procedure")?Response.json({message:d.message,code:"UNKNOWN_PROCEDURE"},{status:400}):Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(i){return e.error("Unexpected error:",i),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var He=b(he(),1);var N=z$1.string(),ge=z$1.union([_e,ne]),Ct=z$1.object({id:N,type:z$1.literal("SUBSCRIBE")}).and(ge),jt=z$1.object({id:N,type:z$1.literal("UNSUBSCRIBE")}).and(ge),Ot=z$1.object({id:N,type:z$1.literal("QUERY")}).and(ge),At=z$1.object({id:N,type:z$1.literal("CUSTOM_QUERY"),resource:z$1.string(),procedure:z$1.string(),input:z$1.any().optional()}),Be=U.extend({id:N}),Et=B.extend({id:N}),Pt=z$1.union([Et,Be]),Fe=z$1.union([Ct,Ot,At,Pt,jt]),Lt=z$1.object({id:N,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),kt=z$1.object({id:N,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([Lt,kt,Be]);z$1.object({resource:z$1.string(),data:z$1.array(me)});var Ue=c=>{let e={},t=c.logger;return (r,i)=>{var d;let s=h=>{r.send(JSON.stringify(h));},o=X(),a=new Map,n={headers:i.headers,cookies:typeof i.headers.cookie=="string"?He.default.parse(i.headers.cookie):{}},u=parse(i.url.split("?")[1]),l=(d=c.contextProvider)==null?void 0:d.call(c,{transport:"WEBSOCKET",headers:n.headers,cookies:n.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=Fe.parse(JSON.parse(h.toString()));if(y.type==="SUBSCRIBE"||y.type==="QUERY"){let{type:p,id:m,...g}=y,T=p==="SUBSCRIBE";if("procedure"in g){let f=await c.handleCustomQuery({req:{...n,type:"CUSTOM_QUERY",resource:g.resource,procedure:g.procedure,input:g.input,context:await l??{},queryParams:u},subscription:T?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[o])==null||b.send(JSON.stringify(R));}:void 0});if(T){if(!f||!f.data||!f.query)throw new Error("Invalid resource");f.unsubscribe&&a.set(B$1(g),f.unsubscribe),s({id:m,type:"REPLY",data:{resource:f.query.resource,data:(f.data??[]).map(R=>R.value)}});}else s({id:m,type:"REPLY",data:f});}else {let f=await c.handleQuery({req:{...n,...g,type:"QUERY",context:await l??{},queryParams:u},subscription:T?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[o])==null||b.send(JSON.stringify(R));}:void 0});if(!f||!f.data)throw new Error("Invalid resource");T&&f.unsubscribe&&a.set(B$1(g),f.unsubscribe),s({id:m,type:"REPLY",data:{resource:g.resource,data:(f.data??[]).map(R=>R.value)}});}}else if(y.type==="UNSUBSCRIBE"){let{type:p,id:m,...g}=y,T=a.get(B$1(g));T&&(T(),a.delete(B$1(g)));}else if(y.type==="CUSTOM_QUERY"){let{resource:p,procedure:m,input:g,id:T}=y;t.debug("Received custom query from client:",y);try{let f=await c.handleCustomQuery({req:{...n,type:"CUSTOM_QUERY",resource:p,procedure:m,input:g,context:await l??{},queryParams:u}});s({id:T,type:"REPLY",data:f});}catch(f){s({id:T,type:"REJECT",resource:p,message:f.message}),t.error("Error handling custom query from the client:",f);}}else if(y.type==="MUTATE"){let{resource:p}=y;t.debug("Received mutation from client:",y);try{let m=await c.handleMutation({req:{...n,type:"MUTATE",resource:p,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:m});}catch(m){s({id:y.id,type:"REJECT",resource:p,message:m.message}),t.error("Error parsing mutation from the client:",m);}}}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 We(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([r,i])=>{i&&t.set(r,Array.isArray(i)?i.join(","):i);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Hr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ue(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(r,i)=>{ze(e)(We(r)).then(o=>o.json().then(a=>i.status(o.status).send(a)));});};var se=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,r,i,s,o,a,n){this._collection=e,this._client=t,this._where=r??{},this._include=i??{},this._limit=s,this._single=o,this._sort=a,this._shouldAwait=n,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 Nt=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),Te=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(r=>Nt(r)?z$2(r):r))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function D(c,e,t){let r=new Te(c),i=o=>{let a=se._init(o,r,true);return Object.assign(Object.create(a),{insert:async u=>{let l=c._getTimestamp(),d=await c.rawInsert(o.name,u.id,{value:Object.fromEntries(Object.entries(u).map(([h,y])=>[h,{value:y,_meta:{timestamp:l}}]))},void 0,t);return z$2(d.data)},update:async(u,l)=>{let d=c._getTimestamp(),{id:h,...y}=l,p=await c.rawUpdate(o.name,u,{value:Object.fromEntries(Object.entries(y).map(([T,f])=>[T,{value:f,_meta:{timestamp:d}}]))},void 0,t),m=z$2(p.data),g={};for(let T of Object.keys(y))T in m&&(g[T]=m[T]);return g}})},s={get(o,a){if(a==="findOne")return c.findOne.bind(c);if(a==="find")return c.find.bind(c);if(a==="insert")return (n,u)=>{let l=c._getTimestamp();return c.rawInsert(n.name,u.id,{value:Object.fromEntries(Object.entries(u).map(([d,h])=>[d,{value:h,_meta:{timestamp:l}}]))},void 0,t).then(d=>z$2(d.data))};if(a==="update")return (n,u,l)=>{let d=c._getTimestamp(),{id:h,...y}=l;return c.rawUpdate(n.name,u,{value:Object.fromEntries(Object.entries(y).map(([p,m])=>[p,{value:m,_meta:{timestamp:d}}]))},void 0,t).then(p=>{let m=z$2(p.data),g={};for(let T of Object.keys(y))T in m&&(g[T]=m[T]);return g})};if(a==="transaction")return async n=>c.transaction(async({trx:u,commit:l,rollback:d})=>{let h=D(u,e,t);return n({trx:h,commit:l,rollback:d})});if(a in e){let n=e[a];return i(n)}}};return new Proxy({},s)}var Re=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)}},tn=c=>Re.create({...c}),Je=(c=>({handler:e=>({_type:"query",inputValidator:c??z$1.undefined(),handler:e})})),Ge=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z$1.undefined(),handler:e})})),be=class c{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,r,i,s){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=r??{},this.authorization=i,this.hooks=s;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:Ge,query:Je}),r={},i={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:i[s]=o;return new c(this.resourceSchema,r,i,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 i={resource:r.resource,where:r.where,include:r.include,lastSyncedAt:r.lastSyncedAt,limit:r.limit,sort:r.sort},s=B$1(i);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 i=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(i),o=D(s,r,e.context);return await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let u=n.procedure==="INSERT"?"insert":n.procedure==="UPDATE"?"update":void 0,l=this.customMutations[n.procedure]?n.procedure:u&&this.customMutations[u]?u:n.procedure,d=this.customMutations[l];if(d){n.procedure=l;let h=d.inputValidator["~standard"].validate(n.input),y=h instanceof Promise?await h:h;if(y.issues){let p=y.issues.map(m=>{var T;let g=(T=m.path)==null?void 0:T.map(f=>typeof f=="object"&&"key"in f?String(f.key):String(f)).join(".");return g?`${g}: ${m.message}`:m.message}).join(", ");throw new Error(`Validation failed: ${p}`)}return n.input=y.value,d.handler({req:n,db:o})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:s,operation:n.procedure,schema:r});throw new Error(`Unknown procedure: ${n.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let i=D(t,r,e.context);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),n=a instanceof Promise?await a:a;if(n.issues){let u=n.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=n.value,o.handler({req:s,db:i})})(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:i})=>{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,p,m,g;if(r==="INSERT"){let{data:T,acceptedValues:f}=await a.rawInsert(e.resource,e.resourceId,o,(l=e.context)==null?void 0:l.messageId,e.context);if(!f)throw new Error("Mutation rejected");let R=z$2(T);if(R.id=R.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let S=C(b,e.resource,i),v=Object.keys(S).length>0?await a.rawFindById(e.resource,e.resourceId,S):T,E=z$2(v);if(E.id=E.id??e.resourceId,!D$1(E,b))throw new Error("Not authorized")}}return {data:T,acceptedValues:f}}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 f=this.authorization.update.preMutation({ctx:e.context,value:T});if(typeof f=="boolean"){if(!f)throw new Error("Not authorized")}else {let R=C(f,e.resource,i),b=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):s,S=z$2(b);if(S.id=S.id??e.resourceId,!D$1(S,f))throw new Error("Not authorized")}}let{data:n,acceptedValues:u}=await a.rawUpdate(e.resource,e.resourceId,o,(p=e.context)==null?void 0:p.messageId,e.context);if(!u)throw new Error("Mutation rejected");if((g=(m=this.authorization)==null?void 0:m.update)!=null&&g.postMutation){let T=z$2(n);T.id=T.id??e.resourceId;let f=this.authorization.update.postMutation({ctx:e.context,value:T});if(typeof f=="boolean"){if(!f)throw new Error("Not authorized")}else {let R=C(f,e.resource,i),b=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):n,S=z$2(b);if(S.id=S.id??e.resourceId,!D$1(S,f))throw new Error("Not authorized")}}return {data:n,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,i)=>s=>i({req:s,next:r}),e)(t)}},Se=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 i=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),s=t._setMutationTimestamp(i),o=D(s,r,e.context);return await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[n.procedure];if(u){let l=u.inputValidator["~standard"].validate(n.input),d=l instanceof Promise?await l:l;if(d.issues){let h=d.issues.map(y=>{var m;let p=(m=y.path)==null?void 0:m.map(g=>typeof g=="object"&&"key"in g?String(g.key):String(g)).join(".");return p?`${p}: ${y.message}`:y.message}).join(", ");throw new Error(`Validation failed: ${h}`)}return n.input=d.value,u.handler({req:n,db:o})}throw new Error(`Unknown procedure: ${n.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let i=D(t,r,e.context);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),n=a instanceof Promise?await a:a;if(n.issues){let u=n.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=n.value,o.handler({req:s,db:i})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,i)=>s=>i({req:s,next:r}),e)(t)}};function rn(c){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:r})=>c({ctx:t.context,req:t,next:i=>(t.context=i,r(t))})}}var we=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new be(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:Ge,query:Je}),r={},i={};for(let[s,o]of Object.entries(t))o._type==="mutation"?r[s]=o:i[s]=o;return new Se(r,i).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}},nn=we.create;var W=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(),i=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(i.data)}async update(e,t,r){let i=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:i}}]))}),n=z$2(a.data),u={};for(let l of Object.keys(o))l in n&&(u[l]=n[l]);return u}};var Bt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function k(c){var i,s,o;let e=(i=c.getExecutor)==null?void 0:i.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 Ze(c){let e=k(c);return Bt[e]}var Ft="42701";function K(c){var t;if(c.code===Ft)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 ve(c,e){let{type:t,enumValues:r,enumName:i}=c;if(r&&r.length>0)return e==="postgres"&&i?i:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Ht(c,e,t,r){if(t!=="postgres")return;let i=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&&i.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let s of Array.from(i.values())){let{name:o,values:a}=s;try{let n=a.map(u=>`'${u}'`).join(", ");await sql`
|
|
1
|
+
import {a,b,B as B$1,z as z$1,C,D as D$1,G,F as F$1,E}from'./chunk-3XEJ2M4E.js';import Z from'crypto';import At,{parse}from'qs';import {z}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 fe=a(re=>{Object.defineProperty(re,"__esModule",{value:true});re.parse=vt;re.serialize=It;var Tt=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Rt=/^[\u0021-\u003A\u003C-\u007E]*$/,bt=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,St=/^[\u0020-\u003A\u003D-\u007E]*$/,wt=Object.prototype.toString,xt=(()=>{let c=function(){};return c.prototype=Object.create(null),c})();function vt(c,e){let t=new xt,r=c.length;if(r<2)return t;let s=(e==null?void 0:e.decode)||Mt,i=0;do{let o=c.indexOf("=",i);if(o===-1)break;let a=c.indexOf(";",i),n=a===-1?r:a;if(o>n){i=c.lastIndexOf(";",o-1)+1;continue}let u=_e(c,i,o),l=De(c,o,u),d=c.slice(u,l);if(t[d]===void 0){let y=_e(c,o+1,n),h=De(c,n,y),f=s(c.slice(y,h));t[d]=f;}i=n+1;}while(i<r);return t}function _e(c,e,t){do{let r=c.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function De(c,e,t){for(;e>t;){let r=c.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function It(c,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!Tt.test(c))throw new TypeError(`argument name is invalid: ${c}`);let s=r(e);if(!Rt.test(s))throw new TypeError(`argument val is invalid: ${e}`);let i=c+"="+s;if(!t)return i;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);i+="; Max-Age="+t.maxAge;}if(t.domain){if(!bt.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);i+="; Domain="+t.domain;}if(t.path){if(!St.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);i+="; Path="+t.path;}if(t.expires){if(!Ct(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);i+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(i+="; HttpOnly"),t.secure&&(i+="; Secure"),t.partitioned&&(i+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":i+="; Priority=Low";break;case "medium":i+="; Priority=Medium";break;case "high":i+="; 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":i+="; SameSite=Strict";break;case "lax":i+="; SameSite=Lax";break;case "none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return i}function Mt(c){if(c.indexOf("%")===-1)return c;try{return decodeURIComponent(c)}catch{return c}}function Ct(c){return wt.call(c)==="[object Date]"}});var Ne="0123456789ABCDEFGHJKMNPQRSTVWXYZ",H=32;var ct=16,$e=10,Qe=0xffffffffffff;var _;(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";})(_||(_={}));var D=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function ut(c){let e=Math.floor(c()*H);return e===H&&(e=H-1),Ne.charAt(e)}function dt(c){var r;let e=lt(),t=e&&(e.crypto||e.msCrypto)||(typeof Z<"u"?Z:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let s=new Uint8Array(1);return t.getRandomValues(s),s[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=Z)!=null&&r.randomBytes)return ()=>Z.randomBytes(1).readUInt8()/255;throw new D(_.PRNGDetectFailure,"Failed to find a reliable PRNG")}function lt(){return mt()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function yt(c,e){let t="";for(;c>0;c--)t=ut(e)+t;return t}function ht(c,e=$e){if(isNaN(c))throw new D(_.EncodeTimeValueMalformed,`Time must be a number: ${c}`);if(c>Qe)throw new D(_.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Qe}: ${c}`);if(c<0)throw new D(_.EncodeTimeNegative,`Time must be positive: ${c}`);if(Number.isInteger(c)===false)throw new D(_.EncodeTimeValueMalformed,`Time must be an integer: ${c}`);let t,r="";for(let s=e;s>0;s--)t=c%H,r=Ne.charAt(t)+r,c=(c-t)/H;return r}function mt(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function qe(c,e){let t=dt(),r=Date.now();return ht(r,$e)+yt(ct,t)}var X=()=>qe().toLowerCase(),Y=c=>({then(e,t){try{if(e){let r=e(c);return r instanceof Promise?r:Y(r)}return Y(c)}catch(r){if(t){let s=t(r);return s instanceof Promise?s:Y(s)}throw r}}}),he=c=>c instanceof Promise?c:Y(c);var B=(...c)=>{let e=c.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var ee=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...s}){return new Promise((i,o)=>{let a=this.getBatchKey({resource:e,commonWhere:t,...s}),n={resource:e,commonWhere:t,uniqueWhere:r,...s,resolve:i,reject:o};this.queue.has(a)||this.queue.set(a,[]);let u=this.queue.get(a);u&&u.push(n),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...s}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(s??{})}`}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(s=>{s.reject(r);});}}async executeBatchedRequests(e){var y;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:s,include:i,sort:o}=t,a=e.length===1?t.limit:void 0,n=e.map(h=>h.uniqueWhere).filter(h=>h!==void 0),u=s,l=(y=Object.entries(n[0]??{})[0])==null?void 0:y[0];if(n.length>0){let h=n.map(f=>f[l]).filter(f=>f!=null);h.length>0&&(u=B(s,{[l]:{$in:h}}));}let d=await this.storage.get({resource:r,where:u,include:i,sort:o,limit:a});for(let h of e){let f=d;if(h.uniqueWhere){let[p,m]=Object.entries(h.uniqueWhere)[0];f=d.filter(T=>{var g;return ((g=T.value[p])==null?void 0:g.value)===m});}h.resolve(f);}}};function me(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 te=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[s,i]of Object.entries(r.relations))i.type==="one"&&i.relationalColumn&&t.set(String(i.relationalColumn),{relationName:s,targetResource:i.entity.name});return t}ensureObjectNode(e,t,r){let s=this.objectNodes.get(e);return s?r&&s.matchedQueries.add(r):(s={id:e,type:t,matchedQueries:new Set(r?[r]:[]),referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e,s)),s}storeRelation(e,t,r,s){let i=this.objectNodes.get(e),o=this.objectNodes.get(t);if(i&&i.referencesObjects.set(r,t),o&&s){let a=o.referencedByObjects.get(s);a||(a=new Set,o.referencedByObjects.set(s,a)),a.add(e);}}removeRelation(e,t,r,s){let i=this.objectNodes.get(e),o=this.objectNodes.get(t);if(i&&i.referencesObjects.delete(r),o&&s){let a=o.referencedByObjects.get(s);a&&(a.delete(e),a.size===0&&o.referencedByObjects.delete(s));}}getInverseRelationName(e,t,r){let s=this.schema[e];if(!(s!=null&&s.relations))return;let i=s.relations[r];if(!i)return;let o=this.schema[t];if(o!=null&&o.relations){if(i.type==="many"&&i.foreignColumn){for(let[a,n]of Object.entries(o.relations))if(n.entity.name===e&&n.type==="one"&&n.relationalColumn===i.foreignColumn)return a}if(i.type==="one"&&i.relationalColumn){for(let[a,n]of Object.entries(o.relations))if(n.entity.name===e&&n.type==="many"&&n.foreignColumn===i.relationalColumn)return a}}}updateRelationsFromMutation(e,t,r,s){let i=this.getRelationalColumns(e),o=this.objectNodes.get(t);if(o)for(let[a,{relationName:n,targetResource:u}]of Array.from(i)){if(!(s&&a in s))continue;let d=this.getInverseRelationName(e,u,n),y=o.referencesObjects.get(n),h=r[a];y!==h&&(y&&this.removeRelation(t,y,n,d),h&&(this.ensureObjectNode(h,u),this.storeRelation(t,h,n,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 ee(this.storage)})}subscribe(e,t,r={}){let s=this.breakdownQuery({query:e,context:r}),i={},o=[];for(let a of s){this.logger.debug("[QueryEngine] Subscribing to step",a.stepPath.join("."));let n=me(a),u=i[a.stepPath.at(-2)??""],l=a.stepPath.at(-1)??"",d=this.queryNodes.get(n);if(d)d.subscriptions.add(t);else if(d={hash:n,queryStep:a,relationName:l,trackedObjects:new Set,subscriptions:new Set([t]),parentQuery:u,childQueries:new Set},this.queryNodes.set(d.hash,d),u){let y=this.queryNodes.get(u);y&&y.childQueries.add(d.hash);}i[l]=n,o.push(()=>{let y=this.queryNodes.get(n);y&&(y.subscriptions.delete(t),y.subscriptions.size===0&&this.queryNodes.delete(n));});}return ()=>{for(let a of o)a();}}breakdownQuery(e){var m;let{query:t,stepPath:r=[],context:s={},parentResource:i}=e,{include:o}=t,a=r.length===0,n=r.at(-1),u,l,d;if(!a&&i&&n){let T=this.schema[i],g=(m=T==null?void 0:T.relations)==null?void 0:m[n];g&&(d=g.type==="many",g.type==="one"?(u=R=>({id:R}),l=R=>R.map(b=>{var S,x;return (x=(S=b.value)==null?void 0:S[g.relationalColumn])==null?void 0:x.value}).filter(b=>b!==void 0)):(u=R=>({[g.foreignColumn]:R}),l=R=>R.map(b=>{var S,x;return (x=(S=b.value)==null?void 0:S.id)==null?void 0:x.value}).filter(b=>b!==void 0)));}let{include:y,...h}=t,p=[this.router.incrementQueryStep({query:h,stepPath:[...r],getWhere:u,referenceGetter:l,isMany:d,relationName:n},s)];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 b=T.relations[g];if(!b)throw new Error(`Relation ${g} not found for resource ${t.resource}`);let S=b.entity.name,x=E(R)?R:null;return this.breakdownQuery({query:{resource:S,include:x?x.include:typeof R=="object"?R:void 0,where:x==null?void 0:x.where,limit:x==null?void 0:x.limit,sort:x==null?void 0:x.orderBy},stepPath:[...r,g],context:s,parentResource:t.resource})}));}return p}resolveQuery(e,t){this.logger.debug("[QueryEngine] Resolving query",e.map(i=>i.stepPath.join(".")).join(" -> "));let r={},s=this.resolveStep(e[0],t).then(i=>{this.logger.debug("[QueryEngine] Resolved step",e[0].stepPath.join("."),"with results count:",i.length),r[e[0].stepPath.join(".")]=[{data:i}];});for(let i=1;i<e.length;i++){let o=e[i],a=o.stepPath.slice(0,-1).join(".");s=s.then(async()=>{var u,l;let n=r[a];if(!n){r[o.stepPath.join(".")]=[];return}if(o.referenceGetter&&o.getWhere){let d=new Map;for(let f of n)for(let p of f.data){let m=(l=(u=p==null?void 0:p.value)==null?void 0:u.id)==null?void 0:l.value;if(!m)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(m);}}let y=Array.from(d.keys());if(y.length===0){r[o.stepPath.join(".")]=[];return}let h=[];for(let f of y){let p=o.getWhere(f),m={...o,relationalWhere:p},T=await this.resolveStep(m,t),g=d.get(f);if(g)for(let R of Array.from(g))h.push({includedBy:R,data:T});}this.logger.debug("[QueryEngine] Resolved step",o.stepPath.join("."),"with results count:",h.reduce((f,p)=>f+p.data.length,0)),r[o.stepPath.join(".")]=h;}else {let d=await this.resolveStep(o,t);r[o.stepPath.join(".")]=[{data:d}];}});}return s=s.then((()=>(this.logger.debug("[QueryEngine] Assembling results"),this.assembleResults(e,r)))),s}assembleResults(e,t){var o,a,n,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 y=d.stepPath.join("."),h=t[y]??[],f=Object.keys(d.query.include??{});this.logger.debug(`[QueryEngine] assembleResults: Processing step "${y}"`,{resource:d.query.resource,includedRelations:f,resultGroups:h.length,isMany:d.isMany,relationName:d.relationName});for(let p of h){this.logger.debug(`[QueryEngine] assembleResults: Processing result group for "${y}"`,{dataCount:p.data.length,includedBy:p.includedBy});for(let m of p.data){let T=(a=(o=m==null?void 0:m.value)==null?void 0:o.id)==null?void 0:a.value;if(!T){this.logger.debug(`[QueryEngine] assembleResults: Skipping data without id in step "${y}"`);continue}let g=y?`${y}.${T}`:T,R=[];if(d.stepPath.length>0&&p.includedBy){let S=d.stepPath.slice(0,-1).join(".");R=[S?`${S}.${p.includedBy}`:p.includedBy],this.logger.debug(`[QueryEngine] assembleResults: Child entity "${g}" has parent keys:`,R,{stepPath:y,parentStepPath:S,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:`,R);for(let S of R)b.includedBy.add(S);}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:f,parentKeys:R}),r.set(g,{data:m,includedBy:new Set(R),path:d.stepPath.at(-1)??"",isMany:d.isMany??false,relationName:d.relationName,resourceName:d.query.resource,includedRelations:f});}}}this.logger.debug(`[QueryEngine] assembleResults: Built entriesMap with ${r.size} entries`),this.logger.debug("[QueryEngine] assembleResults: EntriesMap keys:",Array.from(r.keys()));let s=Array.from(r.entries()),i=[];this.logger.debug(`[QueryEngine] assembleResults: Starting assembly phase with ${s.length} entries`);for(let d=s.length-1;d>=0;d--){let[y,h]=s[d],f=this.schema[h.resourceName];this.logger.debug(`[QueryEngine] assembleResults: Processing entry "${y}"`,{resource:h.resourceName,path:h.path,isMany:h.isMany,relationName:h.relationName,includedRelations:h.includedRelations,parentKeys:Array.from(h.includedBy)});for(let p of h.includedRelations){let m=(u=(n=f==null?void 0:f.relations)==null?void 0:n[p])==null?void 0:u.type,T=!!h.data.value[p];if(this.logger.debug(`[QueryEngine] assembleResults: Checking included relation "${p}" for "${y}"`,{relationType:m,hasRelation:T,resourceHasRelation:!!((l=f==null?void 0:f.relations)!=null&&l[p])}),h.data.value[p])this.logger.debug(`[QueryEngine] assembleResults: Relation "${p}" already exists for "${y}"`,h.data.value[p]);else {let g=m==="many"?{value:[]}:{value:null};h.data.value[p]=g,this.logger.debug(`[QueryEngine] assembleResults: Initialized relation "${p}" for "${y}" with`,g);}}if(h.path===""){this.logger.debug(`[QueryEngine] assembleResults: Adding root entity "${y}" to resultData`),i.unshift(h.data);continue}this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to ${h.includedBy.size} parent(s)`);for(let p of Array.from(h.includedBy)){let m=r.get(p);if(!m){this.logger.warn(`[QueryEngine] assembleResults: WARNING - Parent "${p}" not found in entriesMap for child "${y}"`);continue}let T=h.relationName??h.path;this.logger.debug(`[QueryEngine] assembleResults: Attaching "${y}" to parent "${p}" via relation "${T}"`,{isMany:h.isMany,parentHasRelation:!!m.data.value[T]}),h.isMany?(m.data.value[T]??={value:[]},m.data.value[T].value.push(h.data),this.logger.debug(`[QueryEngine] assembleResults: Added "${y}" to many relation "${T}" on parent "${p}"`,{arrayLength:m.data.value[T].value.length})):(m.data.value[T]=h.data,this.logger.debug(`[QueryEngine] assembleResults: Set one relation "${T}" on parent "${p}" to "${y}"`));}}return this.logger.debug(`[QueryEngine] assembleResults: Assembly complete. Returning ${i.length} root items`),i}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:s}=e,i=r.where&&s?B(r.where,s):s??r.where,o=i?{...r,where:i}:r;return he(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=me(e),s=this.queryNodes.get(r),i=e.query.resource;if(!s)return;let o=this.getRelationalColumns(i);for(let a of t){let n=z$1(a),u=n.id;this.ensureObjectNode(u,i,r),s.trackedObjects.add(u);for(let[l,{relationName:d,targetResource:y}]of Array.from(o)){let h=n[l];if(h){this.ensureObjectNode(h,y);let f=this.getInverseRelationName(i,y,d);this.storeRelation(u,h,d,f);}}this.loadNestedRelations(i,u,n),this.logger.debug("[QueryEngine] Loaded nested relations for",u);}}loadNestedRelations(e,t,r){let s=this.schema[e];if(s!=null&&s.relations)for(let[i,o]of Object.entries(s.relations)){let a=r[i];if(!a)continue;let n=o.entity.name,u=this.getInverseRelationName(e,n,i);if(o.type==="one")a&&typeof a=="object"&&a.id&&(this.ensureObjectNode(a.id,n),this.storeRelation(t,a.id,i,u),this.loadNestedRelations(n,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,n);let d=this.getInverseRelationName(n,e,i);d&&this.storeRelation(l.id,t,d,i),this.loadNestedRelations(n,l.id,l);}}}}buildIncludeFromChildQueries(e){let t=this.queryNodes.get(e);if(!t||t.childQueries.size===0)return {};let r={};for(let s of Array.from(t.childQueries)){let i=this.queryNodes.get(s);if(!i||!i.relationName)continue;let o=this.buildIncludeFromChildQueries(s);r[i.relationName]=Object.keys(o).length>0?o:true;}return r}sendInsertsForTree(e,t,r){var a,n;let s=(n=(a=t==null?void 0:t.value)==null?void 0:a.id)==null?void 0:n.value;if(!s)return;let i={procedure:"INSERT",resource:r,resourceId:s,type:"MUTATE",payload:t.value};for(let u of Array.from(e.subscriptions))try{u(i);}catch(l){this.logger.error("[QueryEngine] Error in subscription callback during sendInsertsForTree",{error:l,queryHash:e.hash,resource:r,resourceId:s,stepPath:e.queryStep.stepPath.join(".")});}e.trackedObjects.add(s),this.ensureObjectNode(s,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,y=l.queryStep.query.resource,h=t.value[d];if(!h)continue;let f=h.value;if(Array.isArray(f))for(let p of f)this.sendInsertsForTree(l,p,y);else f&&typeof f=="object"&&this.sendInsertsForTree(l,f,y);}}handleMutation(e,t){if(e.procedure==="INSERT"){if(this.objectNodes.has(e.resourceId))return;let r=z$1(t);if(!r)return;let s={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map};this.objectNodes.set(e.resourceId,s);let i=this.getRelationalColumns(e.resource);for(let[a,{relationName:n,targetResource:u}]of Array.from(i)){let l=r[a];if(l){this.ensureObjectNode(l,u);let d=this.getInverseRelationName(e.resource,u,n);this.storeRelation(e.resourceId,l,n,d);}}let o=this.objectNodes.get(e.resourceId);this.getMatchingQueries(e,r).then(a=>{for(let n of a){let u=this.queryNodes.get(n);if(u){u.trackedObjects.add(e.resourceId),o&&o.matchedQueries.add(n);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$1(t);if(!r)return;let s=this.objectNodes.get(e.resourceId),i=new Set((s==null?void 0:s.matchedQueries)??[]);s||(s={id:e.resourceId,type:e.resource,matchedQueries:new Set,referencesObjects:new Map,referencedByObjects:new Map},this.objectNodes.set(e.resourceId,s)),this.updateRelationsFromMutation(e.resource,e.resourceId,r,e.payload),this.getMatchingQueries(e,r).then(o=>{let a=new Set(o),n=[],u=[],l=[];for(let y of o)i.has(y)?l.push(y):n.push(y);for(let y of Array.from(i))a.has(y)||u.push(y);for(let y of n){let h=this.queryNodes.get(y);h&&h.trackedObjects.add(e.resourceId);}for(let y of u){let h=this.queryNodes.get(y);h&&h.trackedObjects.delete(e.resourceId);}let d=this.objectNodes.get(e.resourceId);if(d){for(let y of n)d.matchedQueries.add(y);for(let y of u)d.matchedQueries.delete(y);}for(let y of [...u,...l]){let h=this.queryNodes.get(y);if(h)for(let f of Array.from(h.subscriptions))try{f(e);}catch(p){this.logger.error("[QueryEngine] Error in subscription callback during UPDATE mutation",{error:p,queryHash:h.hash,resource:e.resource,resourceId:e.resourceId,stepPath:h.queryStep.stepPath.join(".")});}}if(n.length>0)for(let y of n){let h=this.queryNodes.get(y);if(!h)continue;let f=this.buildIncludeFromChildQueries(y);this.get({resource:e.resource,where:{id:e.resourceId},include:Object.keys(f).length>0?f:void 0}).then(p=>{!p||p.length===0||this.sendInsertsForTree(h,p[0],e.resource);});}});return}}getMatchingQueries(e,t){let r=[];for(let s of Array.from(this.queryNodes.values()))s.queryStep.query.resource===e.resource&&r.push(s);return r.length===0?he([]):Promise.all(r.map(async s=>{let i=s.queryStep.query.where,o=s.queryStep.query.resource,a=e.resourceId,n=this.objectNodes.get(a);if(!n)return {hash:s.hash,matches:false};if(s.relationName){let h=s.parentQuery?this.queryNodes.get(s.parentQuery):void 0,f=h==null?void 0:h.queryStep.query.resource,p=f?this.getInverseRelationName(f,o,s.relationName):void 0,m=p?n.referencesObjects.get(p):void 0;if(!m)return {hash:s.hash,matches:false};let T=this.objectNodes.get(m);return !T||!h||!T.matchedQueries.has(h.hash)?{hash:s.hash,matches:false}:{hash:s.hash,matches:true}}if(!i)return {hash:s.hash,matches:true};let u=C(i,o,this.schema),l=Object.keys(u).length>0;if(!l&&t!==void 0)return {hash:s.hash,matches:D$1(t,i)};let d=await this.storage.get({resource:o,where:{id:a},include:l?u:void 0});if(!d||d.length===0)return {hash:s.hash,matches:false};let y=z$1(d[0]);return y?{hash:s.hash,matches:D$1(y,i)}:{hash:s.hash,matches:false}})).then(s=>s.filter(i=>i.matches).map(i=>i.hash))}};var Sr=c=>c,pt=["beforeInsert","afterInsert","beforeUpdate","afterUpdate"],ft=c=>c.length===1?c[0]:(async e=>{let t=e.rawValue,r=e.value,s=false;for(let i of c){let o=await i({...e,value:r,rawValue:t});o&&(t=o,r=z$1(t),r.id=e.value.id,s=true);}return s?t:void 0}),gt=c=>c.length===1?c[0]:(async e=>{for(let t of c)await t(e);}),pe=c=>{let e=c.filter(r=>r!=null);if(e.length===0)return;if(e.length===1)return e[0];let t={};for(let r of pt){let s=e.map(i=>i[r]).filter(i=>i!=null);s.length!==0&&(r==="afterInsert"||r==="afterUpdate"?t[r]=gt(s):t[r]=ft(s));}return t},wr=(...c)=>{let e={},t=new Set;for(let r of c)for(let s of Object.keys(r))t.add(s);for(let r of Array.from(t)){let s=c.map(o=>o[r]),i=pe(s);i&&(e[r]=i);}return e};var He=b(fe(),1);var ne=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.coerce.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),ge=z.record(z.string(),z.object({value:z.any().nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})),jt=ge.superRefine((c,e)=>{c.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Ve=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),ze=z.object({timestamp:z.string().optional(),originMutationId:z.string().optional()}).optional(),F=Ve.extend({procedure:z.string(),payload:z.any().optional(),meta:ze}),U=Ve.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:jt,meta:ze});z.union([U,F]);var Be=z.object({resource:z.string(),procedure:z.string(),input:z.any().optional()});var Fe=ne.omit({resource:true}),se=F.omit({id:true,type:true,resource:true,procedure:true}).extend({meta:F.shape.meta}),Te=U.omit({id:true,type:true,resource:true,procedure:true});z.union([Te,se]);var Re=c=>{if(c==null)return c;if(c==="null")return null;if(Array.isArray(c))return c.map(Re);if(typeof c=="object"&&c.constructor===Object){let e={};for(let[t,r]of Object.entries(c))e[t]=Re(r);return e}return c},Ue=c=>{let e=c.logger;return async t=>{var r,s,i,o,a,n;try{let u=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,l={headers:u,cookies:u.cookie?He.default.parse(u.cookie):{}},d=new URL(t.url),y=d.pathname.split("/"),h=d.searchParams,f=Re(At.parse(h.toString())),p=await((r=c.contextProvider)==null?void 0:r.call(c,{transport:"HTTP",headers:l.headers,cookies:l.cookies,queryParams:f}))??{};if(t.method==="GET"){let m=y[y.length-1],{success:T,data:g,error:R}=Fe.safeParse(f);if(!T)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:R},{status:400});let b=await c.handleQuery({req:{...l,...g,type:"QUERY",resource:m,context:p,queryParams:f}});return !b||!b.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(b.data)}if(t.method==="POST")try{let m=y[y.length-1],T=y[y.length-2];if(T==="query"){if(y.length<3)return Response.json({message:"Invalid path structure for custom query",code:"INVALID_PATH"},{status:400});let E=y[y.length-3],C=t.body?await t.json():{};if(!E||E.trim()==="")return Response.json({message:"Invalid resource in path",code:"INVALID_RESOURCE"},{status:400});let v=await c.handleCustomQuery({req:{...l,type:"CUSTOM_QUERY",resource:E,procedure:m,input:C.input,context:p,queryParams:f}});return Response.json(v)}let g=T,R=t.body?await t.json():{},b,S=m,x,A;if(m==="insert"||m==="update"){let E=Te.safeParse(R);if(S=m.toUpperCase(),E.success)b=E.data;else {if(!(typeof R=="object"&&R!==null&&"payload"in R&&"meta"in R))return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:E.error},{status:400});let v=se.safeParse(R);if(!v.success)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:v.error},{status:400});b=v.data;let j=(i=(s=c.router)==null?void 0:s.routes)==null?void 0:i[g],O=m==="insert"?"insert":"update";if(!!!((o=j==null?void 0:j.customMutations)!=null&&o[O])){let de=b.payload??{},{id:le,...Ee}=de;if(m==="update"&&typeof le!="string")return Response.json({message:"Invalid mutation: payload.id is required for update",code:"INVALID_REQUEST"},{status:400});x=typeof le=="string"?le:void 0;let ye=(a=c.schema)==null?void 0:a[g];if(ye&&typeof ye.encodeMutation=="function"){let at=((n=b.meta)==null?void 0:n.timestamp)??new Date().toISOString();A=ye.encodeMutation("set",Ee,at);}else A=Ee;}}}else {let{success:E,data:C,error:v}=se.safeParse(R);if(!E)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:v},{status:400});b=C;}let k=await c.handleMutation({req:{...l,type:"MUTATE",resource:g,input:A??b.payload,context:p,resourceId:x??b.resourceId,procedure:S,queryParams:{},meta:b.meta}});return Response.json(k)}catch(m){return e.error("Error parsing mutation from the client:",m),m instanceof Error&&m.message.includes("Unknown procedure")?Response.json({message:m.message,code:"UNKNOWN_PROCEDURE"},{status:400}):Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(u){return e.error("Unexpected error:",u),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var Je=b(fe(),1);var $=z.string(),be=z.union([Be,ne]),Et=z.object({id:$,type:z.literal("SUBSCRIBE")}).and(be),Pt=z.object({id:$,type:z.literal("UNSUBSCRIBE")}).and(be),Lt=z.object({id:$,type:z.literal("QUERY")}).and(be),kt=z.object({id:$,type:z.literal("CUSTOM_QUERY"),resource:z.string(),procedure:z.string(),input:z.any().optional()}),We=U.extend({id:$}),Qt=F.extend({id:$}),Nt=z.union([Qt,We]),Ke=z.union([Et,Lt,kt,Nt,Pt]),$t=z.object({id:$,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),qt=z.object({id:$,type:z.literal("REPLY"),data:z.any()});z.union([$t,qt,We]);z.object({resource:z.string(),data:z.array(ge)});var Ge=c=>{let e={},t=c.logger;return (r,s)=>{var d;let i=y=>{r.send(JSON.stringify(y));},o=X(),a=new Map,n={headers:s.headers,cookies:typeof s.headers.cookie=="string"?Je.default.parse(s.headers.cookie):{}},u=parse(s.url.split("?")[1]),l=(d=c.contextProvider)==null?void 0:d.call(c,{transport:"WEBSOCKET",headers:n.headers,cookies:n.cookies,queryParams:u});e[o]=r,t.info("Client connected:",o),r.on("message",async y=>{try{t.debug("Message received from the client:",y);let h=Ke.parse(JSON.parse(y.toString()));if(h.type==="SUBSCRIBE"||h.type==="QUERY"){let{type:f,id:p,...m}=h,T=f==="SUBSCRIBE";if("procedure"in m){let g=await c.handleCustomQuery({req:{...n,type:"CUSTOM_QUERY",resource:m.resource,procedure:m.procedure,input:m.input,context:await l??{},queryParams:u},subscription:T?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[o])==null||b.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(m),g.unsubscribe),i({id:p,type:"REPLY",data:{resource:g.query.resource,data:(g.data??[]).map(R=>R.value)}});}else i({id:p,type:"REPLY",data:g});}else {let g=await c.handleQuery({req:{...n,...m,type:"QUERY",context:await l??{},queryParams:u},subscription:T?R=>{var b;!R.resourceId||!R.payload||!Object.keys(R.payload).length||(b=e[o])==null||b.send(JSON.stringify(R));}:void 0});if(!g||!g.data)throw new Error("Invalid resource");T&&g.unsubscribe&&a.set(B$1(m),g.unsubscribe),i({id:p,type:"REPLY",data:{resource:m.resource,data:(g.data??[]).map(R=>R.value)}});}}else if(h.type==="UNSUBSCRIBE"){let{type:f,id:p,...m}=h,T=a.get(B$1(m));T&&(T(),a.delete(B$1(m)));}else if(h.type==="CUSTOM_QUERY"){let{resource:f,procedure:p,input:m,id:T}=h;t.debug("Received custom query from client:",h);try{let g=await c.handleCustomQuery({req:{...n,type:"CUSTOM_QUERY",resource:f,procedure:p,input:m,context:await l??{},queryParams:u}});i({id:T,type:"REPLY",data:g});}catch(g){i({id:T,type:"REJECT",resource:f,message:g.message}),t.error("Error handling custom query from the client:",g);}}else if(h.type==="MUTATE"){let{resource:f}=h;t.debug("Received mutation from client:",h);try{let p=await c.handleMutation({req:{...n,type:"MUTATE",resource:f,input:h.payload,context:{messageId:h.id,...await l??{}},resourceId:h.resourceId,procedure:h.procedure,queryParams:u,meta:h.meta}});h.procedure&&h.procedure!=="INSERT"&&h.procedure!=="UPDATE"&&i({id:h.id,type:"REPLY",data:p});}catch(p){i({id:h.id,type:"REJECT",resource:f,message:p.message}),t.error("Error parsing mutation from the client:",p);}}}catch(h){t.error("Error handling message from the client:",h);}}),r.on("close",()=>{t.info("Connection closed",o),delete e[o];for(let y of Array.from(a.values()))y();});}};function Ze(c){let e=`${c.protocol}://${c.hostname}${c.url}`,t=new Headers;return Object.entries(c.headers).forEach(([r,s])=>{s&&t.set(r,Array.isArray(s)?s.join(","):s);}),new Request(e,{method:c.method,headers:t,body:c.body&&c.method!=="GET"?JSON.stringify(c.body):void 0})}var Jr=(c,e,t)=>{c.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Ge(e)),c.use(`${(t==null?void 0:t.basePath)??""}/`,(r,s)=>{Ue(e)(Ze(r)).then(o=>o.json().then(a=>s.status(o.status).send(a)));});};var ie=class c{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,t,r,s,i,o,a,n){this._collection=e,this._client=t,this._where=r??{},this._include=s??{},this._limit=i,this._single=o,this._sort=a,this._shouldAwait=n,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 Dt=c=>typeof c=="object"&&c!==null&&"value"in c&&!Array.isArray(c),Se=class{constructor(e){this.storage=e;}get(e){return Promise.resolve(this.storage.get(e)).then(t=>t.map(r=>Dt(r)?z$1(r):r))}subscribe(){throw new Error("Subscriptions are not supported server-side. Use .get() instead.")}};function V(c,e,t){let r=new Se(c),s=o=>{let a=ie._init(o,r,true);return Object.assign(Object.create(a),{insert:async u=>{let l=c._getTimestamp(),d=await c.rawInsert(o.name,u.id,{value:Object.fromEntries(Object.entries(u).map(([y,h])=>[y,{value:h,_meta:{timestamp:l}}]))},void 0,t);return z$1(d.data)},update:async(u,l)=>{let d=c._getTimestamp(),{id:y,...h}=l,f=await c.rawUpdate(o.name,u,{value:Object.fromEntries(Object.entries(h).map(([T,g])=>[T,{value:g,_meta:{timestamp:d}}]))},void 0,t),p=z$1(f.data),m={};for(let T of Object.keys(h))T in p&&(m[T]=p[T]);return m}})},i={get(o,a){if(a==="findOne")return c.findOne.bind(c);if(a==="find")return c.find.bind(c);if(a==="insert")return (n,u)=>{let l=c._getTimestamp();return c.rawInsert(n.name,u.id,{value:Object.fromEntries(Object.entries(u).map(([d,y])=>[d,{value:y,_meta:{timestamp:l}}]))},void 0,t).then(d=>z$1(d.data))};if(a==="update")return (n,u,l)=>{let d=c._getTimestamp(),{id:y,...h}=l;return c.rawUpdate(n.name,u,{value:Object.fromEntries(Object.entries(h).map(([f,p])=>[f,{value:p,_meta:{timestamp:d}}]))},void 0,t).then(f=>{let p=z$1(f.data),m={};for(let T of Object.keys(h))T in p&&(m[T]=p[T]);return m})};if(a==="transaction")return async n=>c.transaction(async({trx:u,commit:l,rollback:d})=>{let y=V(u,e,t);return n({trx:y,commit:l,rollback:d})});if(a in e){let n=e[a];return s(n)}}};return new Proxy({},i)}var we=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)}},an=c=>we.create({...c}),Xe=(c=>({handler:e=>({_type:"query",inputValidator:c??z.undefined(),handler:e})})),et=(c=>({handler:e=>({_type:"mutation",inputValidator:c??z.undefined(),handler:e})})),xe=class c{resourceSchema;middlewares;customMutations;customQueries;authorization;hooks;constructor(e,t,r,s,i){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.customQueries=r??{},this.authorization=s,this.hooks=i;}use(...e){for(let t of e)this.middlewares.add(t);return this}withProcedures(e){let t=e({mutation:et,query:Xe}),r={},s={};for(let[i,o]of Object.entries(t))o._type==="mutation"?r[i]=o:s[i]=o;return new c(this.resourceSchema,r,s,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 s={resource:r.resource,where:r.where,include:r.include,lastSyncedAt:r.lastSyncedAt,limit:r.limit,sort:r.sort},i=B$1(s);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:i}})(e);handleMutation=async({req:e,db:t,schema:r})=>{var a;let s=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),i=t._setMutationTimestamp(s),o=V(i,r,e.context);return await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let u=n.procedure==="INSERT"?"insert":n.procedure==="UPDATE"?"update":void 0,l=this.customMutations[n.procedure]?n.procedure:u&&this.customMutations[u]?u:n.procedure,d=this.customMutations[l];if(d){n.procedure=l;let y=d.inputValidator["~standard"].validate(n.input),h=y instanceof Promise?await y:y;if(h.issues){let f=h.issues.map(p=>{var T;let m=(T=p.path)==null?void 0:T.map(g=>typeof g=="object"&&"key"in g?String(g.key):String(g)).join(".");return m?`${m}: ${p.message}`:p.message}).join(", ");throw new Error(`Validation failed: ${f}`)}return n.input=h.value,d.handler({req:n,db:o})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:i,operation:n.procedure,schema:r});throw new Error(`Unknown procedure: ${n.procedure}`)}})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let s=V(t,r,e.context);return await this.wrapInMiddlewares(async i=>{let o=this.customQueries[i.procedure];if(!o)throw new Error(`Unknown query procedure: ${i.procedure}`);let a=o.inputValidator["~standard"].validate(i.input),n=a instanceof Promise?await a:a;if(n.issues){let u=n.issues.map(l=>{var y;let d=(y=l.path)==null?void 0:y.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return i.input=n.value,o.handler({req:i,db:s})})(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:s})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let i=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&i)throw new Error("Resource already exists");if(r==="UPDATE"&&!i)throw new Error("Resource not found");let o={value:e.input};return t.transaction(async({trx:a})=>{var l,d,y,h,f,p,m;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$1(T);if(R.id=R.id??e.resourceId,(d=this.authorization)!=null&&d.insert){let b=this.authorization.insert({ctx:e.context,value:R});if(typeof b=="boolean"){if(!b)throw new Error("Not authorized")}else {let S=C(b,e.resource,s),x=Object.keys(S).length>0?await a.rawFindById(e.resource,e.resourceId,S):T,A=z$1(x);if(A.id=A.id??e.resourceId,!D$1(A,b))throw new Error("Not authorized")}}return {data:T,acceptedValues:g}}if((h=(y=this.authorization)==null?void 0:y.update)!=null&&h.preMutation){let T=z$1(i);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,s),b=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):i,S=z$1(b);if(S.id=S.id??e.resourceId,!D$1(S,g))throw new Error("Not authorized")}}let{data:n,acceptedValues:u}=await a.rawUpdate(e.resource,e.resourceId,o,(f=e.context)==null?void 0:f.messageId,e.context);if(!u)throw new Error("Mutation rejected");if((m=(p=this.authorization)==null?void 0:p.update)!=null&&m.postMutation){let T=z$1(n);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,s),b=Object.keys(R).length>0?await a.rawFindById(e.resource,e.resourceId,R):n,S=z$1(b);if(S.id=S.id??e.resourceId,!D$1(S,g))throw new Error("Not authorized")}}return {data:n,acceptedValues:u}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,s)=>i=>s({req:i,next:r}),e)(t)}},ve=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 s=((a=e.meta)==null?void 0:a.timestamp)??new Date().toISOString(),i=t._setMutationTimestamp(s),o=V(i,r,e.context);return await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let u=this.customMutations[n.procedure];if(u){let l=u.inputValidator["~standard"].validate(n.input),d=l instanceof Promise?await l:l;if(d.issues){let y=d.issues.map(h=>{var p;let f=(p=h.path)==null?void 0:p.map(m=>typeof m=="object"&&"key"in m?String(m.key):String(m)).join(".");return f?`${f}: ${h.message}`:h.message}).join(", ");throw new Error(`Validation failed: ${y}`)}return n.input=d.value,u.handler({req:n,db:o})}throw new Error(`Unknown procedure: ${n.procedure}`)})(e)};handleCustomQuery=async({req:e,db:t,schema:r})=>{let s=V(t,r,e.context);return await this.wrapInMiddlewares(async i=>{let o=this.customQueries[i.procedure];if(!o)throw new Error(`Unknown query procedure: ${i.procedure}`);let a=o.inputValidator["~standard"].validate(i.input),n=a instanceof Promise?await a:a;if(n.issues){let u=n.issues.map(l=>{var y;let d=(y=l.path)==null?void 0:y.map(h=>typeof h=="object"&&"key"in h?String(h.key):String(h)).join(".");return d?`${d}: ${l.message}`:l.message}).join(", ");throw new Error(`Validation failed: ${u}`)}return i.input=n.value,o.handler({req:i,db:s})})(e)};getAuthorizationClause(){}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,s)=>i=>s({req:i,next:r}),e)(t)}};function on(c){return {_brand:"TypedMiddleware",_rawMiddleware:({req:t,next:r})=>c({ctx:t.context,req:t,next:s=>(t.context=s,r(t))})}}var Ie=class c{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new xe(e,void 0,void 0,t,void 0).use(...this.middlewares)}withProcedures(e){let t=e({mutation:et,query:Xe}),r={},s={};for(let[i,o]of Object.entries(t))o._type==="mutation"?r[i]=o:s[i]=o;return new ve(r,s).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}},cn=Ie.create;var W=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(),s=await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([i,o])=>[i,{value:o,_meta:{timestamp:r}}]))});return z$1(s.data)}async update(e,t,r){let s=this._getTimestamp(),{id:i,...o}=r,a=await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([l,d])=>[l,{value:d,_meta:{timestamp:s}}]))}),n=z$1(a.data),u={};for(let l of Object.keys(o))l in n&&(u[l]=n[l]);return u}};var Wt={postgres:{jsonObjectFrom:jsonObjectFrom$2,jsonArrayFrom:jsonArrayFrom$2},mysql:{jsonObjectFrom:jsonObjectFrom$1,jsonArrayFrom:jsonArrayFrom$1},sqlite:{jsonObjectFrom:jsonObjectFrom,jsonArrayFrom:jsonArrayFrom}};function N(c){var s,i,o;let e=(s=c.getExecutor)==null?void 0:s.call(c),t=e==null?void 0:e.adapter;if(!t)return "postgres";let r=((o=(i=t.constructor)==null?void 0:i.name)==null?void 0:o.toLowerCase())??"";return r.includes("postgres")?"postgres":r.includes("mysql")?"mysql":r.includes("sqlite")?"sqlite":"postgres"}function tt(c){let e=N(c);return Wt[e]}var Kt="42701";function K(c){var t;if(c.code===Kt)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 Ce(c,e){let{type:t,enumValues:r,enumName:s}=c;if(r&&r.length>0)return e==="postgres"&&s?s:"varchar";if(t==="jsonb"||t==="json")switch(e){case "postgres":return "jsonb";case "mysql":return "json";case "sqlite":return "text"}return t}async function Jt(c,e,t,r){if(t!=="postgres")return;let s=new Map;for(let i of Object.values(e))for(let o of Object.values(i.fields)){let a=o.getStorageFieldType();a.enumValues&&a.enumName&&s.set(a.enumName,{name:a.enumName,values:a.enumValues});}for(let i of Array.from(s.values())){let{name:o,values:a}=i;try{let n=a.map(u=>`'${u}'`).join(", ");await sql`
|
|
2
2
|
DO $$ BEGIN
|
|
3
3
|
CREATE TYPE ${sql.id(o)} AS ENUM (${sql.raw(n)});
|
|
4
4
|
EXCEPTION
|
|
5
5
|
WHEN duplicate_object THEN null;
|
|
6
6
|
END $$;
|
|
7
|
-
`.execute(c);}catch(n){r==null||r.warn("Could not create enum type",o,n);}}}function J(c,e){return c.some(t=>t.name===e)}function
|
|
7
|
+
`.execute(c);}catch(n){r==null||r.warn("Could not create enum type",o,n);}}}function J(c,e){return c.some(t=>t.name===e)}function Gt(c,e){return (c==null?void 0:c.columns.some(t=>t.name===e))??false}function je(c,e){let[t]=e.split(".");return J(c,t)}function Me(c,e,t,r=false){let s=c;return e.unique&&(s=s.unique()),e.nullable||(s=s.notNull()),e.primary&&(s=s.primaryKey()),e.default!==void 0&&(s=s.defaultTo(e.default)),!r&&e.references&&je(t,e.references)&&(s=s.references(e.references)),s}function Zt(c,e,t,r,s){let i=[];for(let[o,a]of Object.entries(c.fields)){let n=e==null?void 0:e.columns.find(l=>l.name===o),u=a.getStorageFieldType();n?(n.dataType,u.type):(i.push({name:o,storageFieldType:u}),u.references&&!je(t,u.references)&&r.push({tableName:s,columnName:o,references:u.references}));}return i}function rt(c,e){return e==="postgres"&&!!c.enumValues&&c.enumValues.length>0&&!!c.enumName}async function Yt(c,e,t,r,s,i){if(t.length===0)return;let o=c.schema.createTable(e);for(let{name:a,storageFieldType:n}of t)if(rt(n,s))o=o.addColumn(a,sql.raw(n.enumName),u=>Me(u,n,r));else {let u=Ce(n,s);o=o.addColumn(a,u,l=>Me(l,n,r));}await o.execute().catch(a=>{if(!K(a))throw i==null||i.error("Error creating table",e,a),a});}async function Xt(c,e,t,r,s,i,o){for(let{name:a,storageFieldType:n}of t){let u=n.references?je(r,n.references):false,l=rt(n,i)?sql.raw(n.enumName):Ce(n,i);await c.schema.alterTable(e).addColumn(a,l,d=>Me(d,n,r,!u)).execute().catch(d=>{if(!K(d))throw o==null||o.error("Error adding column",a,d),d}),n.references&&!u&&!s.some(d=>d.tableName===e&&d.columnName===a)&&s.push({tableName:e,columnName:a,references:n.references}),n.index&&await c.schema.createIndex(`${e}_${a}_index`).on(e).column(a).execute().catch(()=>{});}}async function er(c,e,t,r,s,i){let o=`${e}_meta`,a=[];for(let[n,u]of Object.entries(t.fields)){let l=u.getStorageFieldType();Gt(r,n)||a.push({name:n,storageFieldType:l});}if(!r&&a.length>0){let n=c.schema.createTable(o);for(let{name:u,storageFieldType:l}of a)n=n.addColumn(u,"varchar",d=>{let y=d;return l.primary&&(y=y.primaryKey(),J(s,e)&&(y=y.references(`${e}.${u}`))),y});await n.execute().catch(u=>{if(!K(u))throw i==null||i.error("Error creating meta table",o,u),u});}else if(r)for(let{name:n,storageFieldType:u}of a)await c.schema.alterTable(o).addColumn(n,"varchar",l=>{let d=l;return u.primary&&(d=d.primaryKey(),J(s,e)&&(d=d.references(`${e}.${n}`))),d}).execute().catch(l=>{if(!K(l))throw i==null||i.error("Error adding meta column",n,l),l});}async function nt(c,e,t,r,s){let[i,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
|
-
REFERENCES ${sql.id(
|
|
12
|
-
`.execute(c);}catch(n){K(n)||i==null||i.warn("Could not add foreign key constraint",e,t,r,n);}}async function Zt(c,e,t,r){for(let{tableName:i,columnName:s,references:o}of e){let a=t.find(l=>l.name===i),n=a==null?void 0:a.columns.find(l=>l.name===s),[u]=o.split(".");a&&n&&J(t,u)&&await Xe(c,i,s,o,r);}}async function Yt(c,e,t,r){for(let[i,s]of Object.entries(e)){let o=`${i}_meta`,a=t.find(n=>n.name===o);if(a)for(let[n,u]of Object.entries(s.fields)){let l=u.getStorageFieldType(),d=a.columns.find(h=>h.name===n);l.primary&&d&&J(t,i)&&await Xe(c,o,n,`${i}.${n}`,r);}}}async function et(c,e,t){let r=k(c),i=await c.introspection.getTables(),s=[];await Ht(c,e,r,t);for(let[a,n]of Object.entries(e)){let u=i.find(h=>h.name===a),l=i.find(h=>h.name===`${a}_meta`),d=Wt(n,u,i,s,a);if(u)for(let[h,y]of Object.entries(n.fields)){let p=u.columns.find(T=>T.name===h),m=y.getStorageFieldType(),g=ve(m,r);p&&p.dataType!==g&&(t==null||t.warn("Column type mismatch:",h,"expected to have type:",g,"but has type:",p.dataType));}!u&&d.length>0?await Kt(c,a,d,i,r,t):u&&await Jt(c,a,d,i,s,r,t),await Gt(c,a,n,l,i,t);}let o=await c.introspection.getTables();await Zt(c,s,o,t),await Yt(c,e,o,t);}function ae(c,e,t,r){if(!c)throw new Error("Schema not initialized");let i=c[e];if(!i)throw new Error("Resource not found");let s=r.$or,o=r.$and;return (s?t.or:t.and)(s?r.$or.map(a=>ae(c,e,t,a)):o?r.$and.map(a=>ae(c,e,t,a)):Object.entries(r).map(([a,n])=>{var u,l;if(i.fields[a])return (n==null?void 0:n.$eq)!==void 0?t(`${e}.${a}`,n.$eq===null?"is":"=",n.$eq):(n==null?void 0:n.$in)!==void 0?t(`${e}.${a}`,"in",n.$in):(n==null?void 0:n.$not)!==void 0?((u=n==null?void 0:n.$not)==null?void 0:u.$in)!==void 0?t(`${e}.${a}`,"not in",n.$not.$in):((l=n==null?void 0:n.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${a}`,n.$not.$eq===null?"is not":"!=",n.$not.$eq):t(`${e}.${a}`,n.$not===null?"is not":"!=",n.$not):(n==null?void 0:n.$gt)!==void 0?t(`${e}.${a}`,">",n.$gt):(n==null?void 0:n.$gte)!==void 0?t(`${e}.${a}`,">=",n.$gte):(n==null?void 0:n.$lt)!==void 0?t(`${e}.${a}`,"<",n.$lt):(n==null?void 0:n.$lte)!==void 0?t(`${e}.${a}`,"<=",n.$lte):t(`${e}.${a}`,n===null?"is":"=",n);if(i.relations[a]){let d=i.relations[a],h=d.entity.name;return d.type==="many"?t.exists(ce(c,h,t.selectFrom(h).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),n)):ae(c,h,t,n)}return null}).filter(Boolean))}function oe(c,e,t,r){let i=c[e];if(!i)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let s of r.$and)t=oe(c,e,t,s);return t}else if(r.$or){for(let s of r.$or)t=oe(c,e,t,s);return t}for(let[s,o]of Object.entries(r)){if(!i.relations[s])continue;let a=i.relations[s],n=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,l=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(n,`${n}.${u}`,`${e}.${l}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=oe(c,n,t,o));}return t}function ce(c,e,t,r){return !r||Object.keys(r).length===0?t:(t=oe(c,e,t,r),t.where(i=>ae(c,e,i,r)))}function Xt(c,e,t,r,i){let s=k(i),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),n=c.selectFrom(r);for(let u of a)n=n.select(`${r}.${u}`);return n}return c.selectFrom(r).selectAll(r)}function er(c,e,t,r,i){let s=k(i),o=e[t];if(s==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),n=c.selectFrom(r);for(let u of a)n=n.select(`${r}.${u}`);return n}return c.selectFrom(r).selectAll(r)}function ue(c,e,t,r,i,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:n}=i;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,p=l.type==="one"?l.relationalColumn:"id",m=l.type==="one"?a:n,g=E(h)?h:null,T=g==null?void 0:g.include;t=t.select(f=>{let R=`${d}_meta`,b=er(f,c,d,d,s).whereRef(`${d}.${y}`,"=",`${e}.${p}`).select(S=>a(Xt(S,c,d,R,s).whereRef(`${R}.id`,"=",`${d}.id`)).as("_meta"));if(g!=null&&g.where&&(b=ce(c,d,b,g.where)),g!=null&&g.orderBy)for(let S of g.orderBy)b=b.orderBy(`${d}.${S.key}`,S.direction);return (g==null?void 0:g.limit)!==void 0&&(b=b.limit(g.limit)),T&&Object.keys(T).length>0&&(b=ue(c,d,b,T,i,s)),m(b).as(u)});}return t}var Me=class c extends W{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,r,i){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=Ze(this.db),this.schema=t,this.logger=r,this.server=i,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 et(this.db,e,t);}selectMetaColumns(e,t,r){var o;let i=k(this.db),s=(o=this.schema)==null?void 0:o[t];if(i==="sqlite"&&(s!=null&&s.fields)){let a=Object.keys(s.fields),n=e.selectFrom(r);for(let u of a)n=n.select(`${r}.${u}`);return n}return e.selectFrom(r).selectAll(r)}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let i=`${e}_meta`,s=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(n=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(n,e,i).whereRef(`${i}.id`,"=",`${e}.id`)).as("_meta"));s=ue(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 i=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(i)return z$2(i)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:i,limit:s,sort:o}=e,a=`${t}_meta`,n=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,a).whereRef(`${a}.id`,"=",`${t}.id`)).as("_meta"));n=ce(this.schema,t,n,r),n=ue(this.schema,t,n,i,this.dialectHelpers,this.db),s!==void 0&&(n=n.limit(s)),o!==void 0&&o.forEach(l=>{n=n.orderBy(l.key,l.direction);});let u=await n.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(i=>z$2(i))}async rawInsert(e,t,r,i,s){var m,g,T,f,R,b,S,v,E,Q,F;let o=(m=this.server)==null?void 0:m.getHooks(e),a=(g=this.schema)==null?void 0:g[e],[n,u]=((T=a==null?void 0:a.mergeMutation)==null?void 0:T.call(a,"set",r.value,void 0))??[r,r.value];if(!u)return {data:r,acceptedValues:null};let l=n,d={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let j=z$2(d);j.id=t;let I=await o.beforeInsert({ctx:s,value:j,rawValue:d,db:this});I&&(l=I);}let h={},y={};for(let[j,I]of Object.entries(l.value)){let O=(f=I._meta)==null?void 0:f.timestamp;if(!O)continue;let C=(b=(R=a==null?void 0:a.fields[j])==null?void 0:R.getStorageFieldType)==null?void 0:b.call(R);(C==null?void 0:C.type)==="jsonb"||(C==null?void 0:C.type)==="json"?h[j]=JSON.stringify(I.value):h[j]=I.value,y[j]=O;}await this.db.insertInto(e).values({...h,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...y,id:t}).execute(),(v=(S=this.logger)==null?void 0:S.debug)==null||v.call(S,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:i??"(auto-generated)",contextMessageId:(s==null?void 0:s.messageId)??"(none)",hasContext:!!s,contextKeys:s?Object.keys(s):[]});let p=this.buildMutation(e,t,"INSERT",l,i,s==null?void 0:s.messageId);if(p&&((F=(E=this.logger)==null?void 0:E.debug)==null||F.call(E,"[rawInsert] Mutation built, tracking",{mutationId:p.id,hasMeta:!!p.meta,originMutationId:((Q=p.meta)==null?void 0:Q.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(p,l)),o!=null&&o.afterInsert){let j={...l,value:{...l.value,id:{value:t}}},I=z$2(j);I.id=t,await o.afterInsert({ctx:s,value:I,rawValue:j,db:this});}return {data:l,acceptedValues:u}}async rawUpdate(e,t,r,i,s){var g,T,f,R,b,S,v,E,Q,F,j;let o=(g=this.server)==null?void 0:g.getHooks(e),a=(T=this.schema)==null?void 0:T[e],n=await this.rawFindById(e,t),[u,l]=((f=a==null?void 0:a.mergeMutation)==null?void 0:f.call(a,"set",r.value,n))??[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 I=z$2(h);I.id=t;let O;if(n){let A={...n,value:{...n.value,id:{value:t}}};O=z$2(A),O.id=t;}let C=await o.beforeUpdate({ctx:s,value:I,rawValue:h,previousValue:O,previousRawValue:n,db:this});C&&(d=C);}let y={},p={};for(let[I,O]of Object.entries(d.value)){let C=(R=O._meta)==null?void 0:R.timestamp;if(!C)continue;let A=(S=(b=a==null?void 0:a.fields[I])==null?void 0:b.getStorageFieldType)==null?void 0:S.call(b);(A==null?void 0:A.type)==="jsonb"||(A==null?void 0:A.type)==="json"?y[I]=JSON.stringify(O.value):y[I]=O.value,p[I]=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({...p,id:t}).onConflict(I=>I.column("id").doUpdateSet(p)).execute()]),(E=(v=this.logger)==null?void 0:v.debug)==null||E.call(v,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:i??"(auto-generated)",contextMessageId:(s==null?void 0:s.messageId)??"(none)",hasContext:!!s,contextKeys:s?Object.keys(s):[]});let m=this.buildMutation(e,t,"UPDATE",d,i,s==null?void 0:s.messageId);if(m){(j=(Q=this.logger)==null?void 0:Q.debug)==null||j.call(Q,"[rawUpdate] Mutation built, tracking",{mutationId:m.id,hasMeta:!!m.meta,originMutationId:((F=m.meta)==null?void 0:F.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});let I=await this.rawFindById(e,t);I&&this.trackMutation(m,I);}if(o!=null&&o.afterUpdate){let I=await this.rawFindById(e,t);if(I){let O={...I,value:{...I.value,id:{value:t}}},C=z$2(O);C.id=t;let A;if(n){let rt={...n,value:{...n.value,id:{value:t}}};A=z$2(rt),A.id=t;}await o.afterUpdate({ctx:s,value:C,rawValue:O,previousValue:A,previousRawValue:n,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 n=await this.db.savepoint(s).execute(),u=false,l=false;try{return await e({trx:this,commit:async()=>{await n.releaseSavepoint(s).execute(),u=!0,o.push(...a);},rollback:async()=>{await n.rollbackToSavepoint(s).execute(),l=!0,a.length=0;}}).then(d=>n.isCommitted||n.isRolledBack||u||l?d:n.releaseSavepoint(s).execute().then(()=>(o.push(...a),d)))}catch(d){throw l||await n.rollbackToSavepoint(s).execute().catch(()=>{}),a.length=0,d}finally{this.mutationStack=o;}}let t=[],r=this.mutationStack;this.mutationStack=t;let i=await this.db.startTransaction().execute();try{let s=new c(i,this.schema,this.logger,this.server);return s.mutationStack=t,await e({trx:s,commit:async()=>{var o,a;await i.commit().execute(),(a=(o=this.logger)==null?void 0:o.debug)==null||a.call(o,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:n})=>{var u;return {id:n.id,resource:n.resource,resourceId:n.resourceId,procedure:n.procedure,hasMeta:!!n.meta,originMutationId:((u=n.meta)==null?void 0:u.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await i.rollback().execute(),t.length=0;}}).then(o=>i.isCommitted||i.isRolledBack?o:i.commit().execute().then(()=>{var a,n;return (n=(a=this.logger)==null?void 0:a.debug)==null||n.call(a,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:u})=>{var l;return {id:u.id,resource:u.resource,resourceId:u.resourceId,procedure:u.procedure,hasMeta:!!u.meta,originMutationId:((l=u.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t),o}))}catch(s){throw await i.rollback().execute(),t.length=0,s}finally{this.mutationStack=r;}}get internalDB(){return this.db}isRelationalField(e,t){var i;if(!this.schema)return false;let r=this.schema[e];return !!((i=r==null?void 0:r.relations)!=null&&i[t])}parseRelationalJsonStrings(e,t){var s,o;if(k(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 i={};for(let[a,n]of Object.entries(e))if(a==="_meta"&&typeof n=="string")if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{i[a]=JSON.parse(n);}catch{i[a]=n;}else i[a]=n;else if(this.isRelationalField(t,a))if(typeof n=="string")if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{let u=JSON.parse(n);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;i[a]=this.parseRelationalJsonStrings(u,h);}else i[a]=u;}else i[a]=u;}catch{i[a]=n;}else i[a]=n;else if(typeof n=="object"&&n!==null&&!Array.isArray(n))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;i[a]=this.parseRelationalJsonStrings(n,d);}else i[a]=n;}else i[a]=n;else Array.isArray(n)?i[a]=n.map(u=>{var l,d;if(typeof u=="string")try{let h=JSON.parse(u);if(this.schema){let y=this.schema[t],p=(l=y==null?void 0:y.relations)==null?void 0:l[a];if(p){let m=p.entity.name;return this.parseRelationalJsonStrings(h,m)}}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 p=y.entity.name;return this.parseRelationalJsonStrings(u,p)}}return u}):i[a]=n;else i[a]=n;return i}convertToMaterializedLiveType(e,t){var i;let r=(i=this.schema)==null?void 0:i[t];return {value:Object.entries(e).reduce((s,[o,a])=>{var d,h,y,p,m,g,T,f,R;if(o==="_meta")return s;let n=(h=(d=r==null?void 0:r.fields[o])==null?void 0:d.getStorageFieldType)==null?void 0:h.call(d),u=(n==null?void 0:n.type)==="jsonb"||(n==null?void 0:n.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,S=(b==null?void 0:b.name)??t;Array.isArray(a)?s[o]={value:a.map(v=>this.convertToMaterializedLiveType(v,S)),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:a!==null&&typeof a=="object"?s[o]={...this.convertToMaterializedLiveType(a,S),_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}}:s[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[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:(f=e==null?void 0:e._meta)==null?void 0:f[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",i=typeof t.startTransaction=="function",s=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&i||s&&o}buildMutation(e,t,r,i,s,o){var n;let a={};for(let[u,l]of Object.entries(i.value)){if(u==="id")continue;let d=(n=l._meta)==null?void 0:n.timestamp;d&&(a[u]={value:l.value,_meta:{timestamp:d}});}return Object.keys(a).length===0?null:{id:s??X(),type:"MUTATE",resource:e,resourceId:t,procedure:r,payload:a,meta:o?{originMutationId:o}:void 0}}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 i of r)this.server.notifySubscribers(i,t);}else {let r=e;for(let{mutation:i,entityData:s}of r)this.server.notifySubscribers(i,s);}}};var Ce=class c{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var i;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G({level:e.logLevel??F.INFO}),(i=e.middlewares)==null||i.forEach(s=>{this.middlewares.add(s);});let t=this.router.hooksRegistry,r=new Set;if(t&&t.forEach((s,o)=>{r.add(o);}),e.hooks)for(let s of Object.keys(e.hooks))r.add(s);r.forEach(s=>{var u;let o=t==null?void 0:t.get(s),a=(u=e.hooks)==null?void 0:u[s],n=ye([o,a]);n&&this.hooksRegistry.set(s,n);}),this.initPromise=this.storage.init(this.schema,this.logger,this).catch(s=>{this.initError=s;}),this.contextProvider=e.contextProvider,this.queryEngine=new te({router:{get:async(s,o)=>{var y;let{headers:a,cookies:n,queryParams:u,context:l}=(o==null?void 0:o.context)??{};if(!(o!=null&&o.batcher))throw new Error("Batcher is required");let d={...s,type:"QUERY",headers:a,cookies:n,queryParams:u,context:l},h=await((y=this.router.routes[s.resource])==null?void 0:y.handleQuery({req:d,batcher:o.batcher}));return (h==null?void 0:h.data)??[]},incrementQueryStep:(s,o={})=>{var u;let a=(u=this.router.routes[s.query.resource])==null?void 0:u.getAuthorizationClause({...s.query,type:"QUERY",headers:o.headers,cookies:o.cookies,queryParams:o.queryParams,context:o.context});if(typeof a=="boolean"&&!a)throw new Error("Not authorized");let n=z(s.query.where,typeof a=="object"?a:void 0);return {...s,query:{...s.query,where:n}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleQuery(e){return await this.ensureInitialized(),this.wrapInMiddlewares(async t=>{let{headers:r,cookies:i,queryParams:s,context:o,...a}=t,n={headers:r,cookies:i,queryParams:s,context:o},u=e.subscription?this.queryEngine.subscribe(a,d=>{var h;(h=e.subscription)==null||h.call(e,d);},n):void 0;return {data:await this.queryEngine.get(a,{context:n}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.ensureInitialized(),await this.wrapInMiddlewares(async r=>{let i=this.router.routes[r.resource];if(!i)throw new Error("Invalid resource");return i.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){await this.ensureInitialized();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:i,cookies:s,queryParams:o,context:a}=e.req,n={headers:i,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);},n):void 0,d=await this.queryEngine.get(u,{context:n});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,i)=>s=>i({req:s,next:r}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},Qn=Ce.create;export{Se as ProcedureRoute,be as Route,we as RouteFactory,Re as Router,Me as SQLStorage,Ce as Server,W as Storage,rn as createMiddleware,D as createServerDB,gr as defineHooks,Hr as expressAdapter,ye as mergeEntityHooks,Tr as mergeHooks,nn as routeFactory,tn as router,Qn as server};
|
|
11
|
+
REFERENCES ${sql.id(i)} (${sql.id(o)})
|
|
12
|
+
`.execute(c);}catch(n){K(n)||s==null||s.warn("Could not add foreign key constraint",e,t,r,n);}}async function tr(c,e,t,r){for(let{tableName:s,columnName:i,references:o}of e){let a=t.find(l=>l.name===s),n=a==null?void 0:a.columns.find(l=>l.name===i),[u]=o.split(".");a&&n&&J(t,u)&&await nt(c,s,i,o,r);}}async function rr(c,e,t,r){for(let[s,i]of Object.entries(e)){let o=`${s}_meta`,a=t.find(n=>n.name===o);if(a)for(let[n,u]of Object.entries(i.fields)){let l=u.getStorageFieldType(),d=a.columns.find(y=>y.name===n);l.primary&&d&&J(t,s)&&await nt(c,o,n,`${s}.${n}`,r);}}}async function st(c,e,t){let r=N(c),s=await c.introspection.getTables(),i=[];await Jt(c,e,r,t);for(let[a,n]of Object.entries(e)){let u=s.find(y=>y.name===a),l=s.find(y=>y.name===`${a}_meta`),d=Zt(n,u,s,i,a);if(u)for(let[y,h]of Object.entries(n.fields)){let f=u.columns.find(T=>T.name===y),p=h.getStorageFieldType(),m=Ce(p,r);f&&f.dataType!==m&&(t==null||t.warn("Column type mismatch:",y,"expected to have type:",m,"but has type:",f.dataType));}!u&&d.length>0?await Yt(c,a,d,s,r,t):u&&await Xt(c,a,d,s,i,r,t),await er(c,a,n,l,s,t);}let o=await c.introspection.getTables();await tr(c,i,o,t),await rr(c,e,o,t);}function ae(c,e,t,r){if(!c)throw new Error("Schema not initialized");let s=c[e];if(!s)throw new Error("Resource not found");let i=r.$or,o=r.$and;return (i?t.or:t.and)(i?r.$or.map(a=>ae(c,e,t,a)):o?r.$and.map(a=>ae(c,e,t,a)):Object.entries(r).map(([a,n])=>{var u,l;if(s.fields[a])return (n==null?void 0:n.$eq)!==void 0?t(`${e}.${a}`,n.$eq===null?"is":"=",n.$eq):(n==null?void 0:n.$in)!==void 0?t(`${e}.${a}`,"in",n.$in):(n==null?void 0:n.$not)!==void 0?((u=n==null?void 0:n.$not)==null?void 0:u.$in)!==void 0?t(`${e}.${a}`,"not in",n.$not.$in):((l=n==null?void 0:n.$not)==null?void 0:l.$eq)!==void 0?t(`${e}.${a}`,n.$not.$eq===null?"is not":"!=",n.$not.$eq):t(`${e}.${a}`,n.$not===null?"is not":"!=",n.$not):(n==null?void 0:n.$gt)!==void 0?t(`${e}.${a}`,">",n.$gt):(n==null?void 0:n.$gte)!==void 0?t(`${e}.${a}`,">=",n.$gte):(n==null?void 0:n.$lt)!==void 0?t(`${e}.${a}`,"<",n.$lt):(n==null?void 0:n.$lte)!==void 0?t(`${e}.${a}`,"<=",n.$lte):t(`${e}.${a}`,n===null?"is":"=",n);if(s.relations[a]){let d=s.relations[a],y=d.entity.name;return d.type==="many"?t.exists(ce(c,y,t.selectFrom(y).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),n)):ae(c,y,t,n)}return null}).filter(Boolean))}function oe(c,e,t,r){let s=c[e];if(!s)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let i of r.$and)t=oe(c,e,t,i);return t}else if(r.$or){for(let i of r.$or)t=oe(c,e,t,i);return t}for(let[i,o]of Object.entries(r)){if(!s.relations[i])continue;let a=s.relations[i],n=a.entity.name,u=a.type==="one"?"id":a.foreignColumn,l=a.type==="one"?a.relationalColumn:"id";t=t.leftJoin(n,`${n}.${u}`,`${e}.${l}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=oe(c,n,t,o));}return t}function ce(c,e,t,r){return !r||Object.keys(r).length===0?t:(t=oe(c,e,t,r),t.where(s=>ae(c,e,s,r)))}function nr(c,e,t,r,s){let i=N(s),o=e[t];if(i==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),n=c.selectFrom(r);for(let u of a)n=n.select(`${r}.${u}`);return n}return c.selectFrom(r).selectAll(r)}function sr(c,e,t,r,s){let i=N(s),o=e[t];if(i==="sqlite"&&(o!=null&&o.fields)){let a=Object.keys(o.fields),n=c.selectFrom(r);for(let u of a)n=n.select(`${r}.${u}`);return n}return c.selectFrom(r).selectAll(r)}function ue(c,e,t,r,s,i){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:n}=s;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,y=r[u],h=l.type==="one"?"id":l.foreignColumn,f=l.type==="one"?l.relationalColumn:"id",p=l.type==="one"?a:n,m=E(y)?y:null,T=m==null?void 0:m.include;t=t.select(g=>{let R=`${d}_meta`,b=sr(g,c,d,d,i).whereRef(`${d}.${h}`,"=",`${e}.${f}`).select(S=>a(nr(S,c,d,R,i).whereRef(`${R}.id`,"=",`${d}.id`)).as("_meta"));if(m!=null&&m.where&&(b=ce(c,d,b,m.where)),m!=null&&m.orderBy)for(let S of m.orderBy)b=b.orderBy(`${d}.${S.key}`,S.direction);return (m==null?void 0:m.limit)!==void 0&&(b=b.limit(m.limit)),T&&Object.keys(T).length>0&&(b=ue(c,d,b,T,s,i)),p(b).as(u)});}return t}var Oe=class c extends W{db;dialectHelpers;schema;logger;server;mutationStack=[];constructor(e,t,r,s){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.dialectHelpers=tt(this.db),this.schema=t,this.logger=r,this.server=s,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 st(this.db,e,t);}selectMetaColumns(e,t,r){var o;let s=N(this.db),i=(o=this.schema)==null?void 0:o[t];if(s==="sqlite"&&(i!=null&&i.fields)){let a=Object.keys(i.fields),n=e.selectFrom(r);for(let u of a)n=n.select(`${r}.${u}`);return n}return e.selectFrom(r).selectAll(r)}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let s=`${e}_meta`,i=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(n=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(n,e,s).whereRef(`${s}.id`,"=",`${e}.id`)).as("_meta"));i=ue(this.schema,e,i,r,this.dialectHelpers,this.db);let o=await i.executeTakeFirst();if(!o)return;let a=this.parseRelationalJsonStrings(o,e);return this.convertToMaterializedLiveType(a,e)}async findOne(e,t,r){let s=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(s)return z$1(s)}async get(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:s,limit:i,sort:o}=e,a=`${t}_meta`,n=this.db.selectFrom(t).selectAll(t).select(l=>this.dialectHelpers.jsonObjectFrom(this.selectMetaColumns(l,t,a).whereRef(`${a}.id`,"=",`${t}.id`)).as("_meta"));n=ce(this.schema,t,n,r),n=ue(this.schema,t,n,s,this.dialectHelpers,this.db),i!==void 0&&(n=n.limit(i)),o!==void 0&&o.forEach(l=>{n=n.orderBy(l.key,l.direction);});let u=await n.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(s=>z$1(s))}async rawInsert(e,t,r,s,i){var p,m,T,g,R,b,S,x,A,k,E;let o=(p=this.server)==null?void 0:p.getHooks(e),a=(m=this.schema)==null?void 0:m[e],[n,u]=((T=a==null?void 0:a.mergeMutation)==null?void 0:T.call(a,"set",r.value,void 0))??[r,r.value];if(!u)return {data:r,acceptedValues:null};let l=n,d={...l,value:{...l.value,id:{value:t}}};if(o!=null&&o.beforeInsert){let C=z$1(d);C.id=t;let v=await o.beforeInsert({ctx:i,value:C,rawValue:d,db:this});v&&(l=v);}let y={},h={};for(let[C,v]of Object.entries(l.value)){let j=(g=v._meta)==null?void 0:g.timestamp;if(!j)continue;let O=(b=(R=a==null?void 0:a.fields[C])==null?void 0:R.getStorageFieldType)==null?void 0:b.call(R);(O==null?void 0:O.type)==="jsonb"||(O==null?void 0:O.type)==="json"?y[C]=JSON.stringify(v.value):y[C]=v.value,h[C]=j;}await this.db.insertInto(e).values({...y,id:t}).execute(),await this.db.insertInto(`${e}_meta`).values({...h,id:t}).execute(),(x=(S=this.logger)==null?void 0:S.debug)==null||x.call(S,"[rawInsert] Building mutation",{resourceName:e,resourceId:t,mutationId:s??"(auto-generated)",contextMessageId:(i==null?void 0:i.messageId)??"(none)",hasContext:!!i,contextKeys:i?Object.keys(i):[]});let f=this.buildMutation(e,t,"INSERT",l,s,i==null?void 0:i.messageId);if(f&&((E=(A=this.logger)==null?void 0:A.debug)==null||E.call(A,"[rawInsert] Mutation built, tracking",{mutationId:f.id,hasMeta:!!f.meta,originMutationId:((k=f.meta)==null?void 0:k.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction}),this.trackMutation(f,l)),o!=null&&o.afterInsert){let C={...l,value:{...l.value,id:{value:t}}},v=z$1(C);v.id=t,await o.afterInsert({ctx:i,value:v,rawValue:C,db:this});}return {data:l,acceptedValues:u}}async rawUpdate(e,t,r,s,i){var m,T,g,R,b,S,x,A,k,E,C;let o=(m=this.server)==null?void 0:m.getHooks(e),a=(T=this.schema)==null?void 0:T[e],n=await this.rawFindById(e,t),[u,l]=((g=a==null?void 0:a.mergeMutation)==null?void 0:g.call(a,"set",r.value,n))??[r,r.value];if(!l)return {data:r,acceptedValues:null};let d=u,y={...d,value:{...d.value,id:{value:t}}};if(o!=null&&o.beforeUpdate){let v=z$1(y);v.id=t;let j;if(n){let P={...n,value:{...n.value,id:{value:t}}};j=z$1(P),j.id=t;}let O=await o.beforeUpdate({ctx:i,value:v,rawValue:y,previousValue:j,previousRawValue:n,db:this});O&&(d=O);}let h={},f={};for(let[v,j]of Object.entries(d.value)){let O=(R=j._meta)==null?void 0:R.timestamp;if(!O)continue;let P=(S=(b=a==null?void 0:a.fields[v])==null?void 0:b.getStorageFieldType)==null?void 0:S.call(b);(P==null?void 0:P.type)==="jsonb"||(P==null?void 0:P.type)==="json"?h[v]=JSON.stringify(j.value):h[v]=j.value,f[v]=O;}if(Object.keys(h).length===0)return {data:d,acceptedValues:l};await Promise.all([this.db.updateTable(e).set(h).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...f,id:t}).onConflict(v=>v.column("id").doUpdateSet(f)).execute()]),(A=(x=this.logger)==null?void 0:x.debug)==null||A.call(x,"[rawUpdate] Building mutation",{resourceName:e,resourceId:t,mutationId:s??"(auto-generated)",contextMessageId:(i==null?void 0:i.messageId)??"(none)",hasContext:!!i,contextKeys:i?Object.keys(i):[]});let p=this.buildMutation(e,t,"UPDATE",d,s,i==null?void 0:i.messageId);if(p){(C=(k=this.logger)==null?void 0:k.debug)==null||C.call(k,"[rawUpdate] Mutation built, tracking",{mutationId:p.id,hasMeta:!!p.meta,originMutationId:((E=p.meta)==null?void 0:E.originMutationId)??"(none)",isTransaction:!!this.db.isTransaction});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}}},O=z$1(j);O.id=t;let P;if(n){let de={...n,value:{...n.value,id:{value:t}}};P=z$1(de),P.id=t;}await o.afterUpdate({ctx:i,value:O,rawValue:j,previousValue:P,previousRawValue:n,db:this});}}return {data:d,acceptedValues:l}}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let i=Math.random().toString(36).substring(2,15),o=this.mutationStack,a=[];this.mutationStack=a;let n=await this.db.savepoint(i).execute(),u=false,l=false;try{return await e({trx:this,commit:async()=>{await n.releaseSavepoint(i).execute(),u=!0,o.push(...a);},rollback:async()=>{await n.rollbackToSavepoint(i).execute(),l=!0,a.length=0;}}).then(d=>n.isCommitted||n.isRolledBack||u||l?d:n.releaseSavepoint(i).execute().then(()=>(o.push(...a),d)))}catch(d){throw l||await n.rollbackToSavepoint(i).execute().catch(()=>{}),a.length=0,d}finally{this.mutationStack=o;}}let t=[],r=this.mutationStack;this.mutationStack=t;let s=await this.db.startTransaction().execute();try{let i=new c(s,this.schema,this.logger,this.server);return i.mutationStack=t,await e({trx:i,commit:async()=>{var o,a;await s.commit().execute(),(a=(o=this.logger)==null?void 0:o.debug)==null||a.call(o,"[transaction] Explicit commit flushing mutations",{count:t.length,mutations:t.map(({mutation:n})=>{var u;return {id:n.id,resource:n.resource,resourceId:n.resourceId,procedure:n.procedure,hasMeta:!!n.meta,originMutationId:((u=n.meta)==null?void 0:u.originMutationId)??"(none)"}})}),this.notifyMutations(t);},rollback:async()=>{await s.rollback().execute(),t.length=0;}}).then(o=>s.isCommitted||s.isRolledBack?o:s.commit().execute().then(()=>{var a,n;return (n=(a=this.logger)==null?void 0:a.debug)==null||n.call(a,"[transaction] Auto-commit flushing mutations",{count:t.length,mutations:t.map(({mutation:u})=>{var l;return {id:u.id,resource:u.resource,resourceId:u.resourceId,procedure:u.procedure,hasMeta:!!u.meta,originMutationId:((l=u.meta)==null?void 0:l.originMutationId)??"(none)"}})}),this.notifyMutations(t),o}))}catch(i){throw await s.rollback().execute(),t.length=0,i}finally{this.mutationStack=r;}}get internalDB(){return this.db}isRelationalField(e,t){var s;if(!this.schema)return false;let r=this.schema[e];return !!((s=r==null?void 0:r.relations)!=null&&s[t])}parseRelationalJsonStrings(e,t){var i,o;if(N(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 s={};for(let[a,n]of Object.entries(e))if(a==="_meta"&&typeof n=="string")if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{s[a]=JSON.parse(n);}catch{s[a]=n;}else s[a]=n;else if(this.isRelationalField(t,a))if(typeof n=="string")if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{let u=JSON.parse(n);if(this.schema){let l=this.schema[t],d=(i=l==null?void 0:l.relations)==null?void 0:i[a];if(d){let y=d.entity.name;s[a]=this.parseRelationalJsonStrings(u,y);}else s[a]=u;}else s[a]=u;}catch{s[a]=n;}else s[a]=n;else if(typeof n=="object"&&n!==null&&!Array.isArray(n))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;s[a]=this.parseRelationalJsonStrings(n,d);}else s[a]=n;}else s[a]=n;else Array.isArray(n)?s[a]=n.map(u=>{var l,d;if(typeof u=="string")try{let y=JSON.parse(u);if(this.schema){let h=this.schema[t],f=(l=h==null?void 0:h.relations)==null?void 0:l[a];if(f){let p=f.entity.name;return this.parseRelationalJsonStrings(y,p)}}return y}catch{return u}if(typeof u=="object"&&u!==null&&this.schema){let y=this.schema[t],h=(d=y==null?void 0:y.relations)==null?void 0:d[a];if(h){let f=h.entity.name;return this.parseRelationalJsonStrings(u,f)}}return u}):s[a]=n;else s[a]=n;return s}convertToMaterializedLiveType(e,t){var s;let r=(s=this.schema)==null?void 0:s[t];return {value:Object.entries(e).reduce((i,[o,a])=>{var d,y,h,f,p,m,T,g,R;if(o==="_meta")return i;let n=(y=(d=r==null?void 0:r.fields[o])==null?void 0:d.getStorageFieldType)==null?void 0:y.call(d),u=(n==null?void 0:n.type)==="jsonb"||(n==null?void 0:n.type)==="json",l=(r==null?void 0:r.relations)&&o in r.relations;if(o==="id")i[o]={value:a};else if(u)i[o]={value:a,_meta:{timestamp:(h=e==null?void 0:e._meta)==null?void 0:h[o]}};else if(l){let b=r.relations[o].entity,S=(b==null?void 0:b.name)??t;Array.isArray(a)?i[o]={value:a.map(x=>this.convertToMaterializedLiveType(x,S)),_meta:{timestamp:(f=e==null?void 0:e._meta)==null?void 0:f[o],relation:true}}:a!==null&&typeof a=="object"?i[o]={...this.convertToMaterializedLiveType(a,S),_meta:{timestamp:(p=e==null?void 0:e._meta)==null?void 0:p[o],relation:true}}:i[o]={value:a,_meta:{timestamp:(m=e==null?void 0:e._meta)==null?void 0:m[o],relation:true}};}else Array.isArray(a)?i[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)?i[o]={value:a,_meta:{timestamp:(g=e==null?void 0:e._meta)==null?void 0:g[o]}}:i[o]={value:a,_meta:{timestamp:(R=e==null?void 0:e._meta)==null?void 0:R[o]}};return i},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",s=typeof t.startTransaction=="function",i=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&s||i&&o}buildMutation(e,t,r,s,i,o){var n;let a={};for(let[u,l]of Object.entries(s.value)){if(u==="id")continue;let d=(n=l._meta)==null?void 0:n.timestamp;d&&(a[u]={value:l.value,_meta:{timestamp:d}});}return Object.keys(a).length===0?null:{id:i??X(),type:"MUTATE",resource:e,resourceId:t,procedure:r,payload:a,meta:o?{originMutationId:o}:void 0}}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 s of r)this.server.notifySubscribers(s,t);}else {let r=e;for(let{mutation:s,entityData:i}of r)this.server.notifySubscribers(s,i);}}};var Ae=class c{router;storage;schema;middlewares=new Set;logger;hooksRegistry=new Map;initPromise;initError;contextProvider;queryEngine;constructor(e){var s;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=G({level:e.logLevel??F$1.INFO}),(s=e.middlewares)==null||s.forEach(i=>{this.middlewares.add(i);});let t=this.router.hooksRegistry,r=new Set;if(t&&t.forEach((i,o)=>{r.add(o);}),e.hooks)for(let i of Object.keys(e.hooks))r.add(i);r.forEach(i=>{var u;let o=t==null?void 0:t.get(i),a=(u=e.hooks)==null?void 0:u[i],n=pe([o,a]);n&&this.hooksRegistry.set(i,n);}),this.initPromise=this.storage.init(this.schema,this.logger,this).catch(i=>{this.initError=i;}),this.contextProvider=e.contextProvider,this.queryEngine=new te({router:{get:async(i,o)=>{var h;let{headers:a,cookies:n,queryParams:u,context:l}=(o==null?void 0:o.context)??{};if(!(o!=null&&o.batcher))throw new Error("Batcher is required");let d={...i,type:"QUERY",headers:a,cookies:n,queryParams:u,context:l},y=await((h=this.router.routes[i.resource])==null?void 0:h.handleQuery({req:d,batcher:o.batcher}));return (y==null?void 0:y.data)??[]},incrementQueryStep:(i,o={})=>{var u;let a=(u=this.router.routes[i.query.resource])==null?void 0:u.getAuthorizationClause({...i.query,type:"QUERY",headers:o.headers,cookies:o.cookies,queryParams:o.queryParams,context:o.context});if(typeof a=="boolean"&&!a)throw new Error("Not authorized");let n=B(i.query.where,typeof a=="object"?a:void 0);return {...i,query:{...i.query,where:n}}}},storage:this.storage,schema:this.schema,logger:this.logger});}static create(e){return new c(e)}getHooks(e){return this.hooksRegistry.get(e)}async handleQuery(e){return await this.ensureInitialized(),this.wrapInMiddlewares(async t=>{let{headers:r,cookies:s,queryParams:i,context:o,...a}=t,n={headers:r,cookies:s,queryParams:i,context:o},u=e.subscription?this.queryEngine.subscribe(a,d=>{var y;(y=e.subscription)==null||y.call(e,d);},n):void 0;return {data:await this.queryEngine.get(a,{context:n}),unsubscribe:u}})(e.req)}async handleMutation(e){return await this.ensureInitialized(),await this.wrapInMiddlewares(async r=>{let s=this.router.routes[r.resource];if(!s)throw new Error("Invalid resource");return s.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req)}async handleCustomQuery(e){await this.ensureInitialized();let t=await this.wrapInMiddlewares(async y=>{let h=this.router.routes[y.resource];if(!h)throw new Error("Invalid resource");return h.handleCustomQuery({req:y,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:s,cookies:i,queryParams:o,context:a}=e.req,n={headers:s,cookies:i,queryParams:o,context:a},u=t.buildQueryRequest(),l=e.subscription?this.queryEngine.subscribe(u,y=>{var h;(h=e.subscription)==null||h.call(e,y);},n):void 0,d=await this.queryEngine.get(u,{context:n});return e.subscription?{data:d,unsubscribe:l,query:u}:d.map(y=>z$1(y))}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,s)=>i=>s({req:i,next:r}),e)(t)}async ensureInitialized(){if(await this.initPromise,this.initError)throw this.initError}},_n=Ae.create;export{ve as ProcedureRoute,xe as Route,Ie as RouteFactory,we as Router,Oe as SQLStorage,Ae as Server,W as Storage,on as createMiddleware,V as createServerDB,Sr as defineHooks,Jr as expressAdapter,pe as mergeEntityHooks,wr as mergeHooks,cn as routeFactory,an as router,_n as server};
|