@live-state/sync 0.0.4-beta.4 → 0.0.4-beta.5
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/{chunk-GNY3ZGE5.js → chunk-7C33XQ3U.js} +1 -1
- package/dist/chunk-VYWZ6RGP.js +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +2 -14
- package/dist/fetch-client.js +1 -1
- package/dist/{index-BjkfU9Th.d.ts → index-Y5wSNhd8.d.ts} +32 -24
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +18 -12
- package/dist/index.d.ts +18 -12
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-RWM6TXG7.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var R=Object.create;var
|
|
1
|
+
var R=Object.create;var x=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var g=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var O=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of g(e))!M.call(t,a)&&a!==n&&x(t,a,{get:()=>e[a],enumerable:!(i=b(e,a))||i.enumerable});return t};var K=(t,e,n)=>(n=t!=null?R(I(t)):{},O(e||!t||!t.__esModule?x(n,"default",{value:t,enumerable:true}):n,t));var s=class{_value;_meta;_encodeInput;_decodeInput};var c=class extends s{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,n,i){return this.inner.encodeMutation(e,n,i)}mergeMutation(e,n,i){return this.inner.mergeMutation(e,n,i)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class t extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,n,i,a,r,u,y){super(),this.storageType=e,this.convertFunc=n,this.isIndex=i??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=u,this.isPrimary=y??false;}encodeMutation(e,n,i){return {value:n,_meta:{timestamp:i}}}mergeMutation(e,n,i){return i&&i._meta.timestamp&&n._meta.timestamp&&i._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[i,null]:[{value:this.convertFunc?this.convertFunc(n.value):n.value,_meta:n._meta},n]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new t(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new t(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new t(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}nullable(){return new c(this)}},p=class t extends l{constructor(){super("integer",e=>Number(e));}static create(){return new t}},V=p.create,o=class t extends l{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new t}static createId(){return new t().index().unique().primary()}static createReference(e){return new t(e)}},_=o.create,E=o.createId,F=o.createReference,d=class t extends l{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},C=d.create,m=class t extends l{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},q=m.create;var v=class t extends s{name;fields;relations;constructor(e,n,i){super(),this.name=e,this.fields=n,this.relations=i??{};}encodeMutation(e,n,i){return Object.fromEntries(Object.entries(n).map(([a,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,i)]))}mergeMutation(e,n,i){let a={};return [{value:{...(i==null?void 0:i.value)??{},...Object.fromEntries(Object.entries(n).map(([r,u])=>{let y=this.fields[r]??this.relations[r];if(!y)return [r,u];let[L,f]=y.mergeMutation(e,u,i==null?void 0:i.value[r]);return f&&(a[r]=f),[r,L]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,n){return new t(e,n)}},P=v.create,T=class t extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,n,i,a,r){super(),this.entity=e,this.type=n,this.required=r??false,this.relationalColumn=i,this.foreignColumn=a;}encodeMutation(e,n,i){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:n,_meta:{timestamp:i}}}mergeMutation(e,n,i){if(this.type==="many")throw new Error("Many not implemented.");return i&&i._meta.timestamp&&n._meta.timestamp&&i._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[i,null]:[n,n]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,n,i)=>new t(e,"one",n,void 0,i??false)}static createManyFactory(){return (e,n,i)=>new t(e,"many",void 0,n,i??false)}},$=(t,e)=>({$type:"relations",objectName:t.name,relations:e({one:T.createOneFactory(),many:T.createManyFactory()})}),h=t=>{if(t)return Array.isArray(t.value)?t.value.map(e=>h(e)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([e,n])=>[e,h(n)]))},k=t=>Object.fromEntries(Object.entries(t).flatMap(([e,n])=>{if(n.$type==="relations")return [];let i=n,a=Object.values(t).find(r=>r.$type==="relations"&&r.objectName===n.name);return a&&(i=i.setRelations(a.relations)),[[i.name,i]]}));export{j as a,K as b,s as c,c as d,l as e,p as f,V as g,o as h,_ as i,E as j,F as k,d as l,C as m,m as n,q as o,v as p,P as q,T as r,$ as s,h as t,k as u};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var c;(function(t){t.Base32IncorrectEncoding="B32_ENC_INVALID",t.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",t.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",t.EncodeTimeNegative="ENC_TIME_NEG",t.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",t.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",t.PRNGDetectFailure="PRNG_DETECT",t.ULIDInvalid="ULID_INVALID",t.Unexpected="UNEXPECTED",t.UUIDInvalid="UUID_INVALID";})(c||(c={}));var u=class extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e;}};function _(t){let e=Math.floor(t()*32);return e===32&&(e=31),f.charAt(e)}function m(t){let e=p(),n=e&&(e.crypto||e.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return n.getRandomValues(i),i[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return ()=>n.randomBytes(1).readUInt8()/255;throw new u(c.PRNGDetectFailure,"Failed to find a reliable PRNG")}function p(){return g()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function I(t,e){let n="";for(;t>0;t--)n=_(e)+n;return n}function w(t,e=10){if(isNaN(t))throw new u(c.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>0xffffffffffff)throw new u(c.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${t}`);if(t<0)throw new u(c.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===false)throw new u(c.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,i="";for(let r=e;r>0;r--)n=t%32,i=f.charAt(n)+i,t=(t-n)/32;return i}function g(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function h(t,e){let n=m(),i=Date.now();return w(i,10)+I(16,n)}var b=()=>h().toLowerCase(),A=(t,e)=>typeof t=="function"?t(e):t;var T=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,r,o,s,l,a){this._collection=e,this._client=n,this._where=i??{},this._include=r??{},this._limit=o,this._single=s,this._sort=l,this._shouldAwait=a,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this);}where(e){return new t(this._collection,this._client,{...this._where,...e},this._include,this._limit,this._single,this._sort,this._shouldAwait)}include(e){return new t(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort,this._shouldAwait)}get(){let e=this._client.get({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort});return this._shouldAwait?Promise.resolve(e).then(n=>this._single?n[0]:n):this._single?e[0]:e}subscribe(e){return this._client.subscribe({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort},n=>{if(this._single)return e(n[0]);e(n);})}limit(e){return new t(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 t(this._collection,this._client,e??this._where,this._include,1,true,this._sort,this._shouldAwait)}orderBy(e,n="asc"){let i=[...this._sort??[],{key:e,direction:n}];return new t(this._collection,this._client,this._where,this._include,this._limit,this._single,i,this._shouldAwait)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}static _init(e,n,i){return new t(e,n,void 0,void 0,void 0,void 0,void 0,i??false)}};var E=(t,e,n=[])=>new Proxy(t,{get:(i,r)=>{var a,d;if(r==="__isProxy__")return true;let o=(a=e.get)==null?void 0:a.call(e,i,[...n,r]);if(o!==void 0)return o;let s=i,l=r;return (d=s[l])!=null&&d.__isProxy__||(s[l]=E(typeof s[l]=="object"?s[l]:()=>{},e,[...n,r])),s[l]},apply:(i,r,o)=>{var s;return (s=e.apply)==null?void 0:s.call(e,i,n,o)}}),D=(t,e,n)=>{let i=[],r=0;for(let o=0;o<t.length&&(n===void 0||r<n);o++)e(t[o],o)&&(i.push(t[o]),r++);return i};export{b as a,A as b,T as c,E as d,D as e};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { d as Client, c as ClientEvents, C as ClientOptions, b as ConnectionStateChangeEvent, M as MessageReceivedEvent, S as SubscriptionProvider, e as createClient, u as useLiveQuery } from './index-Y5wSNhd8.js';
|
|
2
2
|
import 'react/jsx-runtime';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'zod/v3';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {c,a,e,d,b}from'./chunk-RWM6TXG7.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {jsx,Fragment}from'react/jsx-runtime';import {z as z$1}from'zod';import {stringify}from'qs';import se from'fast-deep-equal';import {openDB}from'idb';var y=c=>xxHash32(JSON.stringify(c)).toString(32),g=(c,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(n=>g(c,n,t));if(i==="$or")return s.some(n=>g(c,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 n=c[i];return n===void 0?false:t?!s.$in.includes(n):s.$in.includes(n)}if(s.$not!==void 0&&!t)return g(c,{[i]:s.$not},true);if(s.$gt!==void 0){let n=c[i];return typeof n!="number"?false:t?n<=s.$gt:n>s.$gt}if(s.$gte!==void 0){let n=c[i];return typeof n!="number"?false:t?n<s.$gte:n>=s.$gte}if(s.$lt!==void 0){let n=c[i];return typeof n!="number"?false:t?n>=s.$lt:n<s.$lt}if(s.$lte!==void 0){let n=c[i];return typeof n!="number"?false:t?n>s.$lte:n<=s.$lte}return !c[i]||typeof c[i]!="object"?false:g(c[i],s,t)}return t?c[i]!==r:c[i]===r});var C=class{subscriptions=new Map;getOrStoreSubscription(e){let t=y(e);return this.subscriptions.has(t)?this.subscriptions.get(t).subscribe:(this.subscriptions.set(t,{subscribe:i=>{var r;(r=this.subscriptions.get(t))==null||r.callbacks.add(i);let s=e.subscribe(()=>{var n;(n=this.subscriptions.get(t))==null||n.callbacks.forEach(o=>{o();});});return ()=>{var n;(n=this.subscriptions.get(t))==null||n.callbacks.delete(i),setTimeout(()=>{var o;((o=this.subscriptions.get(t))==null?void 0:o.callbacks.size)===0&&(this.subscriptions.delete(t),s());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},N=new C,ce=c=>useSyncExternalStore(N.getOrStoreSubscription(c),c.get),le=({children:c,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:c}));var Q=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.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),R=z$1.record(z$1.string(),z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()).nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})).superRefine((c,e)=>{c.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),z=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),j=z.extend({procedure:z$1.string(),payload:z$1.any().optional()}),k=z.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:R});z$1.union([k,j]);var v=z$1.string(),Y=z$1.object({id:v,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),F=Q.extend({id:v,type:z$1.literal("QUERY")}),B=k.extend({id:v}),Z=j.extend({id:v}),X=z$1.union([Z,B]);z$1.union([Y,F,X]);var ee=z$1.object({id:v,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),te=z$1.object({id:v,type:z$1.literal("REPLY"),data:z$1.any()}),$=z$1.union([ee,te,B]),G=z$1.object({resource:z$1.string(),data:z$1.record(z$1.string(),R)});var S=class c{_collection;_client;_where;_include;_limit;_single;_sort;constructor(e,t,i,s,r,n,o){this._collection=e,this._client=t,this._where=i??{},this._include=s??{},this._limit=r,this._single=n,this._sort=o,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)}include(e){return new c(this._collection,this._client,this._where,{...this._include,...e},this._limit,this._single,this._sort)}get(){let e=this._client.get({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort});return this._single?e[0]:e}subscribe(e){return this._client.subscribe({resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort},t=>{if(this._single)return e(t[0]);e(t);})}limit(e){return new c(this._collection,this._client,this._where,this._include,e,this._single,this._sort)}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)}orderBy(e,t="asc"){let i=[...this._sort??[],{key:e,direction:t}];return new c(this._collection,this._client,this._where,this._include,this._limit,this._single,i)}toJSON(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}static _init(e,t){return new c(e,t)}};var w=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 b(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 M=class{nodes;constructor(){this.nodes=new Map;}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=>{try{i(e);}catch(s){console.error(`Error in node subscription for node ${e}:`,s);}});}getAllNodes(){return Array.from(this.nodes.values())}};var x="__meta",T="databases",E=class{db;async init(e,t){var d,h;if(typeof window>"u")return;let s=((d=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:d.version)??1,r=await y(e),n=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,f])=>[u,await y(f)]))),o=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(T)||u.createObjectStore(T);}}),a=(h=await this.getAll(o,T))==null?void 0:h[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(u){[...Object.keys(e),x].forEach(f=>{(a==null?void 0:a.objectHashes[f])!==n[f]&&u.objectStoreNames.contains(f)&&u.deleteObjectStore(f),u.objectStoreNames.contains(f)||u.createObjectStore(f);}),await o.put(T,{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(x,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(x,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 O=class{constructor(e,t,i){this.schema=e;this.kvStorage=new E,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{this.kvStorage.getMeta("mutationStack").then(s=>{!s||Object.keys(s).length===0||(this.optimisticMutationStack=s,i==null||i(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([s,r])=>{this.kvStorage.get(s).then(n=>{!n||Object.keys(n).length===0||this.loadConsolidatedState(s,n);});});}).catch(s=>{console.error("Failed to load state from storage",s);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new M;optimisticRawObjPool={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var n;let s=t??y(e$1);if(this.querySnapshots[s]&&!i){let o=this.querySnapshots[s];if(o)return o}let r=((n=e$1.where)!=null&&n.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(o=>{let a=e(this.materializeOneWithInclude(o,e$1.include));return a?[a]:[]});if(e$1.sort&&e$1.sort.length>0){let o=(a,d)=>{for(let h of e$1.sort){let u=a[h.key],f=d[h.key];if(u<f)return h.direction==="asc"?-1:1;if(u>f)return h.direction==="asc"?1:-1}return 0};r.sort(o);}if(e$1.where||e$1.limit){let o=e$1.where?a=>g(a,e$1.where):()=>true;r=d(r,o,e$1.limit);}return i||(this.querySnapshots[s]=r),r}subscribe(e,t){var n;let i=y(e),s=this.collectionSubscriptions.get(i),r=this.schema[e.resource];return s||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?Object.keys(e.include).map(o=>r.relations[o].entity.name):void 0}),(n=this.collectionSubscriptions.get(i))==null||n.callbacks.add(t),()=>{var o,a;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((a=this.collectionSubscriptions.get(i))==null?void 0:a.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var n,o,a;let s=this.schema[e];if(console.log("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(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let d={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=d;let h=d.value;delete h.id,this.kvStorage.set(e,t.resourceId,h);}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];console.log("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);}loadConsolidatedState(e,t){Object.entries(t).forEach(([i,s])=>{this.addMutation(e,{id:i,type:"MUTATE",resource:e,resourceId:i,procedure:"INSERT",payload:s});});}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,d)=>d.resourceId!==t?a:this.schema[e].mergeMutation("set",d.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(([d,h])=>h.type==="one"?[[h.relationalColumn,d]]:[]));Object.entries(i).forEach(([d,h])=>{let u=this.schema[e].relations[a[d]];if(!a[d])return;let f=s==null?void 0:s.value[d],[,m]=u.mergeMutation("set",h,f);if(m){if(!this.optimisticObjGraph.hasNode(m.value)){let L=u.entity.name;this.optimisticObjGraph.createNode(m.value,L,Object.values(this.schema[L].relations).flatMap(A=>A.type==="many"?[A.entity.name]:[]));}f!=null&&f.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.keys(t).reduce((d,h)=>{let u=this.schema[s].relations[h];return u.type==="one"?d[0].push([h,u.entity.name]):u.type==="many"&&d[1].push([h,u.entity.name]),d},[[],[]]);return {value:{...r.value,...Object.fromEntries(n.map(([d,h])=>[d,this.materializeOneWithInclude(i.references.get(h))])),...Object.fromEntries(o.map(([d,h])=>{let u=i.referencedBy.get(h),f=u instanceof Set;return [d,f?{value:Array.from(u.values()).map(m=>this.materializeOneWithInclude(m))}:this.materializeOneWithInclude(u)]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=y(t.query),s=this.querySnapshots[i],r=this.get(t.query,void 0,true);if(se(r,s))return;this.querySnapshots[i]=r,t.callbacks.forEach(n=>{n(r);});}});}};var _=class{url;ws;store;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){this.url=e.url,this.store=new O(e.schema,e.storage,t=>{var i,s;(s=(i=Object.values(t))==null?void 0:i.flat())==null||s.forEach(r=>{this.sendWsMessage(r);});}),this.ws=new w({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3,credentials:e.credentials}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:t.open}),t.open&&(Object.keys(this.store.schema).forEach(i=>{this.sendWsMessage({id:a(),type:"QUERY",resource:i});}),Object.entries(this.remoteSubCounters).forEach(([i,s])=>{s>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:i});}),Object.values(this.store.optimisticMutationStack).forEach(i=>{i&&i.forEach(s=>{this.sendWsMessage(s);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=$.parse(JSON.parse(e));if(console.log("Parsed message:",t),this.emitEvent({type:"MESSAGE_RECEIVED",message:t}),t.type==="MUTATE"){let{resource:i}=t;try{this.store.addMutation(i,t);}catch(s){console.error("Error merging mutation from the server:",s);}}else if(t.type==="REJECT")this.store.undoMutation(t.resource,t.id);else if(t.type==="REPLY"){let{id:i,data:s}=t;if(this.replyHandlers[i]){clearTimeout(this.replyHandlers[i].timeoutHandle),this.replyHandlers[i].handler(s);return}let r=G.parse(s);this.store.loadConsolidatedState(r.resource,r.data);}}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.remoteSubCounters[e]=(this.remoteSubCounters[e]??0)+1,this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:e}),()=>{this.remoteSubCounters[e]-=1,this.remoteSubCounters[e];}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var n;let r={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i};(n=this.store)==null||n.addMutation(e,r,true),this.sendWsMessage(r);}genericMutate(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let s={id:a(),type:"MUTATE",resource:e,procedure:t,payload: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);}};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},Be=c$1=>{let e=new _(c$1);return {client:{ws:e.ws,subscribe:t=>{let i=[];for(let s of t??Object.keys(e.store.schema))i.push(e.subscribeToRemote(s));return ()=>{console.log("Removing listeners",i),i.forEach(s=>{s();});}},addEventListener:t=>e.addEventListener(t)},store:{query:Object.entries(c$1.schema).reduce((t,[i,s])=>(t[i]=S._init(s,e),t),{}),mutate:c(()=>{},{apply:(t,i,s)=>{if(i.length<2)return;if(i.length>2)throw new Error("Trying to access an invalid path");let[r,n]=i;if(n==="insert"){let{id:o,...a}=s[0];return e.mutate(r,o,"INSERT",a)}if(n==="update"){let[o,a]=s;return e.mutate(r,o,"UPDATE",a)}return e.genericMutate(r,n,s[0])}})}}};export{le as SubscriptionProvider,Be as createClient,ce as useLiveQuery};
|
|
1
|
+
import {d,c,a,e,b as b$1}from'./chunk-VYWZ6RGP.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {jsx,Fragment}from'react/jsx-runtime';import {z}from'zod';import {stringify}from'qs';import pe from'fast-deep-equal';import {openDB}from'idb';var m=a=>xxHash32(JSON.stringify(a)).toString(32),b=(a,e,t=false)=>Object.entries(e).every(([i,n])=>{if(i==="$and")return n.every(r=>b(a,r,t));if(i==="$or")return n.some(r=>b(a,r,t));let s=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let r=a[i];return r===void 0?false:t?!n.$in.includes(r):n.$in.includes(r)}if(n.$not!==void 0&&!t)return b(a,{[i]:n.$not},true);if(n.$gt!==void 0){let r=a[i];return typeof r!="number"?false:t?r<=n.$gt:r>n.$gt}if(n.$gte!==void 0){let r=a[i];return typeof r!="number"?false:t?r<n.$gte:r>=n.$gte}if(n.$lt!==void 0){let r=a[i];return typeof r!="number"?false:t?r>=n.$lt:r<n.$lt}if(n.$lte!==void 0){let r=a[i];return typeof r!="number"?false:t?r>n.$lte:r<=n.$lte}return !a[i]||typeof a[i]!="object"?false:b(a[i],n,t)}return t?a[i]!==s:a[i]===s});var j=class{subscriptions=new Map;getOrStoreSubscription(e){let t=m(e);return this.subscriptions.has(t)?this.subscriptions.get(t).subscribe:(this.subscriptions.set(t,{subscribe:i=>{var s;(s=this.subscriptions.get(t))==null||s.callbacks.add(i);let n=e.subscribe(()=>{var r;(r=this.subscriptions.get(t))==null||r.callbacks.forEach(o=>{o();});});return ()=>{var r;(r=this.subscriptions.get(t))==null||r.callbacks.delete(i),setTimeout(()=>{var o;((o=this.subscriptions.get(t))==null?void 0:o.callbacks.size)===0&&(this.subscriptions.delete(t),n());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},te=new j,fe=a=>useSyncExternalStore(te.getOrStoreSubscription(a),a.get),Te=({children:a,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:a}));var B=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.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),C=z.record(z.string(),z.object({value:z.string().or(z.number()).or(z.boolean()).or(z.date()).nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})).superRefine((a,e)=>{a.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),U=z.object({id:z.string().optional(),type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string().optional()}),A=U.extend({procedure:z.string(),payload:z.any().optional()}),I=U.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:C});z.union([I,A]);var g=z.string(),re=z.object({id:g,type:z.literal("SUBSCRIBE"),resource:z.string()}),se=B.extend({id:g,type:z.literal("QUERY")}),H=I.extend({id:g}),ae=A.extend({id:g}),oe=z.union([ae,H]);z.union([re,se,oe]);var ce=z.object({id:g,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),le=z.object({id:g,type:z.literal("REPLY"),data:z.any()}),Q=z.union([ce,le,H]),J=z.object({resource:z.string(),data:z.record(z.string(),C)});var R=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 b$1(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(n=>{n(t);});}};var w=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>w(e)):typeof a.value!="object"||a.value===null||a.value instanceof Date?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,w(t)]))};var x=class{nodes;constructor(){this.nodes=new Map;}createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let n={id:e,type:t,referencedBy:new Map(i.map(s=>[s,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,n),n}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),n=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!n)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n.type,t);let s=n.referencedBy.get(i.type);s&&s instanceof Set?s.add(e):n.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 n=i.references.get(t);if(!n)return;i.references.delete(t);let s=this.nodes.get(n);if(!s)return;let r=s.referencedBy.get(i.type);r&&(r instanceof Set?r.delete(e):s.referencedBy.delete(i.type),this.notifySubscribers(n)),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,n])=>{(n instanceof Set?Array.from(n.values()):[n]).forEach(r=>{let o=this.nodes.get(r);!o||!o.references.get(i)||(o.references.delete(i),this.notifySubscribers(r));});}),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=>{try{i(e);}catch(n){console.error(`Error in node subscription for node ${e}:`,n);}});}getAllNodes(){return Array.from(this.nodes.values())}};var D="__meta",L="databases",O=class{db;async init(e,t){var p,d;if(typeof window>"u")return;let n=((p=(await window.indexedDB.databases()).find(u=>u.name===t))==null?void 0:p.version)??1,s=await m(e),r=Object.fromEntries(await Promise.all(Object.entries(e).map(async([u,h])=>[u,await m(h)]))),o=await openDB("live-state-databases",1,{upgrade(u){u.objectStoreNames.contains(L)||u.createObjectStore(L);}}),c=(d=await this.getAll(o,L))==null?void 0:d[t];(c==null?void 0:c.schemaHash)!==s&&n++,this.db=await openDB(t,n,{async upgrade(u){[...Object.keys(e),D].forEach(h=>{(c==null?void 0:c.objectHashes[h])!==r[h]&&u.objectStoreNames.contains(h)&&u.deleteObjectStore(h),u.objectStoreNames.contains(h)||u.createObjectStore(h);}),await o.put(L,{schemaHash:s,objectHashes:r},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 n;return (n=this.db)==null?void 0:n.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(D,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(D,t,e)}async getAll(e,t){if(!e)return;if(e.getAllRecords)return e.getAllRecords(t);let[i,n]=await Promise.all([e.getAll(t),e.getAllKeys(t)]);return Object.fromEntries(i.map((s,r)=>[n[r],s]))}};var E=class{constructor(e,t,i){this.schema=e;this.kvStorage=new O,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{this.kvStorage.getMeta("mutationStack").then(n=>{!n||Object.keys(n).length===0||(this.optimisticMutationStack=n,i==null||i(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([n,s])=>{this.kvStorage.get(n).then(r=>{!r||Object.keys(r).length===0||this.loadConsolidatedState(n,r);});});}).catch(n=>{console.error("Failed to load state from storage",n);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new x;optimisticRawObjPool={};collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var r;let n=t??m(e$1);if(this.querySnapshots[n]&&!i){let o=this.querySnapshots[n];if(o)return o}let s=((r=e$1.where)!=null&&r.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(o=>{let c=w(this.materializeOneWithInclude(o,e$1.include));return c?[c]:[]});if(e$1.sort&&e$1.sort.length>0){let o=(c,p)=>{for(let d of e$1.sort){let u=c[d.key],h=p[d.key];if(u<h)return d.direction==="asc"?-1:1;if(u>h)return d.direction==="asc"?1:-1}return 0};s.sort(o);}if(e$1.where||e$1.limit){let o=e$1.where?c=>b(c,e$1.where):()=>true;s=e(s,o,e$1.limit);}return i||(this.querySnapshots[n]=s),s}subscribe(e,t){var r;let i=m(e),n=this.collectionSubscriptions.get(i),s=this.schema[e.resource];return n||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?Object.keys(e.include).map(o=>s.relations[o].entity.name):void 0}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var o,c;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((c=this.collectionSubscriptions.get(i))==null?void 0:c.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var r,o,c;let n=this.schema[e];if(console.log("Adding mutation",t),!n)throw new Error("Schema not found");let s=(r=this.optimisticRawObjPool[e])==null?void 0:r[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((c=(o=this.optimisticMutationStack)==null?void 0:o[e])==null?void 0:c.filter(u=>u.id!==t.id))??[],this.rawObjPool[e]??={};let p={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}};this.rawObjPool[e][t.resourceId]=p;let d=p.value;delete d.id,this.kvStorage.set(e,t.resourceId,d);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,s);}undoMutation(e,t){var r,o;if(!this.optimisticMutationStack[e])return;let i=(r=this.optimisticMutationStack[e])==null?void 0:r.findIndex(c=>c.id===t);if(i===-1)return;let n=this.optimisticMutationStack[e][i];console.log("Removing mutation",n);let s=(o=this.optimisticRawObjPool[e])==null?void 0:o[n.resourceId];this.optimisticMutationStack[e].splice(i,1),this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,n.resourceId,Object.fromEntries(Object.entries(n.payload).map(([c])=>[c,{value:null,_meta:{}}])),s);}loadConsolidatedState(e,t){Object.entries(t).forEach(([i,n])=>{this.addMutation(e,{id:i,type:"MUTATE",resource:e,resourceId:i,procedure:"INSERT",payload:n});});}updateRawObjPool(e,t,i,n){var o;if(!this.schema[e])return;let s=(o=this.rawObjPool[e])==null?void 0:o[t],r=(this.optimisticMutationStack[e]??[]).reduce((c,p)=>p.resourceId!==t?c:this.schema[e].mergeMutation("set",p.payload,c)[0],s);if(this.optimisticRawObjPool[e]??={},r?this.optimisticRawObjPool[e][t]={value:{...r.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!r)){if(this.optimisticObjGraph.hasNode(t)||this.optimisticObjGraph.createNode(t,e,Object.values(this.schema[e].relations).flatMap(c=>c.type==="many"?[c.entity.name]:[])),Object.keys(this.schema[e].relations).length>0){let c=Object.fromEntries(Object.entries(this.schema[e].relations).flatMap(([p,d])=>d.type==="one"?[[d.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,d])=>{let u=this.schema[e].relations[c[p]];if(!c[p])return;let h=n==null?void 0:n.value[p],[,T]=u.mergeMutation("set",d,h);if(T){if(!this.optimisticObjGraph.hasNode(T.value)){let $=u.entity.name;this.optimisticObjGraph.createNode(T.value,$,Object.values(this.schema[$].relations).flatMap(q=>q.type==="many"?[q.entity.name]:[]));}h!=null&&h.value&&this.optimisticObjGraph.removeLink(t,u.entity.name),this.optimisticObjGraph.createLink(t,T.value);}});}this.notifyCollectionSubscribers(e),this.optimisticObjGraph.notifySubscribers(t);}}materializeOneWithInclude(e,t={}){var c;if(!e)return;let i=this.optimisticObjGraph.getNode(e);if(!i)return;let n=i.type,s=(c=this.optimisticRawObjPool[n])==null?void 0:c[e];if(!s)return;let[r,o]=Object.keys(t).reduce((p,d)=>{let u=this.schema[n].relations[d];return u.type==="one"?p[0].push([d,u.entity.name]):u.type==="many"&&p[1].push([d,u.entity.name]),p},[[],[]]);return {value:{...s.value,...Object.fromEntries(r.map(([p,d])=>[p,this.materializeOneWithInclude(i.references.get(d))])),...Object.fromEntries(o.map(([p,d])=>{let u=i.referencedBy.get(d),h=u instanceof Set;return [p,h?{value:Array.from(u.values()).map(T=>this.materializeOneWithInclude(T))}:this.materializeOneWithInclude(u)]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=m(t.query),n=this.querySnapshots[i],s=this.get(t.query,void 0,true);if(pe(s,n))return;this.querySnapshots[i]=s,t.callbacks.forEach(r=>{r(s);});}});}};var W=class{url;ws;store;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){this.url=e.url,this.store=new E(e.schema,e.storage,t=>{var i,n;(n=(i=Object.values(t))==null?void 0:i.flat())==null||n.forEach(s=>{this.sendWsMessage(s);});}),this.ws=new R({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3,credentials:e.credentials}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:t.open}),t.open&&(Object.keys(this.store.schema).forEach(i=>{this.sendWsMessage({id:a(),type:"QUERY",resource:i});}),Object.entries(this.remoteSubCounters).forEach(([i,n])=>{n>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:i});}),Object.values(this.store.optimisticMutationStack).forEach(i=>{i&&i.forEach(n=>{this.sendWsMessage(n);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=Q.parse(JSON.parse(e));if(console.log("Parsed message:",t),this.emitEvent({type:"MESSAGE_RECEIVED",message:t}),t.type==="MUTATE"){let{resource:i}=t;try{this.store.addMutation(i,t);}catch(n){console.error("Error merging mutation from the server:",n);}}else if(t.type==="REJECT")this.store.undoMutation(t.resource,t.id);else if(t.type==="REPLY"){let{id:i,data:n}=t;if(this.replyHandlers[i]){clearTimeout(this.replyHandlers[i].timeoutHandle),this.replyHandlers[i].handler(n);return}let s=J.parse(n);this.store.loadConsolidatedState(s.resource,s.data);}}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.remoteSubCounters[e]=(this.remoteSubCounters[e]??0)+1,this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:e}),()=>{this.remoteSubCounters[e]-=1,this.remoteSubCounters[e];}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,n){var r;let s={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",n,new Date().toISOString()),resourceId:t,procedure:i};(r=this.store)==null||r.addMutation(e,s,true),this.sendWsMessage(s);}genericMutate(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let n={id:a(),type:"MUTATE",resource:e,procedure:t,payload:i};return this.sendWsMessage(n),new Promise((s,r)=>{this.replyHandlers[n.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[n.id],r(new Error("Reply timeout"));},5e3),handler:o=>{delete this.replyHandlers[n.id],s(o);}};})}addEventListener(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e);}}sendWsMessage(e){var t;(t=this.ws)!=null&&t.connected()&&this.ws.send(JSON.stringify(e));}emitEvent(e){this.eventListeners.forEach(t=>{t(e);});}},ot=a=>{let e=new W(a);return {client:{ws:e.ws,subscribe:t=>{let i=[];for(let n of t??Object.keys(e.store.schema))i.push(e.subscribeToRemote(n));return ()=>{console.log("Removing listeners",i),i.forEach(n=>{n();});}},addEventListener:t=>e.addEventListener(t)},store:{query:Object.entries(a.schema).reduce((t,[i,n])=>(t[i]=c._init(n,e),t),{}),mutate:d(()=>{},{apply:(t,i,n)=>{if(i.length<2)return;if(i.length>2)throw new Error("Trying to access an invalid path");let[s,r]=i;if(r==="insert"){let{id:o,...c}=n[0];return e.mutate(s,o,"INSERT",c)}if(r==="update"){let[o,c]=n;return e.mutate(s,o,"UPDATE",c)}return e.genericMutate(s,r,n[0])}})}}};export{Te as SubscriptionProvider,ot as createClient,fe as useLiveQuery};
|
package/dist/fetch-client.d.ts
CHANGED
|
@@ -1,21 +1,9 @@
|
|
|
1
|
-
import { A as AnyRouter, C as ClientOptions,
|
|
1
|
+
import { A as AnyRouter, C as ClientOptions, a as Client } from './index-Y5wSNhd8.js';
|
|
2
2
|
import 'react/jsx-runtime';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import 'zod/v3';
|
|
5
5
|
import 'zod/v4/core';
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
headers?: Record<string, string>;
|
|
9
|
-
where?: WhereClause<T>;
|
|
10
|
-
include?: IncludeClause<T>;
|
|
11
|
-
};
|
|
12
|
-
type FetchClient<TRouter extends AnyRouter> = {
|
|
13
|
-
[K in keyof TRouter["routes"]]: {
|
|
14
|
-
get: (opts?: GetOptions<TRouter["routes"][K]["_resourceSchema"]>) => Promise<Record<string, Simplify<InferLiveObject<TRouter["routes"][K]["_resourceSchema"]>>>>;
|
|
15
|
-
insert: (input: Simplify<InferInsert<TRouter["routes"][K]["_resourceSchema"]>>) => Promise<void>;
|
|
16
|
-
update: (id: string, input: Simplify<InferUpdate<TRouter["routes"][K]["_resourceSchema"]>>) => Promise<void>;
|
|
17
|
-
};
|
|
18
|
-
};
|
|
19
|
-
declare const createClient: <TRouter extends AnyRouter>(opts: Omit<ClientOptions, "storage">) => FetchClient<TRouter>;
|
|
7
|
+
declare const createClient: <TRouter extends AnyRouter>(opts: Omit<ClientOptions, "storage">) => Client<TRouter, true>;
|
|
20
8
|
|
|
21
9
|
export { createClient };
|
package/dist/fetch-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {d,b,c}from'./chunk-VYWZ6RGP.js';import {stringify}from'qs';var i=async(...e)=>{let n=await fetch(...e),t;try{t=await n.json();}catch{t=await n.text().catch(()=>{});}if(!n.ok)throw new Error(`Failed to fetch: ${n.status} ${n.statusText}`,{cause:t});return t},$=e=>{let n={get:async t=>{let r=stringify(t),o=await b(e.credentials)??{};return await i(`${e.url}/${t.resource}${r?`?${r}`:""}`,{headers:{...o,"Content-Type":"application/json"}})},subscribe:()=>{throw new Error("Fetch client does not support subscriptions")}};return {query:Object.entries(e.schema).reduce((t,[r,o])=>(t[r]=c._init(o,n,true),t),{}),mutate:d(()=>{},{apply:async(t,r,o)=>{if(r.length<2)return;if(r.length>2)throw new Error("Trying to access an invalid path");let[a,s]=r,u=await b(e.credentials)??{};if(s==="insert"){let{id:c,...y}=o[0];return i(`${e.url}/${a}/insert`,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({resourceId:c,payload:e.schema[a].encodeMutation("set",y,new Date().toISOString())})})}if(s==="update"){let[c,y]=o,{id:h,...m}=y;return i(`${e.url}/${a}/update`,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({resourceId:c,payload:e.schema[a].encodeMutation("set",m,new Date().toISOString())})})}return i(`${e.url}/${a}/${s}`,{method:"POST",headers:{...u,"Content-Type":"application/json"},body:JSON.stringify({payload:o[0]})})}})}};export{$ as createClient};
|
|
@@ -4,6 +4,7 @@ import * as z3 from 'zod/v3';
|
|
|
4
4
|
import * as z4 from 'zod/v4/core';
|
|
5
5
|
|
|
6
6
|
type Promisify<T> = T extends Promise<any> ? T : Promise<T>;
|
|
7
|
+
type ConditionalPromise<T, P extends boolean> = P extends true ? Promise<T> : T;
|
|
7
8
|
type Awaitable<T> = T | Promise<T>;
|
|
8
9
|
type Generatable<T, Arg = never> = T | ((arg: Arg) => T);
|
|
9
10
|
|
|
@@ -56,7 +57,7 @@ declare class NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value
|
|
|
56
57
|
type LiveAtomicTypeMeta = {
|
|
57
58
|
timestamp: string | null;
|
|
58
59
|
} & LiveTypeMeta;
|
|
59
|
-
declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
60
|
+
declare class LiveAtomicType<Value, DefaultValue = undefined> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
60
61
|
value: Value;
|
|
61
62
|
_meta: LiveAtomicTypeMeta;
|
|
62
63
|
}> {
|
|
@@ -64,10 +65,10 @@ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta,
|
|
|
64
65
|
readonly convertFunc?: (value: any) => Value;
|
|
65
66
|
readonly isIndex: boolean;
|
|
66
67
|
readonly isUnique: boolean;
|
|
67
|
-
readonly defaultValue
|
|
68
|
+
readonly defaultValue: DefaultValue;
|
|
68
69
|
readonly foreignReference?: string;
|
|
69
70
|
readonly isPrimary: boolean;
|
|
70
|
-
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?:
|
|
71
|
+
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: DefaultValue, references?: string, primary?: boolean);
|
|
71
72
|
encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
|
|
72
73
|
value: Value;
|
|
73
74
|
_meta: LiveAtomicTypeMeta;
|
|
@@ -89,16 +90,16 @@ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta,
|
|
|
89
90
|
} | null
|
|
90
91
|
];
|
|
91
92
|
getStorageFieldType(): StorageFieldType;
|
|
92
|
-
unique(): LiveAtomicType<Value>;
|
|
93
|
-
index(): LiveAtomicType<Value>;
|
|
94
|
-
default(value: Value): LiveAtomicType<Value>;
|
|
95
|
-
primary(): LiveAtomicType<Value>;
|
|
93
|
+
unique(): LiveAtomicType<Value, undefined>;
|
|
94
|
+
index(): LiveAtomicType<Value, undefined>;
|
|
95
|
+
default(value: Value): LiveAtomicType<Value, Value>;
|
|
96
|
+
primary(): LiveAtomicType<Value, undefined>;
|
|
96
97
|
nullable(): NullableLiveType<this>;
|
|
97
98
|
}
|
|
98
99
|
declare class LiveString extends LiveAtomicType<string> {
|
|
99
100
|
private constructor();
|
|
100
101
|
static create(): LiveString;
|
|
101
|
-
static createId(): LiveAtomicType<string>;
|
|
102
|
+
static createId(): LiveAtomicType<string, undefined>;
|
|
102
103
|
static createReference(foreignField: `${string}.${string}`): LiveString;
|
|
103
104
|
}
|
|
104
105
|
|
|
@@ -108,10 +109,10 @@ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
|
108
109
|
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
109
110
|
};
|
|
110
111
|
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
111
|
-
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
112
|
+
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? T["fields"][Exclude<T["relations"][K]["relationalColumn"], undefined>] extends NullableLiveType<any> ? InferLiveObject<T["relations"][K]["entity"]> | null : InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
112
113
|
} : {});
|
|
113
114
|
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
114
|
-
[K in keyof T as T[K] extends
|
|
115
|
+
[K in keyof T as T[K]["type"] extends "many" ? never : T[K]["relationalColumn"]]: T[K]["required"] extends true ? InferIndex<T[K]["entity"]> : InferIndex<T[K]["entity"]> | null;
|
|
115
116
|
};
|
|
116
117
|
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
117
118
|
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
@@ -216,7 +217,13 @@ type WhereClause<T extends LiveObjectAny> = ({
|
|
|
216
217
|
type IncludeClause<T extends LiveObjectAny> = {
|
|
217
218
|
[K in keyof T["relations"]]?: boolean;
|
|
218
219
|
};
|
|
219
|
-
type
|
|
220
|
+
type GetFieldType<T> = T extends NullableLiveType<any> ? T["inner"] : T;
|
|
221
|
+
type HasDefaultValue<T> = T extends LiveAtomicType<any, undefined> ? false : true;
|
|
222
|
+
type InferInsert<T extends LiveObjectAny> = {
|
|
223
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends true ? never : K]: InferLiveType<T["fields"][K]>;
|
|
224
|
+
} & {
|
|
225
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends false ? never : K]?: InferLiveType<T["fields"][K]>;
|
|
226
|
+
};
|
|
220
227
|
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
221
228
|
|
|
222
229
|
type Simplify<T> = T extends Record<string, unknown> ? {
|
|
@@ -361,7 +368,7 @@ type ServerMessage = z.infer<typeof serverMessageSchema>;
|
|
|
361
368
|
/** biome-ignore-all lint/complexity/noBannedTypes: <explanation> */
|
|
362
369
|
|
|
363
370
|
type InferQueryResult<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection>, TSingle extends boolean = false> = TSingle extends true ? Simplify<InferLiveObject<TCollection, TInclude>> | undefined : Simplify<InferLiveObject<TCollection, TInclude>>[];
|
|
364
|
-
declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false> {
|
|
371
|
+
declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false, TShouldAwait extends boolean = false> {
|
|
365
372
|
private _collection;
|
|
366
373
|
private _client;
|
|
367
374
|
private _where;
|
|
@@ -369,15 +376,16 @@ declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends I
|
|
|
369
376
|
private _limit?;
|
|
370
377
|
private _single?;
|
|
371
378
|
private _sort?;
|
|
379
|
+
private _shouldAwait?;
|
|
372
380
|
private constructor();
|
|
373
|
-
where(where: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, TSingle>;
|
|
374
|
-
include<TNewInclude extends IncludeClause<TCollection>>(include: TNewInclude): QueryBuilder<TCollection, TInclude & TNewInclude, TSingle>;
|
|
375
|
-
get(): InferQueryResult<TCollection, TInclude, TSingle>;
|
|
381
|
+
where(where: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
382
|
+
include<TNewInclude extends IncludeClause<TCollection>>(include: TNewInclude): QueryBuilder<TCollection, TInclude & TNewInclude, TSingle, TShouldAwait>;
|
|
383
|
+
get(): ConditionalPromise<InferQueryResult<TCollection, TInclude, TSingle>, TShouldAwait>;
|
|
376
384
|
subscribe(callback: (value: InferQueryResult<TCollection, TInclude, TSingle>) => void): () => void;
|
|
377
|
-
limit(limit: number): QueryBuilder<TCollection, TInclude, TSingle>;
|
|
378
|
-
one(id: string): QueryBuilder<TCollection, TInclude, true>;
|
|
379
|
-
first(where?: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, true>;
|
|
380
|
-
orderBy(key: keyof TCollection["fields"], direction?: "asc" | "desc"): QueryBuilder<TCollection, TInclude, TSingle>;
|
|
385
|
+
limit(limit: number): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
386
|
+
one(id: string): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
387
|
+
first(where?: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
388
|
+
orderBy(key: keyof TCollection["fields"], direction?: "asc" | "desc"): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
381
389
|
toJSON(): {
|
|
382
390
|
resource: string;
|
|
383
391
|
where: WhereClause<TCollection>;
|
|
@@ -390,14 +398,14 @@ declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends I
|
|
|
390
398
|
};
|
|
391
399
|
}
|
|
392
400
|
|
|
393
|
-
type Client$1<TRouter extends AnyRouter> = {
|
|
401
|
+
type Client$1<TRouter extends AnyRouter, TShouldAwait extends boolean = false> = {
|
|
394
402
|
query: {
|
|
395
|
-
[K in keyof TRouter["routes"]]: QueryBuilder<TRouter["routes"][K]["_resourceSchema"]>;
|
|
403
|
+
[K in keyof TRouter["routes"]]: QueryBuilder<TRouter["routes"][K]["_resourceSchema"], {}, false, TShouldAwait>;
|
|
396
404
|
};
|
|
397
405
|
mutate: {
|
|
398
406
|
[K in keyof TRouter["routes"]]: {
|
|
399
|
-
insert: (input: Simplify<InferInsert<TRouter["routes"][K]["_resourceSchema"]>>) => void
|
|
400
|
-
update: (id: string, value: Simplify<InferUpdate<TRouter["routes"][K]["_resourceSchema"]>>) => void
|
|
407
|
+
insert: (input: Simplify<InferInsert<TRouter["routes"][K]["_resourceSchema"]>>) => ConditionalPromise<void, TShouldAwait>;
|
|
408
|
+
update: (id: string, value: Simplify<InferUpdate<TRouter["routes"][K]["_resourceSchema"]>>) => ConditionalPromise<void, TShouldAwait>;
|
|
401
409
|
} & {
|
|
402
410
|
[K2 in keyof TRouter["routes"][K]["customMutations"]]: (input: z.infer<TRouter["routes"][K]["customMutations"][K2]["inputValidator"]>) => Promisify<ReturnType<TRouter["routes"][K]["customMutations"][K2]["handler"]>>;
|
|
403
411
|
};
|
|
@@ -471,4 +479,4 @@ type ClientOptions = {
|
|
|
471
479
|
} | false;
|
|
472
480
|
};
|
|
473
481
|
|
|
474
|
-
export { type AnyRouter as A, type ClientOptions as C, type
|
|
482
|
+
export { type AnyRouter as A, type ClientOptions as C, type MessageReceivedEvent as M, SubscriptionProvider as S, type Client$1 as a, type ConnectionStateChangeEvent as b, type ClientEvents as c, type Client as d, createClient as e, useLiveQuery as u };
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var s=class{_value;_meta;_encodeInput;_decodeInput};var c=class extends s{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,t,n){return this.inner.encodeMutation(e,t,n)}mergeMutation(e,t,n){return this.inner.mergeMutation(e,t,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class i extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,t,n,r,a,u,y){super(),this.storageType=e,this.convertFunc=t,this.isIndex=n??false,this.isUnique=r??false,this.defaultValue=a,this.foreignReference=u,this.isPrimary=y??false;}encodeMutation(e,t,n){return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){return n&&n._meta.timestamp&&t._meta.timestamp&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(t.value):t.value,_meta:t._meta},t]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new i(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new i(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new i(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new i(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}nullable(){return new c(this)}},p=class i extends l{constructor(){super("integer",e=>Number(e));}static create(){return new i}},b=p.create,o=class i extends l{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new i}static createId(){return new i().index().unique().primary()}static createReference(e){return new i(e)}},g=o.create,I=o.createId,M=o.createReference,d=class i extends l{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new i}},O=d.create,m=class i extends l{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new i}},j=m.create;var f=class i extends s{name;fields;relations;constructor(e,t,n){super(),this.name=e,this.fields=t,this.relations=n??{};}encodeMutation(e,t,n){return Object.fromEntries(Object.entries(t).map(([r,a])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",a,n)]))}mergeMutation(e,t,n){let r={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(t).map(([a,u])=>{let y=this.fields[a]??this.relations[a];if(!y)return [a,u];let[h,v]=y.mergeMutation(e,u,n==null?void 0:n.value[a]);return v&&(r[a]=v),[a,h]}))}},r]}setRelations(e){return new i(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,t){return new i(e,t)}},A=f.create,T=class i extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,t,n,r,a){super(),this.entity=e,this.type=t,this.required=a??false,this.relationalColumn=n,this.foreignColumn=r;}encodeMutation(e,t,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){if(this.type==="many")throw new Error("Many not implemented.");return n&&n._meta.timestamp&&t._meta.timestamp&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[t,t]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}toJSON(){return {entityName:this.entity.name,type:this.type,required:this.required,relationalColumn:this.relationalColumn,foreignColumn:this.foreignColumn}}static createOneFactory(){return (e,t,n)=>new i(e,"one",t,void 0,n??false)}static createManyFactory(){return (e,t,n)=>new i(e,"many",void 0,t,n??false)}},w=(i,e)=>({$type:"relations",objectName:i.name,relations:e({one:T.createOneFactory(),many:T.createManyFactory()})}),x=i=>{if(i)return Array.isArray(i.value)?i.value.map(e=>x(e)):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([e,t])=>[e,x(t)]))},V=i=>Object.fromEntries(Object.entries(i).flatMap(([e,t])=>{if(t.$type==="relations")return [];let n=t,r=Object.values(i).find(a=>a.$type==="relations"&&a.objectName===t.name);return r&&(n=n.setRelations(r.relations)),[[n.name,n]]}));exports.LiveAtomicType=l;exports.LiveBoolean=d;exports.LiveNumber=p;exports.LiveObject=f;exports.LiveString=o;exports.LiveTimestamp=m;exports.LiveType=s;exports.NullableLiveType=c;exports.Relation=T;exports.boolean=O;exports.createRelations=w;exports.createSchema=V;exports.id=I;exports.inferValue=x;exports.number=b;exports.object=A;exports.reference=M;exports.string=g;exports.timestamp=j;
|
package/dist/index.d.cts
CHANGED
|
@@ -47,7 +47,7 @@ declare class NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value
|
|
|
47
47
|
type LiveAtomicTypeMeta = {
|
|
48
48
|
timestamp: string | null;
|
|
49
49
|
} & LiveTypeMeta;
|
|
50
|
-
declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
50
|
+
declare class LiveAtomicType<Value, DefaultValue = undefined> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
51
51
|
value: Value;
|
|
52
52
|
_meta: LiveAtomicTypeMeta;
|
|
53
53
|
}> {
|
|
@@ -55,10 +55,10 @@ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta,
|
|
|
55
55
|
readonly convertFunc?: (value: any) => Value;
|
|
56
56
|
readonly isIndex: boolean;
|
|
57
57
|
readonly isUnique: boolean;
|
|
58
|
-
readonly defaultValue
|
|
58
|
+
readonly defaultValue: DefaultValue;
|
|
59
59
|
readonly foreignReference?: string;
|
|
60
60
|
readonly isPrimary: boolean;
|
|
61
|
-
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?:
|
|
61
|
+
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: DefaultValue, references?: string, primary?: boolean);
|
|
62
62
|
encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
|
|
63
63
|
value: Value;
|
|
64
64
|
_meta: LiveAtomicTypeMeta;
|
|
@@ -80,10 +80,10 @@ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta,
|
|
|
80
80
|
} | null
|
|
81
81
|
];
|
|
82
82
|
getStorageFieldType(): StorageFieldType;
|
|
83
|
-
unique(): LiveAtomicType<Value>;
|
|
84
|
-
index(): LiveAtomicType<Value>;
|
|
85
|
-
default(value: Value): LiveAtomicType<Value>;
|
|
86
|
-
primary(): LiveAtomicType<Value>;
|
|
83
|
+
unique(): LiveAtomicType<Value, undefined>;
|
|
84
|
+
index(): LiveAtomicType<Value, undefined>;
|
|
85
|
+
default(value: Value): LiveAtomicType<Value, Value>;
|
|
86
|
+
primary(): LiveAtomicType<Value, undefined>;
|
|
87
87
|
nullable(): NullableLiveType<this>;
|
|
88
88
|
}
|
|
89
89
|
declare class LiveNumber extends LiveAtomicType<number> {
|
|
@@ -94,7 +94,7 @@ declare const number: typeof LiveNumber.create;
|
|
|
94
94
|
declare class LiveString extends LiveAtomicType<string> {
|
|
95
95
|
private constructor();
|
|
96
96
|
static create(): LiveString;
|
|
97
|
-
static createId(): LiveAtomicType<string>;
|
|
97
|
+
static createId(): LiveAtomicType<string, undefined>;
|
|
98
98
|
static createReference(foreignField: `${string}.${string}`): LiveString;
|
|
99
99
|
}
|
|
100
100
|
declare const string: typeof LiveString.create;
|
|
@@ -117,10 +117,10 @@ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
|
117
117
|
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
118
118
|
};
|
|
119
119
|
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
120
|
-
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
120
|
+
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? T["fields"][Exclude<T["relations"][K]["relationalColumn"], undefined>] extends NullableLiveType<any> ? InferLiveObject<T["relations"][K]["entity"]> | null : InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
121
121
|
} : {});
|
|
122
122
|
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
123
|
-
[K in keyof T as T[K] extends
|
|
123
|
+
[K in keyof T as T[K]["type"] extends "many" ? never : T[K]["relationalColumn"]]: T[K]["required"] extends true ? InferIndex<T[K]["entity"]> : InferIndex<T[K]["entity"]> | null;
|
|
124
124
|
};
|
|
125
125
|
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
126
126
|
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
@@ -232,7 +232,13 @@ type WhereClause<T extends LiveObjectAny> = ({
|
|
|
232
232
|
type IncludeClause<T extends LiveObjectAny> = {
|
|
233
233
|
[K in keyof T["relations"]]?: boolean;
|
|
234
234
|
};
|
|
235
|
-
type
|
|
235
|
+
type GetFieldType<T> = T extends NullableLiveType<any> ? T["inner"] : T;
|
|
236
|
+
type HasDefaultValue<T> = T extends LiveAtomicType<any, undefined> ? false : true;
|
|
237
|
+
type InferInsert<T extends LiveObjectAny> = {
|
|
238
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends true ? never : K]: InferLiveType<T["fields"][K]>;
|
|
239
|
+
} & {
|
|
240
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends false ? never : K]?: InferLiveType<T["fields"][K]>;
|
|
241
|
+
};
|
|
236
242
|
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
237
243
|
|
|
238
|
-
export { type IncludeClause, type InferIndex, type InferInsert, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, type InferUpdate, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
|
|
244
|
+
export { type IncludeClause, type InferIndex, type InferInsert, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveObjectWithoutRelations, type InferLiveType, type InferUpdate, LiveAtomicType, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, NullableLiveType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
|
package/dist/index.d.ts
CHANGED
|
@@ -47,7 +47,7 @@ declare class NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value
|
|
|
47
47
|
type LiveAtomicTypeMeta = {
|
|
48
48
|
timestamp: string | null;
|
|
49
49
|
} & LiveTypeMeta;
|
|
50
|
-
declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
50
|
+
declare class LiveAtomicType<Value, DefaultValue = undefined> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
|
|
51
51
|
value: Value;
|
|
52
52
|
_meta: LiveAtomicTypeMeta;
|
|
53
53
|
}> {
|
|
@@ -55,10 +55,10 @@ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta,
|
|
|
55
55
|
readonly convertFunc?: (value: any) => Value;
|
|
56
56
|
readonly isIndex: boolean;
|
|
57
57
|
readonly isUnique: boolean;
|
|
58
|
-
readonly defaultValue
|
|
58
|
+
readonly defaultValue: DefaultValue;
|
|
59
59
|
readonly foreignReference?: string;
|
|
60
60
|
readonly isPrimary: boolean;
|
|
61
|
-
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?:
|
|
61
|
+
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: DefaultValue, references?: string, primary?: boolean);
|
|
62
62
|
encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
|
|
63
63
|
value: Value;
|
|
64
64
|
_meta: LiveAtomicTypeMeta;
|
|
@@ -80,10 +80,10 @@ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta,
|
|
|
80
80
|
} | null
|
|
81
81
|
];
|
|
82
82
|
getStorageFieldType(): StorageFieldType;
|
|
83
|
-
unique(): LiveAtomicType<Value>;
|
|
84
|
-
index(): LiveAtomicType<Value>;
|
|
85
|
-
default(value: Value): LiveAtomicType<Value>;
|
|
86
|
-
primary(): LiveAtomicType<Value>;
|
|
83
|
+
unique(): LiveAtomicType<Value, undefined>;
|
|
84
|
+
index(): LiveAtomicType<Value, undefined>;
|
|
85
|
+
default(value: Value): LiveAtomicType<Value, Value>;
|
|
86
|
+
primary(): LiveAtomicType<Value, undefined>;
|
|
87
87
|
nullable(): NullableLiveType<this>;
|
|
88
88
|
}
|
|
89
89
|
declare class LiveNumber extends LiveAtomicType<number> {
|
|
@@ -94,7 +94,7 @@ declare const number: typeof LiveNumber.create;
|
|
|
94
94
|
declare class LiveString extends LiveAtomicType<string> {
|
|
95
95
|
private constructor();
|
|
96
96
|
static create(): LiveString;
|
|
97
|
-
static createId(): LiveAtomicType<string>;
|
|
97
|
+
static createId(): LiveAtomicType<string, undefined>;
|
|
98
98
|
static createReference(foreignField: `${string}.${string}`): LiveString;
|
|
99
99
|
}
|
|
100
100
|
declare const string: typeof LiveString.create;
|
|
@@ -117,10 +117,10 @@ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
|
117
117
|
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
118
118
|
};
|
|
119
119
|
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
120
|
-
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
120
|
+
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? T["fields"][Exclude<T["relations"][K]["relationalColumn"], undefined>] extends NullableLiveType<any> ? InferLiveObject<T["relations"][K]["entity"]> | null : InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
121
121
|
} : {});
|
|
122
122
|
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
123
|
-
[K in keyof T as T[K] extends
|
|
123
|
+
[K in keyof T as T[K]["type"] extends "many" ? never : T[K]["relationalColumn"]]: T[K]["required"] extends true ? InferIndex<T[K]["entity"]> : InferIndex<T[K]["entity"]> | null;
|
|
124
124
|
};
|
|
125
125
|
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
126
126
|
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
@@ -232,7 +232,13 @@ type WhereClause<T extends LiveObjectAny> = ({
|
|
|
232
232
|
type IncludeClause<T extends LiveObjectAny> = {
|
|
233
233
|
[K in keyof T["relations"]]?: boolean;
|
|
234
234
|
};
|
|
235
|
-
type
|
|
235
|
+
type GetFieldType<T> = T extends NullableLiveType<any> ? T["inner"] : T;
|
|
236
|
+
type HasDefaultValue<T> = T extends LiveAtomicType<any, undefined> ? false : true;
|
|
237
|
+
type InferInsert<T extends LiveObjectAny> = {
|
|
238
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends true ? never : K]: InferLiveType<T["fields"][K]>;
|
|
239
|
+
} & {
|
|
240
|
+
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends false ? never : K]?: InferLiveType<T["fields"][K]>;
|
|
241
|
+
};
|
|
236
242
|
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
237
243
|
|
|
238
|
-
export { type IncludeClause, type InferIndex, type InferInsert, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, type InferUpdate, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
|
|
244
|
+
export { type IncludeClause, type InferIndex, type InferInsert, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveObjectWithoutRelations, type InferLiveType, type InferUpdate, LiveAtomicType, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, NullableLiveType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{e as LiveAtomicType,l as LiveBoolean,f as LiveNumber,p as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,d as NullableLiveType,r as Relation,m as boolean,s as createRelations,u as createSchema,j as id,t as inferValue,g as number,q as object,k as reference,i as string,o as timestamp}from'./chunk-7C33XQ3U.js';
|
package/dist/server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var Ve=require('qs'),zod=require('zod'),P=require('crypto');require('js-xxhash');var kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Ve__default=/*#__PURE__*/_interopDefault(Ve);var P__default=/*#__PURE__*/_interopDefault(P);var xe=Object.create;var Y=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var ve=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ie=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of be(e))!we.call(r,i)&&i!==t&&Y(r,i,{get:()=>e[i],enumerable:!(n=Re(e,i))||n.enumerable});return r};var X=(r,e,t)=>(t=r!=null?xe(Se(r)):{},Ie(Y(t,"default",{value:r,enumerable:true}),r));var z=ve($=>{Object.defineProperty($,"__esModule",{value:true});$.parse=$e;$.serialize=Ce;var Me=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Le=/^[\u0021-\u003A\u003C-\u007E]*$/,Ae=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ee=/^[\u0020-\u003A\u003D-\u007E]*$/,Oe=Object.prototype.toString,je=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function $e(r,e){let t=new je,n=r.length;if(n<2)return t;let i=(e==null?void 0:e.decode)||Pe,a=0;do{let s=r.indexOf("=",a);if(s===-1)break;let c=r.indexOf(";",a),o=c===-1?n:c;if(s>o){a=r.lastIndexOf(";",s-1)+1;continue}let y=ee(r,a,s),f=te(r,s,y),u=r.slice(y,f);if(t[u]===void 0){let d=ee(r,s+1,o),p=te(r,o,d),l=i(r.slice(d,p));t[u]=l;}a=o+1;}while(a<n);return t}function ee(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function te(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Ce(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Me.test(r))throw new TypeError(`argument name is invalid: ${r}`);let i=n(e);if(!Le.test(i))throw new TypeError(`argument val is invalid: ${e}`);let a=r+"="+i;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(!Ae.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Ee.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!_e(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 Pe(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function _e(r){return Oe.call(r)==="[object Date]"}});var ie=X(z());var C=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.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),V=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),ne=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),L=ne.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),A=ne.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:V});zod.z.union([A,L]);var re=C.omit({resource:true}),N=L.omit({id:true,type:true,resource:true,procedure:true}),F=A.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([F,N]);var ae=r=>async e=>{var t;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,i={headers:n,cookies:n.cookie?ie.default.parse(n.cookie):{}},a=new URL(e.url),s=a.pathname.split("/"),c=a.searchParams,o=Ve__default.default.parse(c.toString()),y=await((t=r.contextProvider)==null?void 0:t.call(r,{transport:"HTTP",headers:i.headers,cookies:i.cookies,query:o}))??{};if(e.method==="GET"){let f=s[s.length-1],{success:u,data:d,error:p}=re.safeParse(o);if(!u)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let l=await r.handleRequest({req:{...i,type:"QUERY",resourceName:f,context:y,where:d.where,include:d.include,query:o}});return !l||!l.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(l.data)}if(e.method==="POST")try{let f=s[s.length-1],u=s[s.length-2],d=e.body?await e.json():{},p;if(f==="insert"||f==="update"){let{success:h,data:g,error:R}=F.safeParse(d);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=g;}else {let{success:h,data:g,error:R}=N.safeParse(d);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=g;}let l=await r.handleRequest({req:{...i,type:"MUTATE",resourceName:u,input:p.payload,context:y,resourceId:p.resourceId,procedure:f==="insert"||f==="update"?f.toUpperCase():f,query:{}}});return Response.json(l)}catch(f){return console.error("Error parsing mutation from the client:",f),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return console.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var pe=X(z());var I=zod.z.string(),Ne=zod.z.object({id:I,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),Fe=C.extend({id:I,type:zod.z.literal("QUERY")}),oe=A.extend({id:I}),De=L.extend({id:I}),Ue=zod.z.union([De,oe]),se=zod.z.union([Ne,Fe,Ue]),Ke=zod.z.object({id:I,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),qe=zod.z.object({id:I,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Ke,qe,oe]);zod.z.object({resource:zod.z.string(),data:zod.z.record(zod.z.string(),V)});var ue="0123456789ABCDEFGHJKMNPQRSTVWXYZ",E=32;var ke=16,de=10,ce=0xffffffffffff;var S;(function(r){r.Base32IncorrectEncoding="B32_ENC_INVALID",r.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",r.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",r.EncodeTimeNegative="ENC_TIME_NEG",r.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",r.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",r.PRNGDetectFailure="PRNG_DETECT",r.ULIDInvalid="ULID_INVALID",r.Unexpected="UNEXPECTED",r.UUIDInvalid="UUID_INVALID";})(S||(S={}));var w=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function We(r){let e=Math.floor(r()*E);return e===E&&(e=E-1),ue.charAt(e)}function He(r){var n;let e=Ze(),t=e&&(e.crypto||e.msCrypto)||(typeof P__default.default<"u"?P__default.default: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((n=P__default.default)!=null&&n.randomBytes)return ()=>P__default.default.randomBytes(1).readUInt8()/255;throw new w(S.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ze(){return Qe()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Be(r,e){let t="";for(;r>0;r--)t=We(e)+t;return t}function Ge(r,e=de){if(isNaN(r))throw new w(S.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>ce)throw new w(S.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ce}: ${r}`);if(r<0)throw new w(S.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new w(S.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%E,n=ue.charAt(t)+n,r=(r-t)/E;return n}function Qe(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function le(r,e){let t=He(),n=Date.now();return Ge(n,de)+Be(ke,t)}var D=()=>le().toLowerCase();var ye=r=>{let e={},t={};return r.subscribeToMutations(n=>{let i=n;!i.resourceId||!i.payload||(console.log("Mutation propagated:",i),Object.entries(t[i.resource]??{}).forEach(([a,s])=>{var c;(c=e[a])==null||c.send(JSON.stringify({...i,id:i.id??D()}));}));}),(n,i)=>{var f;let a=u=>{n.send(JSON.stringify(u));},s=D(),c={headers:i.headers,cookies:typeof i.headers.cookie=="string"?pe.default.parse(i.headers.cookie):{}},o=Ve.parse(i.url.split("?")[1]),y=(f=r.contextProvider)==null?void 0:f.call(r,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,query:o});e[s]=n,console.log("Client connected:",s),n.on("message",async u=>{try{console.log("Message received from the client:",u);let d=se.parse(JSON.parse(u.toString()));if(d.type==="SUBSCRIBE"){let{resource:p}=d;t[p]||(t[p]={}),t[p][s]={};}else if(d.type==="QUERY"){let{resource:p}=d,l=await r.handleRequest({req:{...c,type:"QUERY",resourceName:p,context:await y??{},query:o}});if(!l||!l.data)throw new Error("Invalid resource");a({id:d.id,type:"REPLY",data:{resource:p,data:Object.fromEntries(Object.entries(l.data??{}).map(([h,g])=>[h,g.value]))}});}else if(d.type==="MUTATE"){let{resource:p}=d;console.log("Received mutation from client:",d);try{let l=await r.handleRequest({req:{...c,type:"MUTATE",resourceName:p,input:d.payload,context:{messageId:d.id,...await y??{}},resourceId:d.resourceId,procedure:d.procedure,query:o}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&a({id:d.id,type:"REPLY",data:l});}catch(l){a({id:d.id,type:"REJECT",resource:p,message:l.message}),console.error("Error parsing mutation from the client:",l);}}}catch(d){console.error("Error handling message from the client:",d);}}),n.on("close",()=>{console.log("Connection closed",s),delete e[s];for(let u of Object.values(t))delete u[s];});}};function me(r){let e=`${r.protocol}://${r.hostname}${r.url}`,t=new Headers;return Object.entries(r.headers).forEach(([n,i])=>{i&&t.set(n,Array.isArray(i)?i.join(","):i);}),new Request(e,{method:r.method,headers:t,body:r.body&&r.method!=="GET"?JSON.stringify(r.body):void 0})}var Ct=(r,e,t)=>{r.ws(`${(t==null?void 0:t.basePath)??""}/ws`,ye(e)),r.use(`${(t==null?void 0:t.basePath)??""}/`,(n,i)=>{ae(e)(me(n)).then(s=>s.json().then(c=>i.status(s.status).send(c)));});};var x=r=>{if(r)return Array.isArray(r.value)?r.value.map(e=>x(e)):typeof r.value!="object"||r.value===null||r.value instanceof Date?r.value:Object.fromEntries(Object.entries(r.value).map(([e,t])=>[e,x(t)]))};var b=(r,e,t=false)=>Object.entries(e).every(([n,i])=>{if(n==="$and")return i.every(s=>b(r,s,t));if(n==="$or")return i.some(s=>b(r,s,t));let a=(i==null?void 0:i.$eq)!==void 0?i==null?void 0:i.$eq:i;if(typeof i=="object"&&i!==null&&(i==null?void 0:i.$eq)===void 0){if(i.$in!==void 0){let s=r[n];return s===void 0?false:t?!i.$in.includes(s):i.$in.includes(s)}if(i.$not!==void 0&&!t)return b(r,{[n]:i.$not},true);if(i.$gt!==void 0){let s=r[n];return typeof s!="number"?false:t?s<=i.$gt:s>i.$gt}if(i.$gte!==void 0){let s=r[n];return typeof s!="number"?false:t?s<i.$gte:s>=i.$gte}if(i.$lt!==void 0){let s=r[n];return typeof s!="number"?false:t?s>=i.$lt:s<i.$lt}if(i.$lte!==void 0){let s=r[n];return typeof s!="number"?false:t?s>i.$lte:s<=i.$lte}return !r[n]||typeof r[n]!="object"?false:b(r[n],i,t)}return t?r[n]!==a:r[n]===a});var H=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},tn=r=>H.create({...r}),Xe=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),Z=class r{_resourceSchema;resourceName;middlewares;customMutations;authorization;constructor(e,t,n){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n;}async handleRequest(e){let t=n=>(()=>{if(n.type==="QUERY")return this.handleFind({req:n,db:e.db,schema:e.schema});if(n.type==="MUTATE"){if(!n.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[n.procedure];if(i){let a=i.inputValidator.parse(n.input);return n.input=a,i.handler({req:n,db:e.db,schema:e.schema})}else if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:e.db,schema:e.schema,operation:n.procedure})}throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>t(n))(e.req)}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new r(this.resourceName,e({mutation:Xe}))}handleFind=async({req:e,db:t})=>{var i,a;let n=(a=(i=this.authorization)==null?void 0:i.read)==null?void 0:a.call(i,{ctx:e.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await t.rawFind(e.resourceName,e.where&&n&&n!==true?{$and:[e.where,n]}:n&&n!==true?n:e.where,e.include),acceptedValues:null}};handleSet=async({req:e,db:t,schema:n,operation:i})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resourceName,e.resourceId);if(i==="INSERT"&&a)throw new Error("Resource already exists");if(i==="UPDATE"&&!a)throw new Error("Resource not found");return t.transaction(async({trx:s})=>{var f,u,d,p,l;let[c,o]=n[this.resourceName].mergeMutation("set",e.input,a);if(!o)throw new Error("Mutation rejected");if(i==="INSERT"){let h=await s.rawInsert(e.resourceName,e.resourceId,c);if((f=this.authorization)!=null&&f.insert){let g=x(h);g.id=g.id??e.resourceId;let R=this.authorization.insert({ctx:e.context,value:g});if(!(typeof R=="boolean"?R:b(g,R)))throw new Error("Not authorized")}return {data:h,acceptedValues:o}}if((d=(u=this.authorization)==null?void 0:u.update)!=null&&d.preMutation){let h=x(a);h.id=h.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:h});if(!(typeof g=="boolean"?g:b(h,g)))throw new Error("Not authorized")}let y=await s.rawUpdate(e.resourceName,e.resourceId,c);if((l=(p=this.authorization)==null?void 0:p.update)!=null&&l.postMutation){let h=x(y);h.id=h.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:h});if(!(typeof g=="boolean"?g:b(h,g)))throw new Error("Not authorized")}return {data:y,acceptedValues:o}})}},B=class r{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Z(e.name,void 0,t).use(...this.middlewares)}use(...e){return new r([...this.middlewares,...e])}static create(){return new r}},nn=B.create;var j=class{async insert(e,t){let n=new Date().toISOString();return x(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([i,a])=>[i,{value:a,_meta:{timestamp:n}}]))}))}async update(e,t,n){let i=new Date().toISOString(),{id:a,...s}=n;return x(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(s).map(([c,o])=>[c,{value:o,_meta:{timestamp:i}}]))}))}};function _(r,e,t,n){if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error("Resource not found");let a=n.$or,s=n.$and;return (a?t.or:t.and)(a?n.$or.map(c=>_(r,e,t,c)):s?n.$and.map(c=>_(r,e,t,c)):Object.entries(n).map(([c,o])=>{var y,f;if(i.fields[c])return (o==null?void 0:o.$eq)!==void 0?t(`${e}.${c}`,o.$eq===null?"is":"=",o.$eq):(o==null?void 0:o.$in)!==void 0?t(`${e}.${c}`,"in",o.$in):(o==null?void 0:o.$not)!==void 0?((y=o==null?void 0:o.$not)==null?void 0:y.$in)!==void 0?t(`${e}.${c}`,"not in",o.$not.$in):((f=o==null?void 0:o.$not)==null?void 0:f.$eq)!==void 0?t(`${e}.${c}`,o.$not.$eq===null?"is not":"!=",o.$not.$eq):t(`${e}.${c}`,o.$not===null?"is not":"!=",o.$not):(o==null?void 0:o.$gt)!==void 0?t(`${e}.${c}`,">",o.$gt):(o==null?void 0:o.$gte)!==void 0?t(`${e}.${c}`,">=",o.$gte):(o==null?void 0:o.$lt)!==void 0?t(`${e}.${c}`,"<",o.$lt):(o==null?void 0:o.$lte)!==void 0?t(`${e}.${c}`,"<=",o.$lte):t(`${e}.${c}`,o===null?"is":"=",o);if(i.relations[c]){let u=i.relations[c],d=u.entity.name;u.type==="one"?"id":u.foreignColumn;u.type==="one"?u.relationalColumn:"id";return _(r,d,t,o)}return null}).filter(Boolean))}function tt(r,e,t,n){let i=r[e];if(!i)throw new Error("Resource not found");if(!n)return t;for(let a of Object.keys(n)){if(!i.relations[a])continue;let s=i.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(c,`${c}.${o}`,`${e}.${y}`);}return t}function Te(r,e,t,n){return !n||Object.keys(n).length===0?t:(t=tt(r,e,t,n),t.where(i=>_(r,e,i,n)))}function G(r,e,t,n){if(!n)return t;if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(n)){if(!i.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let s=i.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id",f=s.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom;t=t.select(u=>f(u.selectFrom(c).selectAll(c).whereRef(`${c}.${o}`,"=",`${e}.${y}`).select(d=>postgres.jsonObjectFrom(d.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"))).as(a));}return t}var Q=class r extends j{db;schema;constructor(e,t){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,i]of Object.entries(e)){let a=t.find(o=>o.name===n);a||await this.db.schema.createTable(n).ifNotExists().execute();let s=`${n}_meta`,c=t.find(o=>o.name===s);c||await this.db.schema.createTable(s).ifNotExists().execute();for(let[o,y]of Object.entries(i.fields)){let f=a==null?void 0:a.columns.find(p=>p.name===o),u=y.getStorageFieldType();f?f.dataType!==u.type&&console.error("Column type mismatch:",o,"expected to have type:",u.type,"but has type:",f.dataType):(await this.db.schema.alterTable(n).addColumn(o,u.type,p=>{let l=p;return u.unique&&(l=l.unique()),u.nullable||(l=l.notNull()),u.references&&(l=l.references(u.references)),u.primary&&(l=l.primaryKey()),u.default!==void 0&&(l=l.defaultTo(u.default)),l}).execute().catch(p=>{throw console.error("Error adding column",o,p),p}),u.index&&await this.db.schema.createIndex(`${n}_${o}_index`).on(n).column(o).execute().catch(p=>{})),(c==null?void 0:c.columns.find(p=>p.name===o))||await this.db.schema.alterTable(s).addColumn(o,"varchar",p=>{let l=p;return u.primary&&(l=l.primaryKey().references(`${n}.${o}`)),l}).execute();}}}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let i=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>postgres.jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));i=G(this.schema,e,i,n);let a=await i.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,n){let i=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(i)return x(i)}async rawFind(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let i=this.db.selectFrom(e).selectAll(e).select(o=>postgres.jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));i=Te(this.schema,e,i,t),i=G(this.schema,e,i,n);let a=await i.execute(),s=Object.fromEntries(a.map(o=>{let{id:y,...f}=o;return [y,f]}));return Object.keys(s).length===0?{}:Object.entries(s).reduce((o,[y,f])=>(o[y]=this.convertToMaterializedLiveType(f),o),{})}async find(e,t){let n=await this.rawFind(e.name,t==null?void 0:t.where,t==null?void 0:t.include);return Object.fromEntries(Object.entries(n).map(([i,a])=>[i,x(a)]))}async rawInsert(e,t,n){var s;let i={},a={};for(let[c,o]of Object.entries(n.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(i[c]=o.value,a[c]=y);}return await this.db.insertInto(e).values({...i,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),n}async rawUpdate(e,t,n){var s;let i={},a={};for(let[c,o]of Object.entries(n.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(i[c]=o.value,a[c]=y);}return await Promise.all([this.db.updateTable(e).set(i).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(c=>c.column("id").doUpdateSet(a)).execute()]),n}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let n=Math.random().toString(36).substring(2,15),i=await this.db.savepoint(n).execute();try{return await e({trx:this,commit:()=>i.releaseSavepoint(n).execute().then(()=>{}),rollback:()=>i.rollbackToSavepoint(n).execute().then(()=>{})}).then(a=>i.isCommitted||i.isRolledBack?a:i.releaseSavepoint(n).execute().then(()=>a))}catch(a){throw await i.rollbackToSavepoint(n).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new r(t,this.schema),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(n=>t.isCommitted||t.isRolledBack?n:t.commit().execute().then(()=>n))}catch(n){throw await t.rollback().execute(),n}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,i])=>{var a,s,c;return n==="_meta"||(n==="id"?t[n]={value:i}:Array.isArray(i)?t[n]={value:i.map(o=>this.convertToMaterializedLiveType(o)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[n]}}:typeof i=="object"&&i!==null&&!(i instanceof Date)?t[n]={...this.convertToMaterializedLiveType(i),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[n]}}:t[n]={value:i,_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[n]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",i=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",s=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&i||a&&s}};var J=class r{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.updateSchema(this.schema),this.contextProvider=e.contextProvider;}static create(e){return new r(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>this.router.routes[e.req.resourceName].handleRequest({req:n,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&this.mutationSubscriptions.forEach(n=>{n({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId,procedure:e.req.procedure});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},gn=J.create;
|
|
2
|
-
exports.Route=Z;exports.RouteFactory=B;exports.Router=H;exports.SQLStorage=Q;exports.Server=J;exports.Storage=j;exports.expressAdapter=Ct;exports.routeFactory=nn;exports.router=tn;exports.server=
|
|
1
|
+
'use strict';var ze=require('qs'),zod=require('zod'),P=require('crypto');require('js-xxhash');var kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ze__default=/*#__PURE__*/_interopDefault(ze);var P__default=/*#__PURE__*/_interopDefault(P);var ge=Object.create;var Y=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var ve=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Ie=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of be(e))!we.call(r,i)&&i!==t&&Y(r,i,{get:()=>e[i],enumerable:!(n=Re(e,i))||n.enumerable});return r};var X=(r,e,t)=>(t=r!=null?ge(Se(r)):{},Ie(Y(t,"default",{value:r,enumerable:true}),r));var V=ve($=>{Object.defineProperty($,"__esModule",{value:true});$.parse=$e;$.serialize=Ce;var Me=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Le=/^[\u0021-\u003A\u003C-\u007E]*$/,Ae=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ee=/^[\u0020-\u003A\u003D-\u007E]*$/,Oe=Object.prototype.toString,je=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function $e(r,e){let t=new je,n=r.length;if(n<2)return t;let i=(e==null?void 0:e.decode)||Pe,a=0;do{let s=r.indexOf("=",a);if(s===-1)break;let c=r.indexOf(";",a),o=c===-1?n:c;if(s>o){a=r.lastIndexOf(";",s-1)+1;continue}let y=ee(r,a,s),f=te(r,s,y),u=r.slice(y,f);if(t[u]===void 0){let l=ee(r,s+1,o),p=te(r,o,l),d=i(r.slice(l,p));t[u]=d;}a=o+1;}while(a<n);return t}function ee(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function te(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Ce(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Me.test(r))throw new TypeError(`argument name is invalid: ${r}`);let i=n(e);if(!Le.test(i))throw new TypeError(`argument val is invalid: ${e}`);let a=r+"="+i;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(!Ae.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Ee.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!_e(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 Pe(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function _e(r){return Oe.call(r)==="[object Date]"}});var ie=X(V());var C=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.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),z=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),ne=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),L=ne.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),A=ne.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:z});zod.z.union([A,L]);var re=C.omit({resource:true}),N=L.omit({id:true,type:true,resource:true,procedure:true}),D=A.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([D,N]);var ae=r=>async e=>{var t;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,i={headers:n,cookies:n.cookie?ie.default.parse(n.cookie):{}},a=new URL(e.url),s=a.pathname.split("/"),c=a.searchParams,o=ze__default.default.parse(c.toString()),y=await((t=r.contextProvider)==null?void 0:t.call(r,{transport:"HTTP",headers:i.headers,cookies:i.cookies,query:o}))??{};if(e.method==="GET"){let f=s[s.length-1],{success:u,data:l,error:p}=re.safeParse(o);if(!u)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let d=await r.handleRequest({req:{...i,type:"QUERY",resourceName:f,context:y,where:l.where,include:l.include,query:o}});return !d||!d.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(d.data)}if(e.method==="POST")try{let f=s[s.length-1],u=s[s.length-2],l=e.body?await e.json():{},p;if(f==="insert"||f==="update"){let{success:h,data:x,error:R}=D.safeParse(l);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=x;}else {let{success:h,data:x,error:R}=N.safeParse(l);if(!h)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=x;}let d=await r.handleRequest({req:{...i,type:"MUTATE",resourceName:u,input:p.payload,context:y,resourceId:p.resourceId,procedure:f==="insert"||f==="update"?f.toUpperCase():f,query:{}}});return Response.json(d)}catch(f){return console.error("Error parsing mutation from the client:",f),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}return Response.json({message:"Not found",code:"NOT_FOUND"},{status:404})}catch(n){return console.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var pe=X(V());var I=zod.z.string(),Ne=zod.z.object({id:I,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),De=C.extend({id:I,type:zod.z.literal("QUERY")}),oe=A.extend({id:I}),Ke=L.extend({id:I}),Fe=zod.z.union([Ke,oe]),se=zod.z.union([Ne,De,Fe]),Ue=zod.z.object({id:I,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),qe=zod.z.object({id:I,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Ue,qe,oe]);zod.z.object({resource:zod.z.string(),data:zod.z.record(zod.z.string(),z)});var ue="0123456789ABCDEFGHJKMNPQRSTVWXYZ",E=32;var ke=16,le=10,ce=0xffffffffffff;var S;(function(r){r.Base32IncorrectEncoding="B32_ENC_INVALID",r.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",r.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",r.EncodeTimeNegative="ENC_TIME_NEG",r.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",r.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",r.PRNGDetectFailure="PRNG_DETECT",r.ULIDInvalid="ULID_INVALID",r.Unexpected="UNEXPECTED",r.UUIDInvalid="UUID_INVALID";})(S||(S={}));var w=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function We(r){let e=Math.floor(r()*E);return e===E&&(e=E-1),ue.charAt(e)}function He(r){var n;let e=Ze(),t=e&&(e.crypto||e.msCrypto)||(typeof P__default.default<"u"?P__default.default: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((n=P__default.default)!=null&&n.randomBytes)return ()=>P__default.default.randomBytes(1).readUInt8()/255;throw new w(S.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ze(){return Qe()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Be(r,e){let t="";for(;r>0;r--)t=We(e)+t;return t}function Ge(r,e=le){if(isNaN(r))throw new w(S.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>ce)throw new w(S.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${ce}: ${r}`);if(r<0)throw new w(S.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new w(S.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%E,n=ue.charAt(t)+n,r=(r-t)/E;return n}function Qe(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function de(r,e){let t=He(),n=Date.now();return Ge(n,le)+Be(ke,t)}var K=()=>de().toLowerCase();var ye=r=>{let e={},t={};return r.subscribeToMutations(n=>{let i=n;!i.resourceId||!i.payload||(console.log("Mutation propagated:",i),Object.entries(t[i.resource]??{}).forEach(([a,s])=>{var c;(c=e[a])==null||c.send(JSON.stringify({...i,id:i.id??K()}));}));}),(n,i)=>{var f;let a=u=>{n.send(JSON.stringify(u));},s=K(),c={headers:i.headers,cookies:typeof i.headers.cookie=="string"?pe.default.parse(i.headers.cookie):{}},o=ze.parse(i.url.split("?")[1]),y=(f=r.contextProvider)==null?void 0:f.call(r,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,query:o});e[s]=n,console.log("Client connected:",s),n.on("message",async u=>{try{console.log("Message received from the client:",u);let l=se.parse(JSON.parse(u.toString()));if(l.type==="SUBSCRIBE"){let{resource:p}=l;t[p]||(t[p]={}),t[p][s]={};}else if(l.type==="QUERY"){let{resource:p}=l,d=await r.handleRequest({req:{...c,type:"QUERY",resourceName:p,context:await y??{},query:o}});if(!d||!d.data)throw new Error("Invalid resource");a({id:l.id,type:"REPLY",data:{resource:p,data:Object.fromEntries(Object.entries(d.data??{}).map(([h,x])=>[h,x.value]))}});}else if(l.type==="MUTATE"){let{resource:p}=l;console.log("Received mutation from client:",l);try{let d=await r.handleRequest({req:{...c,type:"MUTATE",resourceName:p,input:l.payload,context:{messageId:l.id,...await y??{}},resourceId:l.resourceId,procedure:l.procedure,query:o}});l.procedure&&l.procedure!=="INSERT"&&l.procedure!=="UPDATE"&&a({id:l.id,type:"REPLY",data:d});}catch(d){a({id:l.id,type:"REJECT",resource:p,message:d.message}),console.error("Error parsing mutation from the client:",d);}}}catch(l){console.error("Error handling message from the client:",l);}}),n.on("close",()=>{console.log("Connection closed",s),delete e[s];for(let u of Object.values(t))delete u[s];});}};function me(r){let e=`${r.protocol}://${r.hostname}${r.url}`,t=new Headers;return Object.entries(r.headers).forEach(([n,i])=>{i&&t.set(n,Array.isArray(i)?i.join(","):i);}),new Request(e,{method:r.method,headers:t,body:r.body&&r.method!=="GET"?JSON.stringify(r.body):void 0})}var Ct=(r,e,t)=>{r.ws(`${(t==null?void 0:t.basePath)??""}/ws`,ye(e)),r.use(`${(t==null?void 0:t.basePath)??""}/`,(n,i)=>{ae(e)(me(n)).then(s=>s.json().then(c=>i.status(s.status).send(c)));});};var g=r=>{if(r)return Array.isArray(r.value)?r.value.map(e=>g(e)):typeof r.value!="object"||r.value===null||r.value instanceof Date?r.value:Object.fromEntries(Object.entries(r.value).map(([e,t])=>[e,g(t)]))};var b=(r,e,t=false)=>Object.entries(e).every(([n,i])=>{if(n==="$and")return i.every(s=>b(r,s,t));if(n==="$or")return i.some(s=>b(r,s,t));let a=(i==null?void 0:i.$eq)!==void 0?i==null?void 0:i.$eq:i;if(typeof i=="object"&&i!==null&&(i==null?void 0:i.$eq)===void 0){if(i.$in!==void 0){let s=r[n];return s===void 0?false:t?!i.$in.includes(s):i.$in.includes(s)}if(i.$not!==void 0&&!t)return b(r,{[n]:i.$not},true);if(i.$gt!==void 0){let s=r[n];return typeof s!="number"?false:t?s<=i.$gt:s>i.$gt}if(i.$gte!==void 0){let s=r[n];return typeof s!="number"?false:t?s<i.$gte:s>=i.$gte}if(i.$lt!==void 0){let s=r[n];return typeof s!="number"?false:t?s>=i.$lt:s<i.$lt}if(i.$lte!==void 0){let s=r[n];return typeof s!="number"?false:t?s>i.$lte:s<=i.$lte}return !r[n]||typeof r[n]!="object"?false:b(r[n],i,t)}return t?r[n]!==a:r[n]===a});var H=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},tn=r=>H.create({...r}),Xe=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),Z=class r{_resourceSchema;resourceName;middlewares;customMutations;authorization;constructor(e,t,n){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n;}async handleRequest(e){let t=n=>(()=>{if(n.type==="QUERY")return this.handleFind({req:n,db:e.db,schema:e.schema});if(n.type==="MUTATE"){if(!n.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[n.procedure];if(i){let a=i.inputValidator.parse(n.input);return n.input=a,i.handler({req:n,db:e.db,schema:e.schema})}else if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:e.db,schema:e.schema,operation:n.procedure})}throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>t(n))(e.req)}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new r(this.resourceName,e({mutation:Xe}))}handleFind=async({req:e,db:t})=>{var i,a;let n=(a=(i=this.authorization)==null?void 0:i.read)==null?void 0:a.call(i,{ctx:e.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await t.rawFind(e.resourceName,e.where&&n&&n!==true?{$and:[e.where,n]}:n&&n!==true?n:e.where,e.include),acceptedValues:null}};handleSet=async({req:e,db:t,schema:n,operation:i})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resourceName,e.resourceId);if(i==="INSERT"&&a)throw new Error("Resource already exists");if(i==="UPDATE"&&!a)throw new Error("Resource not found");return t.transaction(async({trx:s})=>{var f,u,l,p,d;let[c,o]=n[this.resourceName].mergeMutation("set",e.input,a);if(!o)throw new Error("Mutation rejected");if(i==="INSERT"){let h=await s.rawInsert(e.resourceName,e.resourceId,c);if((f=this.authorization)!=null&&f.insert){let x=g(h);x.id=x.id??e.resourceId;let R=this.authorization.insert({ctx:e.context,value:x});if(!(typeof R=="boolean"?R:b(x,R)))throw new Error("Not authorized")}return {data:h,acceptedValues:o}}if((l=(u=this.authorization)==null?void 0:u.update)!=null&&l.preMutation){let h=g(a);h.id=h.id??e.resourceId;let x=this.authorization.update.preMutation({ctx:e.context,value:h});if(!(typeof x=="boolean"?x:b(h,x)))throw new Error("Not authorized")}let y=await s.rawUpdate(e.resourceName,e.resourceId,c);if((d=(p=this.authorization)==null?void 0:p.update)!=null&&d.postMutation){let h=g(y);h.id=h.id??e.resourceId;let x=this.authorization.update.postMutation({ctx:e.context,value:h});if(!(typeof x=="boolean"?x:b(h,x)))throw new Error("Not authorized")}return {data:y,acceptedValues:o}})}},B=class r{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new Z(e.name,void 0,t).use(...this.middlewares)}use(...e){return new r([...this.middlewares,...e])}static create(){return new r}},nn=B.create;var j=class{async insert(e,t){let n=new Date().toISOString();return g(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([i,a])=>[i,{value:a,_meta:{timestamp:n}}]))}))}async update(e,t,n){let i=new Date().toISOString(),{id:a,...s}=n;return g(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(s).map(([c,o])=>[c,{value:o,_meta:{timestamp:i}}]))}))}};function _(r,e,t,n){if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error("Resource not found");let a=n.$or,s=n.$and;return (a?t.or:t.and)(a?n.$or.map(c=>_(r,e,t,c)):s?n.$and.map(c=>_(r,e,t,c)):Object.entries(n).map(([c,o])=>{var y,f;if(i.fields[c])return (o==null?void 0:o.$eq)!==void 0?t(`${e}.${c}`,o.$eq===null?"is":"=",o.$eq):(o==null?void 0:o.$in)!==void 0?t(`${e}.${c}`,"in",o.$in):(o==null?void 0:o.$not)!==void 0?((y=o==null?void 0:o.$not)==null?void 0:y.$in)!==void 0?t(`${e}.${c}`,"not in",o.$not.$in):((f=o==null?void 0:o.$not)==null?void 0:f.$eq)!==void 0?t(`${e}.${c}`,o.$not.$eq===null?"is not":"!=",o.$not.$eq):t(`${e}.${c}`,o.$not===null?"is not":"!=",o.$not):(o==null?void 0:o.$gt)!==void 0?t(`${e}.${c}`,">",o.$gt):(o==null?void 0:o.$gte)!==void 0?t(`${e}.${c}`,">=",o.$gte):(o==null?void 0:o.$lt)!==void 0?t(`${e}.${c}`,"<",o.$lt):(o==null?void 0:o.$lte)!==void 0?t(`${e}.${c}`,"<=",o.$lte):t(`${e}.${c}`,o===null?"is":"=",o);if(i.relations[c]){let u=i.relations[c],l=u.entity.name;u.type==="one"?"id":u.foreignColumn;u.type==="one"?u.relationalColumn:"id";return _(r,l,t,o)}return null}).filter(Boolean))}function tt(r,e,t,n){let i=r[e];if(!i)throw new Error("Resource not found");if(!n)return t;for(let a of Object.keys(n)){if(!i.relations[a])continue;let s=i.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(c,`${c}.${o}`,`${e}.${y}`);}return t}function Te(r,e,t,n){return !n||Object.keys(n).length===0?t:(t=tt(r,e,t,n),t.where(i=>_(r,e,i,n)))}function G(r,e,t,n){if(!n)return t;if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(n)){if(!i.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let s=i.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id",f=s.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom;t=t.select(u=>f(u.selectFrom(c).selectAll(c).whereRef(`${c}.${o}`,"=",`${e}.${y}`).select(l=>postgres.jsonObjectFrom(l.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"))).as(a));}return t}var Q=class r extends j{db;schema;constructor(e,t){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,i]of Object.entries(e)){let a=t.find(o=>o.name===n);a||await this.db.schema.createTable(n).ifNotExists().execute();let s=`${n}_meta`,c=t.find(o=>o.name===s);c||await this.db.schema.createTable(s).ifNotExists().execute();for(let[o,y]of Object.entries(i.fields)){let f=a==null?void 0:a.columns.find(p=>p.name===o),u=y.getStorageFieldType();f?f.dataType!==u.type&&console.error("Column type mismatch:",o,"expected to have type:",u.type,"but has type:",f.dataType):(await this.db.schema.alterTable(n).addColumn(o,u.type,p=>{let d=p;return u.unique&&(d=d.unique()),u.nullable||(d=d.notNull()),u.references&&(d=d.references(u.references)),u.primary&&(d=d.primaryKey()),u.default!==void 0&&(d=d.defaultTo(u.default)),d}).execute().catch(p=>{throw console.error("Error adding column",o,p),p}),u.index&&await this.db.schema.createIndex(`${n}_${o}_index`).on(n).column(o).execute().catch(p=>{})),(c==null?void 0:c.columns.find(p=>p.name===o))||await this.db.schema.alterTable(s).addColumn(o,"varchar",p=>{let d=p;return u.primary&&(d=d.primaryKey().references(`${n}.${o}`)),d}).execute();}}}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let i=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>postgres.jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));i=G(this.schema,e,i,n);let a=await i.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,n){let i=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(i)return g(i)}async rawFind(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let i=this.db.selectFrom(e).selectAll(e).select(o=>postgres.jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));i=Te(this.schema,e,i,t),i=G(this.schema,e,i,n);let a=await i.execute(),s=Object.fromEntries(a.map(o=>{let{id:y,...f}=o;return [y,f]}));return Object.keys(s).length===0?{}:Object.entries(s).reduce((o,[y,f])=>(o[y]=this.convertToMaterializedLiveType(f),o),{})}async find(e,t){let n=await this.rawFind(e.name,t==null?void 0:t.where,t==null?void 0:t.include);return Object.fromEntries(Object.entries(n).map(([i,a])=>[i,g(a)]))}async rawInsert(e,t,n){var s;let i={},a={};for(let[c,o]of Object.entries(n.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(i[c]=o.value,a[c]=y);}return await this.db.insertInto(e).values({...i,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),n}async rawUpdate(e,t,n){var s;let i={},a={};for(let[c,o]of Object.entries(n.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(i[c]=o.value,a[c]=y);}return await Promise.all([this.db.updateTable(e).set(i).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(c=>c.column("id").doUpdateSet(a)).execute()]),n}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let n=Math.random().toString(36).substring(2,15),i=await this.db.savepoint(n).execute();try{return await e({trx:this,commit:()=>i.releaseSavepoint(n).execute().then(()=>{}),rollback:()=>i.rollbackToSavepoint(n).execute().then(()=>{})}).then(a=>i.isCommitted||i.isRolledBack?a:i.releaseSavepoint(n).execute().then(()=>a))}catch(a){throw await i.rollbackToSavepoint(n).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new r(t,this.schema),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(n=>t.isCommitted||t.isRolledBack?n:t.commit().execute().then(()=>n))}catch(n){throw await t.rollback().execute(),n}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,i])=>{var a,s,c;return n==="_meta"||(n==="id"?t[n]={value:i}:Array.isArray(i)?t[n]={value:i.map(o=>this.convertToMaterializedLiveType(o)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[n]}}:typeof i=="object"&&i!==null&&!(i instanceof Date)?t[n]={...this.convertToMaterializedLiveType(i),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[n]}}:t[n]={value:i,_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[n]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",i=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",s=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&i||a&&s}};var J=class r{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,(t=e.middlewares)==null||t.forEach(n=>{this.middlewares.add(n);}),this.storage.updateSchema(this.schema),this.contextProvider=e.contextProvider;}static create(e){return new r(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>this.router.routes[e.req.resourceName].handleRequest({req:n,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&this.mutationSubscriptions.forEach(n=>{n({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId,procedure:e.req.procedure});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},xn=J.create;
|
|
2
|
+
exports.Route=Z;exports.RouteFactory=B;exports.Router=H;exports.SQLStorage=Q;exports.Server=J;exports.Storage=j;exports.expressAdapter=Ct;exports.routeFactory=nn;exports.router=tn;exports.server=xn;
|
package/dist/server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a,b,r}from'./chunk-GNY3ZGE5.js';import Se,{parse}from'qs';import {z as z$1}from'zod';import j from'node:crypto';import'js-xxhash';import {Kysely,PostgresDialect}from'kysely';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/postgres';var C=a(O=>{Object.defineProperty(O,"__esModule",{value:true});O.parse=Te;O.serialize=ge;var le=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,pe=/^[\u0021-\u003A\u003C-\u007E]*$/,me=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,fe=/^[\u0020-\u003A\u003D-\u007E]*$/,ye=Object.prototype.toString,he=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Te(i,e){let t=new he,r=i.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||xe,a=0;do{let s=i.indexOf("=",a);if(s===-1)break;let c=i.indexOf(";",a),o=c===-1?r:c;if(s>o){a=i.lastIndexOf(";",s-1)+1;continue}let y=H(i,a,s),f=Z(i,s,y),u=i.slice(y,f);if(t[u]===void 0){let d=H(i,s+1,o),p=Z(i,o,d),l=n(i.slice(d,p));t[u]=l;}a=o+1;}while(a<r);return t}function H(i,e,t){do{let r=i.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Z(i,e,t){for(;e>t;){let r=i.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function ge(i,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!le.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(e);if(!pe.test(n))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+n;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(!me.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!fe.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!be(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 xe(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function be(i){return ye.call(i)==="[object Date]"}});var Q=b(C(),1);var L=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.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),z=z$1.record(z$1.string(),z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()).nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})).superRefine((i,e)=>{i.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),B=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),M=B.extend({procedure:z$1.string(),payload:z$1.any().optional()}),E=B.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:z});z$1.union([E,M]);var G=L.omit({resource:true}),v=M.omit({id:true,type:true,resource:true,procedure:true}),N=E.omit({id:true,type:true,resource:true,procedure:true});z$1.union([N,v]);var K=i=>async e=>{var t;try{let r=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,n={headers:r,cookies:r.cookie?Q.default.parse(r.cookie):{}},a=new URL(e.url),s=a.pathname.split("/"),c=a.searchParams,o=Se.parse(c.toString()),y=await((t=i.contextProvider)==null?void 0:t.call(i,{transport:"HTTP",headers:n.headers,cookies:n.cookies,query:o}))??{};if(e.method==="GET"){let f=s[s.length-1],{success:u,data:d,error:p}=G.safeParse(o);if(!u)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let l=await i.handleRequest({req:{...n,type:"QUERY",resourceName:f,context:y,where:d.where,include:d.include,query:o}});return !l||!l.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(l.data)}if(e.method==="POST")try{let f=s[s.length-1],u=s[s.length-2],d=e.body?await e.json():{},p;if(f==="insert"||f==="update"){let{success:T,data:g,error:b}=N.safeParse(d);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=g;}else {let{success:T,data:g,error:b}=v.safeParse(d);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=g;}let l=await i.handleRequest({req:{...n,type:"MUTATE",resourceName:u,input:p.payload,context:y,resourceId:p.resourceId,procedure:f==="insert"||f==="update"?f.toUpperCase():f,query:{}}});return Response.json(l)}catch(f){return console.error("Error parsing mutation from the client:",f),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 console.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var ne=b(C(),1);var I=z$1.string(),we=z$1.object({id:I,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),Ie=L.extend({id:I,type:z$1.literal("QUERY")}),J=E.extend({id:I}),Me=M.extend({id:I}),Ee=z$1.union([Me,J]),Y=z$1.union([we,Ie,Ee]),Ae=z$1.object({id:I,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),$e=z$1.object({id:I,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([Ae,$e,J]);z$1.object({resource:z$1.string(),data:z$1.record(z$1.string(),z)});var ee="0123456789ABCDEFGHJKMNPQRSTVWXYZ",A=32;var Oe=16,te=10,X=0xffffffffffff;var S;(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";})(S||(S={}));var w=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Le(i){let e=Math.floor(i()*A);return e===A&&(e=A-1),ee.charAt(e)}function je(i){var r;let e=Pe(),t=e&&(e.crypto||e.msCrypto)||(typeof j<"u"?j:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=j)!=null&&r.randomBytes)return ()=>j.randomBytes(1).readUInt8()/255;throw new w(S.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Pe(){return ve()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ce(i,e){let t="";for(;i>0;i--)t=Le(e)+t;return t}function ze(i,e=te){if(isNaN(i))throw new w(S.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>X)throw new w(S.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${X}: ${i}`);if(i<0)throw new w(S.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new w(S.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,r="";for(let n=e;n>0;n--)t=i%A,r=ee.charAt(t)+r,i=(i-t)/A;return r}function ve(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function re(i,e){let t=je(),r=Date.now();return ze(r,te)+Ce(Oe,t)}var U=()=>re().toLowerCase();var ie=i=>{let e={},t={};return i.subscribeToMutations(r=>{let n=r;!n.resourceId||!n.payload||(console.log("Mutation propagated:",n),Object.entries(t[n.resource]??{}).forEach(([a,s])=>{var c;(c=e[a])==null||c.send(JSON.stringify({...n,id:n.id??U()}));}));}),(r,n)=>{var f;let a=u=>{r.send(JSON.stringify(u));},s=U(),c={headers:n.headers,cookies:typeof n.headers.cookie=="string"?ne.default.parse(n.headers.cookie):{}},o=parse(n.url.split("?")[1]),y=(f=i.contextProvider)==null?void 0:f.call(i,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,query:o});e[s]=r,console.log("Client connected:",s),r.on("message",async u=>{try{console.log("Message received from the client:",u);let d=Y.parse(JSON.parse(u.toString()));if(d.type==="SUBSCRIBE"){let{resource:p}=d;t[p]||(t[p]={}),t[p][s]={};}else if(d.type==="QUERY"){let{resource:p}=d,l=await i.handleRequest({req:{...c,type:"QUERY",resourceName:p,context:await y??{},query:o}});if(!l||!l.data)throw new Error("Invalid resource");a({id:d.id,type:"REPLY",data:{resource:p,data:Object.fromEntries(Object.entries(l.data??{}).map(([T,g])=>[T,g.value]))}});}else if(d.type==="MUTATE"){let{resource:p}=d;console.log("Received mutation from client:",d);try{let l=await i.handleRequest({req:{...c,type:"MUTATE",resourceName:p,input:d.payload,context:{messageId:d.id,...await y??{}},resourceId:d.resourceId,procedure:d.procedure,query:o}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&a({id:d.id,type:"REPLY",data:l});}catch(l){a({id:d.id,type:"REJECT",resource:p,message:l.message}),console.error("Error parsing mutation from the client:",l);}}}catch(d){console.error("Error handling message from the client:",d);}}),r.on("close",()=>{console.log("Connection closed",s),delete e[s];for(let u of Object.values(t))delete u[s];});}};function oe(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Tt=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,ie(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{K(e)(oe(r)).then(s=>s.json().then(c=>n.status(s.status).send(c)));});};var R=(i,e,t=false)=>Object.entries(e).every(([r,n])=>{if(r==="$and")return n.every(s=>R(i,s,t));if(r==="$or")return n.some(s=>R(i,s,t));let a=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let s=i[r];return s===void 0?false:t?!n.$in.includes(s):n.$in.includes(s)}if(n.$not!==void 0&&!t)return R(i,{[r]:n.$not},true);if(n.$gt!==void 0){let s=i[r];return typeof s!="number"?false:t?s<=n.$gt:s>n.$gt}if(n.$gte!==void 0){let s=i[r];return typeof s!="number"?false:t?s<n.$gte:s>=n.$gte}if(n.$lt!==void 0){let s=i[r];return typeof s!="number"?false:t?s>=n.$lt:s<n.$lt}if(n.$lte!==void 0){let s=i[r];return typeof s!="number"?false:t?s>n.$lte:s<=n.$lte}return !i[r]||typeof i[r]!="object"?false:R(i[r],n,t)}return t?i[r]!==a:i[r]===a});var D=class i{routes;constructor(e){this.routes=e.routes;}static create(e){return new i(e)}},Mt=i=>D.create({...i}),De=i=>({handler:e=>({inputValidator:i??z$1.undefined(),handler:e})}),_=class i{_resourceSchema;resourceName;middlewares;customMutations;authorization;constructor(e,t,r){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=r;}async handleRequest(e){let t=r=>(()=>{if(r.type==="QUERY")return this.handleFind({req:r,db:e.db,schema:e.schema});if(r.type==="MUTATE"){if(!r.procedure)throw new Error("Procedure is required for mutations");let n=this.customMutations[r.procedure];if(n){let a=n.inputValidator.parse(r.input);return r.input=a,n.handler({req:r,db:e.db,schema:e.schema})}else if(r.procedure==="INSERT"||r.procedure==="UPDATE")return this.handleSet({req:r,db:e.db,schema:e.schema,operation:r.procedure})}throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),async r=>t(r))(e.req)}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new i(this.resourceName,e({mutation:De}))}handleFind=async({req:e,db:t})=>{var n,a;let r=(a=(n=this.authorization)==null?void 0:n.read)==null?void 0:a.call(n,{ctx:e.context});if(typeof r=="boolean"&&!r)throw new Error("Not authorized");return {data:await t.rawFind(e.resourceName,e.where&&r&&r!==true?{$and:[e.where,r]}:r&&r!==true?r:e.where,e.include),acceptedValues:null}};handleSet=async({req:e,db:t,schema:r$1,operation:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resourceName,e.resourceId);if(n==="INSERT"&&a)throw new Error("Resource already exists");if(n==="UPDATE"&&!a)throw new Error("Resource not found");return t.transaction(async({trx:s})=>{var f,u,d,p,l;let[c,o]=r$1[this.resourceName].mergeMutation("set",e.input,a);if(!o)throw new Error("Mutation rejected");if(n==="INSERT"){let T=await s.rawInsert(e.resourceName,e.resourceId,c);if((f=this.authorization)!=null&&f.insert){let g=r(T);g.id=g.id??e.resourceId;let b=this.authorization.insert({ctx:e.context,value:g});if(!(typeof b=="boolean"?b:R(g,b)))throw new Error("Not authorized")}return {data:T,acceptedValues:o}}if((d=(u=this.authorization)==null?void 0:u.update)!=null&&d.preMutation){let T=r(a);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(!(typeof g=="boolean"?g:R(T,g)))throw new Error("Not authorized")}let y=await s.rawUpdate(e.resourceName,e.resourceId,c);if((l=(p=this.authorization)==null?void 0:p.update)!=null&&l.postMutation){let T=r(y);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(!(typeof g=="boolean"?g:R(T,g)))throw new Error("Not authorized")}return {data:y,acceptedValues:o}})}},V=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new _(e.name,void 0,t).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},Et=V.create;var $=class{async insert(e,t){let r$1=new Date().toISOString();return r(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([n,a])=>[n,{value:a,_meta:{timestamp:r$1}}]))}))}async update(e,t,r$1){let n=new Date().toISOString(),{id:a,...s}=r$1;return r(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(s).map(([c,o])=>[c,{value:o,_meta:{timestamp:n}}]))}))}};function P(i,e,t,r){if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error("Resource not found");let a=r.$or,s=r.$and;return (a?t.or:t.and)(a?r.$or.map(c=>P(i,e,t,c)):s?r.$and.map(c=>P(i,e,t,c)):Object.entries(r).map(([c,o])=>{var y,f;if(n.fields[c])return (o==null?void 0:o.$eq)!==void 0?t(`${e}.${c}`,o.$eq===null?"is":"=",o.$eq):(o==null?void 0:o.$in)!==void 0?t(`${e}.${c}`,"in",o.$in):(o==null?void 0:o.$not)!==void 0?((y=o==null?void 0:o.$not)==null?void 0:y.$in)!==void 0?t(`${e}.${c}`,"not in",o.$not.$in):((f=o==null?void 0:o.$not)==null?void 0:f.$eq)!==void 0?t(`${e}.${c}`,o.$not.$eq===null?"is not":"!=",o.$not.$eq):t(`${e}.${c}`,o.$not===null?"is not":"!=",o.$not):(o==null?void 0:o.$gt)!==void 0?t(`${e}.${c}`,">",o.$gt):(o==null?void 0:o.$gte)!==void 0?t(`${e}.${c}`,">=",o.$gte):(o==null?void 0:o.$lt)!==void 0?t(`${e}.${c}`,"<",o.$lt):(o==null?void 0:o.$lte)!==void 0?t(`${e}.${c}`,"<=",o.$lte):t(`${e}.${c}`,o===null?"is":"=",o);if(n.relations[c]){let u=n.relations[c],d=u.entity.name;u.type==="one"?"id":u.foreignColumn;u.type==="one"?u.relationalColumn:"id";return P(i,d,t,o)}return null}).filter(Boolean))}function Ve(i,e,t,r){let n=i[e];if(!n)throw new Error("Resource not found");if(!r)return t;for(let a of Object.keys(r)){if(!n.relations[a])continue;let s=n.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(c,`${c}.${o}`,`${e}.${y}`);}return t}function se(i,e,t,r){return !r||Object.keys(r).length===0?t:(t=Ve(i,e,t,r),t.where(n=>P(i,e,n,r)))}function k(i,e,t,r){if(!r)return t;if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(r)){if(!n.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let s=n.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id",f=s.type==="one"?jsonObjectFrom:jsonArrayFrom;t=t.select(u=>f(u.selectFrom(c).selectAll(c).whereRef(`${c}.${o}`,"=",`${e}.${y}`).select(d=>jsonObjectFrom(d.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"))).as(a));}return t}var F=class i extends ${db;schema;constructor(e,t){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.schema=t,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[r,n]of Object.entries(e)){let a=t.find(o=>o.name===r);a||await this.db.schema.createTable(r).ifNotExists().execute();let s=`${r}_meta`,c=t.find(o=>o.name===s);c||await this.db.schema.createTable(s).ifNotExists().execute();for(let[o,y]of Object.entries(n.fields)){let f=a==null?void 0:a.columns.find(p=>p.name===o),u=y.getStorageFieldType();f?f.dataType!==u.type&&console.error("Column type mismatch:",o,"expected to have type:",u.type,"but has type:",f.dataType):(await this.db.schema.alterTable(r).addColumn(o,u.type,p=>{let l=p;return u.unique&&(l=l.unique()),u.nullable||(l=l.notNull()),u.references&&(l=l.references(u.references)),u.primary&&(l=l.primaryKey()),u.default!==void 0&&(l=l.defaultTo(u.default)),l}).execute().catch(p=>{throw console.error("Error adding column",o,p),p}),u.index&&await this.db.schema.createIndex(`${r}_${o}_index`).on(r).column(o).execute().catch(p=>{})),(c==null?void 0:c.columns.find(p=>p.name===o))||await this.db.schema.alterTable(s).addColumn(o,"varchar",p=>{let l=p;return u.primary&&(l=l.primaryKey().references(`${r}.${o}`)),l}).execute();}}}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));n=k(this.schema,e,n,r);let a=await n.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,r$1){let n=await this.rawFindById(e.name,t,r$1==null?void 0:r$1.include);if(n)return r(n)}async rawFind(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=this.db.selectFrom(e).selectAll(e).select(o=>jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));n=se(this.schema,e,n,t),n=k(this.schema,e,n,r);let a=await n.execute(),s=Object.fromEntries(a.map(o=>{let{id:y,...f}=o;return [y,f]}));return Object.keys(s).length===0?{}:Object.entries(s).reduce((o,[y,f])=>(o[y]=this.convertToMaterializedLiveType(f),o),{})}async find(e,t){let r$1=await this.rawFind(e.name,t==null?void 0:t.where,t==null?void 0:t.include);return Object.fromEntries(Object.entries(r$1).map(([n,a])=>[n,r(a)]))}async rawInsert(e,t,r){var s;let n={},a={};for(let[c,o]of Object.entries(r.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(n[c]=o.value,a[c]=y);}return await this.db.insertInto(e).values({...n,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),r}async rawUpdate(e,t,r){var s;let n={},a={};for(let[c,o]of Object.entries(r.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(n[c]=o.value,a[c]=y);}return await Promise.all([this.db.updateTable(e).set(n).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(c=>c.column("id").doUpdateSet(a)).execute()]),r}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let r=Math.random().toString(36).substring(2,15),n=await this.db.savepoint(r).execute();try{return await e({trx:this,commit:()=>n.releaseSavepoint(r).execute().then(()=>{}),rollback:()=>n.rollbackToSavepoint(r).execute().then(()=>{})}).then(a=>n.isCommitted||n.isRolledBack?a:n.releaseSavepoint(r).execute().then(()=>a))}catch(a){throw await n.rollbackToSavepoint(r).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new i(t,this.schema),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(r=>t.isCommitted||t.isRolledBack?r:t.commit().execute().then(()=>r))}catch(r){throw await t.rollback().execute(),r}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[r,n])=>{var a,s,c;return r==="_meta"||(r==="id"?t[r]={value:n}:Array.isArray(n)?t[r]={value:n.map(o=>this.convertToMaterializedLiveType(o)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?t[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[r]}}:t[r]={value:n,_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[r]}}),t},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",s=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||a&&s}};var q=class i{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.updateSchema(this.schema),this.contextProvider=e.contextProvider;}static create(e){return new i(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),async r=>this.router.routes[e.req.resourceName].handleRequest({req:r,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&this.mutationSubscriptions.forEach(r=>{r({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId,procedure:e.req.procedure});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},kt=q.create;
|
|
1
|
+
import {a,b,t}from'./chunk-7C33XQ3U.js';import Se,{parse}from'qs';import {z as z$1}from'zod';import P from'node:crypto';import'js-xxhash';import {Kysely,PostgresDialect}from'kysely';import {jsonObjectFrom,jsonArrayFrom}from'kysely/helpers/postgres';var C=a(O=>{Object.defineProperty(O,"__esModule",{value:true});O.parse=Te;O.serialize=ge;var le=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,pe=/^[\u0021-\u003A\u003C-\u007E]*$/,me=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,fe=/^[\u0020-\u003A\u003D-\u007E]*$/,ye=Object.prototype.toString,he=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function Te(i,e){let t=new he,r=i.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||xe,a=0;do{let s=i.indexOf("=",a);if(s===-1)break;let c=i.indexOf(";",a),o=c===-1?r:c;if(s>o){a=i.lastIndexOf(";",s-1)+1;continue}let y=H(i,a,s),f=Z(i,s,y),u=i.slice(y,f);if(t[u]===void 0){let d=H(i,s+1,o),p=Z(i,o,d),l=n(i.slice(d,p));t[u]=l;}a=o+1;}while(a<r);return t}function H(i,e,t){do{let r=i.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function Z(i,e,t){for(;e>t;){let r=i.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function ge(i,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!le.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(e);if(!pe.test(n))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+n;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(!me.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!fe.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!be(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 xe(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function be(i){return ye.call(i)==="[object Date]"}});var Q=b(C(),1);var L=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.number().optional(),sort:z$1.array(z$1.object({key:z$1.string(),direction:z$1.enum(["asc","desc"])})).optional()}),z=z$1.record(z$1.string(),z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()).nullable(),_meta:z$1.object({timestamp:z$1.string().optional().nullable()}).optional()})).superRefine((i,e)=>{i.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),B=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string(),resourceId:z$1.string().optional()}),M=B.extend({procedure:z$1.string(),payload:z$1.any().optional()}),E=B.extend({procedure:z$1.enum(["INSERT","UPDATE"]),payload:z});z$1.union([E,M]);var G=L.omit({resource:true}),v=M.omit({id:true,type:true,resource:true,procedure:true}),N=E.omit({id:true,type:true,resource:true,procedure:true});z$1.union([N,v]);var K=i=>async e=>{var t;try{let r=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,n={headers:r,cookies:r.cookie?Q.default.parse(r.cookie):{}},a=new URL(e.url),s=a.pathname.split("/"),c=a.searchParams,o=Se.parse(c.toString()),y=await((t=i.contextProvider)==null?void 0:t.call(i,{transport:"HTTP",headers:n.headers,cookies:n.cookies,query:o}))??{};if(e.method==="GET"){let f=s[s.length-1],{success:u,data:d,error:p}=G.safeParse(o);if(!u)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let l=await i.handleRequest({req:{...n,type:"QUERY",resourceName:f,context:y,where:d.where,include:d.include,query:o}});return !l||!l.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(l.data)}if(e.method==="POST")try{let f=s[s.length-1],u=s[s.length-2],d=e.body?await e.json():{},p;if(f==="insert"||f==="update"){let{success:T,data:g,error:b}=N.safeParse(d);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=g;}else {let{success:T,data:g,error:b}=v.safeParse(d);if(!T)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:b},{status:400});p=g;}let l=await i.handleRequest({req:{...n,type:"MUTATE",resourceName:u,input:p.payload,context:y,resourceId:p.resourceId,procedure:f==="insert"||f==="update"?f.toUpperCase():f,query:{}}});return Response.json(l)}catch(f){return console.error("Error parsing mutation from the client:",f),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 console.error("Unexpected error:",r),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}};var ne=b(C(),1);var I=z$1.string(),we=z$1.object({id:I,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),Ie=L.extend({id:I,type:z$1.literal("QUERY")}),J=E.extend({id:I}),Me=M.extend({id:I}),Ee=z$1.union([Me,J]),Y=z$1.union([we,Ie,Ee]),Ae=z$1.object({id:I,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),$e=z$1.object({id:I,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([Ae,$e,J]);z$1.object({resource:z$1.string(),data:z$1.record(z$1.string(),z)});var ee="0123456789ABCDEFGHJKMNPQRSTVWXYZ",A=32;var Oe=16,te=10,X=0xffffffffffff;var S;(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";})(S||(S={}));var w=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Le(i){let e=Math.floor(i()*A);return e===A&&(e=A-1),ee.charAt(e)}function Pe(i){var r;let e=je(),t=e&&(e.crypto||e.msCrypto)||(typeof P<"u"?P:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=P)!=null&&r.randomBytes)return ()=>P.randomBytes(1).readUInt8()/255;throw new w(S.PRNGDetectFailure,"Failed to find a reliable PRNG")}function je(){return ve()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ce(i,e){let t="";for(;i>0;i--)t=Le(e)+t;return t}function ze(i,e=te){if(isNaN(i))throw new w(S.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>X)throw new w(S.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${X}: ${i}`);if(i<0)throw new w(S.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new w(S.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,r="";for(let n=e;n>0;n--)t=i%A,r=ee.charAt(t)+r,i=(i-t)/A;return r}function ve(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function re(i,e){let t=Pe(),r=Date.now();return ze(r,te)+Ce(Oe,t)}var U=()=>re().toLowerCase();var ie=i=>{let e={},t={};return i.subscribeToMutations(r=>{let n=r;!n.resourceId||!n.payload||(console.log("Mutation propagated:",n),Object.entries(t[n.resource]??{}).forEach(([a,s])=>{var c;(c=e[a])==null||c.send(JSON.stringify({...n,id:n.id??U()}));}));}),(r,n)=>{var f;let a=u=>{r.send(JSON.stringify(u));},s=U(),c={headers:n.headers,cookies:typeof n.headers.cookie=="string"?ne.default.parse(n.headers.cookie):{}},o=parse(n.url.split("?")[1]),y=(f=i.contextProvider)==null?void 0:f.call(i,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,query:o});e[s]=r,console.log("Client connected:",s),r.on("message",async u=>{try{console.log("Message received from the client:",u);let d=Y.parse(JSON.parse(u.toString()));if(d.type==="SUBSCRIBE"){let{resource:p}=d;t[p]||(t[p]={}),t[p][s]={};}else if(d.type==="QUERY"){let{resource:p}=d,l=await i.handleRequest({req:{...c,type:"QUERY",resourceName:p,context:await y??{},query:o}});if(!l||!l.data)throw new Error("Invalid resource");a({id:d.id,type:"REPLY",data:{resource:p,data:Object.fromEntries(Object.entries(l.data??{}).map(([T,g])=>[T,g.value]))}});}else if(d.type==="MUTATE"){let{resource:p}=d;console.log("Received mutation from client:",d);try{let l=await i.handleRequest({req:{...c,type:"MUTATE",resourceName:p,input:d.payload,context:{messageId:d.id,...await y??{}},resourceId:d.resourceId,procedure:d.procedure,query:o}});d.procedure&&d.procedure!=="INSERT"&&d.procedure!=="UPDATE"&&a({id:d.id,type:"REPLY",data:l});}catch(l){a({id:d.id,type:"REJECT",resource:p,message:l.message}),console.error("Error parsing mutation from the client:",l);}}}catch(d){console.error("Error handling message from the client:",d);}}),r.on("close",()=>{console.log("Connection closed",s),delete e[s];for(let u of Object.values(t))delete u[s];});}};function oe(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Tt=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,ie(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{K(e)(oe(r)).then(s=>s.json().then(c=>n.status(s.status).send(c)));});};var R=(i,e,t=false)=>Object.entries(e).every(([r,n])=>{if(r==="$and")return n.every(s=>R(i,s,t));if(r==="$or")return n.some(s=>R(i,s,t));let a=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let s=i[r];return s===void 0?false:t?!n.$in.includes(s):n.$in.includes(s)}if(n.$not!==void 0&&!t)return R(i,{[r]:n.$not},true);if(n.$gt!==void 0){let s=i[r];return typeof s!="number"?false:t?s<=n.$gt:s>n.$gt}if(n.$gte!==void 0){let s=i[r];return typeof s!="number"?false:t?s<n.$gte:s>=n.$gte}if(n.$lt!==void 0){let s=i[r];return typeof s!="number"?false:t?s>=n.$lt:s<n.$lt}if(n.$lte!==void 0){let s=i[r];return typeof s!="number"?false:t?s>n.$lte:s<=n.$lte}return !i[r]||typeof i[r]!="object"?false:R(i[r],n,t)}return t?i[r]!==a:i[r]===a});var D=class i{routes;constructor(e){this.routes=e.routes;}static create(e){return new i(e)}},Mt=i=>D.create({...i}),De=i=>({handler:e=>({inputValidator:i??z$1.undefined(),handler:e})}),_=class i{_resourceSchema;resourceName;middlewares;customMutations;authorization;constructor(e,t,r){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=r;}async handleRequest(e){let t=r=>(()=>{if(r.type==="QUERY")return this.handleFind({req:r,db:e.db,schema:e.schema});if(r.type==="MUTATE"){if(!r.procedure)throw new Error("Procedure is required for mutations");let n=this.customMutations[r.procedure];if(n){let a=n.inputValidator.parse(r.input);return r.input=a,n.handler({req:r,db:e.db,schema:e.schema})}else if(r.procedure==="INSERT"||r.procedure==="UPDATE")return this.handleSet({req:r,db:e.db,schema:e.schema,operation:r.procedure})}throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),async r=>t(r))(e.req)}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new i(this.resourceName,e({mutation:De}))}handleFind=async({req:e,db:t})=>{var n,a;let r=(a=(n=this.authorization)==null?void 0:n.read)==null?void 0:a.call(n,{ctx:e.context});if(typeof r=="boolean"&&!r)throw new Error("Not authorized");return {data:await t.rawFind(e.resourceName,e.where&&r&&r!==true?{$and:[e.where,r]}:r&&r!==true?r:e.where,e.include),acceptedValues:null}};handleSet=async({req:e,db:t$1,schema:r,operation:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t$1.rawFindById(e.resourceName,e.resourceId);if(n==="INSERT"&&a)throw new Error("Resource already exists");if(n==="UPDATE"&&!a)throw new Error("Resource not found");return t$1.transaction(async({trx:s})=>{var f,u,d,p,l;let[c,o]=r[this.resourceName].mergeMutation("set",e.input,a);if(!o)throw new Error("Mutation rejected");if(n==="INSERT"){let T=await s.rawInsert(e.resourceName,e.resourceId,c);if((f=this.authorization)!=null&&f.insert){let g=t(T);g.id=g.id??e.resourceId;let b=this.authorization.insert({ctx:e.context,value:g});if(!(typeof b=="boolean"?b:R(g,b)))throw new Error("Not authorized")}return {data:T,acceptedValues:o}}if((d=(u=this.authorization)==null?void 0:u.update)!=null&&d.preMutation){let T=t(a);T.id=T.id??e.resourceId;let g=this.authorization.update.preMutation({ctx:e.context,value:T});if(!(typeof g=="boolean"?g:R(T,g)))throw new Error("Not authorized")}let y=await s.rawUpdate(e.resourceName,e.resourceId,c);if((l=(p=this.authorization)==null?void 0:p.update)!=null&&l.postMutation){let T=t(y);T.id=T.id??e.resourceId;let g=this.authorization.update.postMutation({ctx:e.context,value:T});if(!(typeof g=="boolean"?g:R(T,g)))throw new Error("Not authorized")}return {data:y,acceptedValues:o}})}},V=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new _(e.name,void 0,t).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},Et=V.create;var $=class{async insert(e,t$1){let r=new Date().toISOString();return t(await this.rawInsert(e.name,t$1.id,{value:Object.fromEntries(Object.entries(t$1).map(([n,a])=>[n,{value:a,_meta:{timestamp:r}}]))}))}async update(e,t$1,r){let n=new Date().toISOString(),{id:a,...s}=r;return t(await this.rawUpdate(e.name,t$1,{value:Object.fromEntries(Object.entries(s).map(([c,o])=>[c,{value:o,_meta:{timestamp:n}}]))}))}};function j(i,e,t,r){if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error("Resource not found");let a=r.$or,s=r.$and;return (a?t.or:t.and)(a?r.$or.map(c=>j(i,e,t,c)):s?r.$and.map(c=>j(i,e,t,c)):Object.entries(r).map(([c,o])=>{var y,f;if(n.fields[c])return (o==null?void 0:o.$eq)!==void 0?t(`${e}.${c}`,o.$eq===null?"is":"=",o.$eq):(o==null?void 0:o.$in)!==void 0?t(`${e}.${c}`,"in",o.$in):(o==null?void 0:o.$not)!==void 0?((y=o==null?void 0:o.$not)==null?void 0:y.$in)!==void 0?t(`${e}.${c}`,"not in",o.$not.$in):((f=o==null?void 0:o.$not)==null?void 0:f.$eq)!==void 0?t(`${e}.${c}`,o.$not.$eq===null?"is not":"!=",o.$not.$eq):t(`${e}.${c}`,o.$not===null?"is not":"!=",o.$not):(o==null?void 0:o.$gt)!==void 0?t(`${e}.${c}`,">",o.$gt):(o==null?void 0:o.$gte)!==void 0?t(`${e}.${c}`,">=",o.$gte):(o==null?void 0:o.$lt)!==void 0?t(`${e}.${c}`,"<",o.$lt):(o==null?void 0:o.$lte)!==void 0?t(`${e}.${c}`,"<=",o.$lte):t(`${e}.${c}`,o===null?"is":"=",o);if(n.relations[c]){let u=n.relations[c],d=u.entity.name;u.type==="one"?"id":u.foreignColumn;u.type==="one"?u.relationalColumn:"id";return j(i,d,t,o)}return null}).filter(Boolean))}function Ve(i,e,t,r){let n=i[e];if(!n)throw new Error("Resource not found");if(!r)return t;for(let a of Object.keys(r)){if(!n.relations[a])continue;let s=n.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id";t=t.leftJoin(c,`${c}.${o}`,`${e}.${y}`);}return t}function se(i,e,t,r){return !r||Object.keys(r).length===0?t:(t=Ve(i,e,t,r),t.where(n=>j(i,e,n,r)))}function k(i,e,t,r){if(!r)return t;if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(r)){if(!n.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let s=n.relations[a],c=s.entity.name,o=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id",f=s.type==="one"?jsonObjectFrom:jsonArrayFrom;t=t.select(u=>f(u.selectFrom(c).selectAll(c).whereRef(`${c}.${o}`,"=",`${e}.${y}`).select(d=>jsonObjectFrom(d.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"))).as(a));}return t}var F=class i extends ${db;schema;constructor(e,t){super(),this.isKyselyLike(e)?this.db=e:this.db=new Kysely({dialect:new PostgresDialect({pool:e})}),this.schema=t,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[r,n]of Object.entries(e)){let a=t.find(o=>o.name===r);a||await this.db.schema.createTable(r).ifNotExists().execute();let s=`${r}_meta`,c=t.find(o=>o.name===s);c||await this.db.schema.createTable(s).ifNotExists().execute();for(let[o,y]of Object.entries(n.fields)){let f=a==null?void 0:a.columns.find(p=>p.name===o),u=y.getStorageFieldType();f?f.dataType!==u.type&&console.error("Column type mismatch:",o,"expected to have type:",u.type,"but has type:",f.dataType):(await this.db.schema.alterTable(r).addColumn(o,u.type,p=>{let l=p;return u.unique&&(l=l.unique()),u.nullable||(l=l.notNull()),u.references&&(l=l.references(u.references)),u.primary&&(l=l.primaryKey()),u.default!==void 0&&(l=l.defaultTo(u.default)),l}).execute().catch(p=>{throw console.error("Error adding column",o,p),p}),u.index&&await this.db.schema.createIndex(`${r}_${o}_index`).on(r).column(o).execute().catch(p=>{})),(c==null?void 0:c.columns.find(p=>p.name===o))||await this.db.schema.alterTable(s).addColumn(o,"varchar",p=>{let l=p;return u.primary&&(l=l.primaryKey().references(`${r}.${o}`)),l}).execute();}}}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));n=k(this.schema,e,n,r);let a=await n.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t$1,r){let n=await this.rawFindById(e.name,t$1,r==null?void 0:r.include);if(n)return t(n)}async rawFind(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=this.db.selectFrom(e).selectAll(e).select(o=>jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));n=se(this.schema,e,n,t),n=k(this.schema,e,n,r);let a=await n.execute(),s=Object.fromEntries(a.map(o=>{let{id:y,...f}=o;return [y,f]}));return Object.keys(s).length===0?{}:Object.entries(s).reduce((o,[y,f])=>(o[y]=this.convertToMaterializedLiveType(f),o),{})}async find(e,t$1){let r=await this.rawFind(e.name,t$1==null?void 0:t$1.where,t$1==null?void 0:t$1.include);return Object.fromEntries(Object.entries(r).map(([n,a])=>[n,t(a)]))}async rawInsert(e,t,r){var s;let n={},a={};for(let[c,o]of Object.entries(r.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(n[c]=o.value,a[c]=y);}return await this.db.insertInto(e).values({...n,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),r}async rawUpdate(e,t,r){var s;let n={},a={};for(let[c,o]of Object.entries(r.value)){let y=(s=o._meta)==null?void 0:s.timestamp;y&&(n[c]=o.value,a[c]=y);}return await Promise.all([this.db.updateTable(e).set(n).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(c=>c.column("id").doUpdateSet(a)).execute()]),r}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let r=Math.random().toString(36).substring(2,15),n=await this.db.savepoint(r).execute();try{return await e({trx:this,commit:()=>n.releaseSavepoint(r).execute().then(()=>{}),rollback:()=>n.rollbackToSavepoint(r).execute().then(()=>{})}).then(a=>n.isCommitted||n.isRolledBack?a:n.releaseSavepoint(r).execute().then(()=>a))}catch(a){throw await n.rollbackToSavepoint(r).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new i(t,this.schema),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(r=>t.isCommitted||t.isRolledBack?r:t.commit().execute().then(()=>r))}catch(r){throw await t.rollback().execute(),r}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[r,n])=>{var a,s,c;return r==="_meta"||(r==="id"?t[r]={value:n}:Array.isArray(n)?t[r]={value:n.map(o=>this.convertToMaterializedLiveType(o)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?t[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[r]}}:t[r]={value:n,_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[r]}}),t},{})}}isKyselyLike(e){if(e instanceof Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",s=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||a&&s}};var q=class i{router;storage;schema;middlewares=new Set;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.updateSchema(this.schema),this.contextProvider=e.contextProvider;}static create(e){return new i(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),async r=>this.router.routes[e.req.resourceName].handleRequest({req:r,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&this.mutationSubscriptions.forEach(r=>{r({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId,procedure:e.req.procedure});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},kt=q.create;
|
|
2
2
|
export{_ as Route,V as RouteFactory,D as Router,F as SQLStorage,q as Server,$ as Storage,Tt as expressAdapter,Et as routeFactory,Mt as router,kt as server};
|
package/package.json
CHANGED
package/dist/chunk-RWM6TXG7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var x="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var l;(function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID";})(l||(l={}));var u=class extends Error{constructor(t,n){super(`${n} (${t})`),this.name="ULIDError",this.code=t;}};function R(e){let t=Math.floor(e()*32);return t===32&&(t=31),x.charAt(t)}function I(e){let t=M(),n=t&&(t.crypto||t.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return n.getRandomValues(i),i[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return ()=>n.randomBytes(1).readUInt8()/255;throw new u(l.PRNGDetectFailure,"Failed to find a reliable PRNG")}function M(){return A()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function E(e,t){let n="";for(;e>0;e--)n=R(t)+n;return n}function _(e,t=10){if(isNaN(e))throw new u(l.EncodeTimeValueMalformed,`Time must be a number: ${e}`);if(e>0xffffffffffff)throw new u(l.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${e}`);if(e<0)throw new u(l.EncodeTimeNegative,`Time must be positive: ${e}`);if(Number.isInteger(e)===false)throw new u(l.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let n,i="";for(let a=t;a>0;a--)n=e%32,i=x.charAt(n)+i,e=(e-n)/32;return i}function A(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function L(e,t){let n=I(),i=Date.now();return _(i,10)+E(16,n)}var j=()=>L().toLowerCase(),S=(e,t)=>typeof e=="function"?e(t):e;var O=(e,t,n=[])=>new Proxy(e,{get:(i,a)=>{var p,y;if(a==="__isProxy__")return true;let r=(p=t.get)==null?void 0:p.call(t,i,[...n,a]);if(r!==void 0)return r;let o=i,s=a;return (y=o[s])!=null&&y.__isProxy__||(o[s]=O(typeof o[s]=="object"?o[s]:()=>{},t,[...n,a])),o[s]},apply:(i,a,r)=>{var o;return (o=t.apply)==null?void 0:o.call(t,i,n,r)}}),C=(e,t,n)=>{let i=[],a=0;for(let r=0;r<e.length&&(n===void 0||a<n);r++)t(e[r],r)&&(i.push(e[r]),a++);return i};var b=e=>{if(e)return Array.isArray(e.value)?e.value.map(t=>b(t)):typeof e.value!="object"||e.value===null||e.value instanceof Date?e.value:Object.fromEntries(Object.entries(e.value).map(([t,n])=>[t,b(n)]))};export{j as a,S as b,O as c,C as d,b as e};
|