@live-state/sync 0.0.6-canary-7 → 0.0.6-canary-13
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-AHF6GNMI.js +1 -0
- package/dist/chunk-IT5UC7TA.js +1 -0
- package/dist/client.d.ts +1 -2
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +1 -2
- package/dist/fetch-client.js +1 -1
- package/dist/{index-H5NdEfdH.d.ts → index-BiZR-P7f.d.ts} +101 -46
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/server.cjs +6 -2
- package/dist/server.d.cts +71 -14
- package/dist/server.d.ts +71 -14
- package/dist/server.js +6 -2
- package/package.json +10 -4
- package/dist/chunk-3SQDLIFN.js +0 -1
- package/dist/chunk-RCXJM33Z.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var b="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var l;(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";})(l||(l={}));var u=class extends Error{constructor(e,n){super(`${n} (${e})`),this.name="ULIDError",this.code=e;}};function R(t){let e=Math.floor(t()*32);return e===32&&(e=31),b.charAt(e)}function _(t){let e=w(),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(l.PRNGDetectFailure,"Failed to find a reliable PRNG")}function w(){return M()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function A(t,e){let n="";for(;t>0;t--)n=R(e)+n;return n}function E(t,e=10){if(isNaN(t))throw new u(l.EncodeTimeValueMalformed,`Time must be a number: ${t}`);if(t>0xffffffffffff)throw new u(l.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${t}`);if(t<0)throw new u(l.EncodeTimeNegative,`Time must be positive: ${t}`);if(Number.isInteger(t)===false)throw new u(l.EncodeTimeValueMalformed,`Time must be an integer: ${t}`);let n,i="";for(let r=e;r>0;r--)n=t%32,i=b.charAt(n)+i,t=(t-n)/32;return i}function M(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function I(t,e){let n=_(),i=Date.now();return E(i,10)+A(16,n)}var N=()=>I().toLowerCase();var j=(t,e)=>typeof t=="function"?t(e):t;var L=class t{_collection;_client;_where;_include;_limit;_single;_sort;_shouldAwait;constructor(e,n,i,r,a,s,o,T){this._collection=e,this._client=n,this._where=i??{},this._include=r??{},this._limit=a,this._single=s,this._sort=o,this._shouldAwait=T,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)}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}}buildQueryRequest(){return {resource:this._collection.name,where:this._where,include:this._include,limit:this._limit,sort:this._sort}}get(){let e=this._client.get(this.buildQueryRequest());return this._shouldAwait?Promise.resolve(e).then(n=>this._single?n[0]:n):this._single?e[0]:e}subscribe(e){return this._client.subscribe(this.buildQueryRequest(),n=>{if(this._single)return e(n[0]);e(n);})}static _init(e,n,i){return new t(e,n,void 0,void 0,void 0,void 0,void 0,i??false)}};var O=(t,e,n=[])=>new Proxy(t,{get:(i,r)=>{var T,y;if(r==="__isProxy__")return true;let a=(T=e.get)==null?void 0:T.call(e,i,[...n,r]);if(a!==void 0)return a;let s=i,o=r;return (y=s[o])!=null&&y.__isProxy__||(s[o]=O(typeof s[o]=="object"?s[o]:()=>{},e,[...n,r])),s[o]},apply:(i,r,a)=>{var s;return (s=e.apply)==null?void 0:s.call(e,i,n,a)}}),D=(t,e,n)=>{let i=[],r=0;for(let a=0;a<t.length&&(n===void 0||r<n);a++)e(t[a],a)&&(i.push(t[a]),r++);return i};var g=t=>t?Array.isArray(t.value)?t.value.map(n=>g(n)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([n,i])=>Array.isArray(i)?[n,i.map(r=>g(r))]:[n,g(i)])):void 0;export{N as a,j as b,L as c,O as d,D as e,g as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {xxHash32}from'js-xxhash';var O=Object.create;var I=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var S=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of A(e))!M.call(t,a)&&a!==i&&I(t,a,{get:()=>e[a],enumerable:!(n=K(e,a))||n.enumerable});return t};var $=(t,e,i)=>(i=t!=null?O(j(t)):{},S(e||!t||!t.__esModule?I(i,"default",{value:t,enumerable:true}):i,t));var o=class{_value;_meta;_encodeInput;_decodeInput};var m=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,i,n){return this.inner.encodeMutation(e,i,n)}mergeMutation(e,i,n){return this.inner.mergeMutation(e,i,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},y=class t extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,i,n,a,s,l,r){super(),this.storageType=e,this.convertFunc=i,this.isIndex=n??false,this.isUnique=a??false,this.defaultValue=s,this.foreignReference=l,this.isPrimary=r??false;}encodeMutation(e,i,n){return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){return n&&n._meta.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(i.value):i.value,_meta:i._meta},i]}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 m(this)}},v=class t extends y{constructor(){super("integer",e=>Number(e));}static create(){return new t}},q=v.create,p=class t extends y{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)}},N=p.create,D=p.createId,W=p.createReference,L=class t extends y{constructor(){super("boolean",e=>typeof e=="string"?e.toLowerCase()==="true":!!e);}static create(){return new t}},P=L.create,x=class t extends y{constructor(){super("timestamp",e=>typeof e=="string"?new Date(e):e);}static create(){return new t}},k=x.create;var g=class t extends o{name;fields;relations;constructor(e,i,n){super(),this.name=e,this.fields=i,this.relations=n??{};}encodeMutation(e,i,n){return Object.fromEntries(Object.entries(i).map(([a,s])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",s,n)]))}mergeMutation(e,i,n){let a={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(i).map(([s,l])=>{let r=this.fields[s]??this.relations[s];if(!r)return [s,l];let[u,d]=r.mergeMutation(e,l,n==null?void 0:n.value[s]);return d&&(a[s]=d),[s,u]}))}},a]}setRelations(e){return new t(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,i){return new t(e,i)}},H=g.create,f=class t extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,i,n,a,s){super(),this.entity=e,this.type=i,this.required=s??false,this.relationalColumn=n,this.foreignColumn=a;}encodeMutation(e,i,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:i,_meta:{timestamp:n}}}mergeMutation(e,i,n){var a;return this.type==="many"?n?[n,null]:[i,i]:(a=n==null?void 0:n._meta)!=null&&a.timestamp&&i._meta.timestamp&&n._meta.timestamp.localeCompare(i._meta.timestamp)>=0?[n,null]:[i,i]}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,i,n)=>new t(e,"one",i,void 0,n??false)}static createManyFactory(){return (e,i,n)=>new t(e,"many",void 0,i,n??false)}},z=(t,e)=>({$type:"relations",objectName:t.name,relations:e({one:f.createOneFactory(),many:f.createManyFactory()})}),h=t=>t?Array.isArray(t.value)?t.value.map(i=>h(i)):typeof t.value!="object"||t.value===null||t.value instanceof Date?t.value:Object.fromEntries(Object.entries(t.value).map(([i,n])=>Array.isArray(n)?[i,n.map(a=>h(a))]:[i,h(n)])):void 0,B=t=>Object.fromEntries(Object.entries(t).flatMap(([e,i])=>{if(i.$type==="relations")return [];let n=i,a=Object.values(t).find(s=>s.$type==="relations"&&s.objectName===i.name);return a&&(n=n.setRelations(a.relations)),[[n.name,n]]}));var Z=t=>xxHash32(JSON.stringify(t)).toString(32),C=(t,e,i)=>{let n={},a=i[e];if(!a)return n;let s=l=>{l.$and?l.$and.forEach(s):l.$or?l.$or.forEach(s):Object.entries(l).forEach(([r,u])=>{var d;if((d=a.relations)!=null&&d[r]&&(n[r]=true,typeof u=="object"&&u!==null&&!Array.isArray(u))){let b=C(u,a.relations[r].entity.name,i);Object.keys(b).length>0&&(n[r]=b);}});};return s(t),n},c=(t,e,i=false)=>Object.entries(e).every(([n,a])=>{if(n==="$and")return a.every(l=>c(t,l,i));if(n==="$or")return a.some(l=>c(t,l,i));let s=(a==null?void 0:a.$eq)!==void 0?a==null?void 0:a.$eq:a;if(typeof a=="object"&&a!==null&&(a==null?void 0:a.$eq)===void 0){if(a.$in!==void 0){let r=t[n];return r===void 0?false:i?!a.$in.includes(r):a.$in.includes(r)}if(a.$not!==void 0&&!i)return c(t,{[n]:a.$not},true);if(a.$gt!==void 0){let r=t[n];return typeof r!="number"?false:i?r<=a.$gt:r>a.$gt}if(a.$gte!==void 0){let r=t[n];return typeof r!="number"?false:i?r<a.$gte:r>=a.$gte}if(a.$lt!==void 0){let r=t[n];return typeof r!="number"?false:i?r>=a.$lt:r<a.$lt}if(a.$lte!==void 0){let r=t[n];return typeof r!="number"?false:i?r>a.$lte:r<=a.$lte}let l=t[n];return !l||typeof l!="object"&&!Array.isArray(l)?false:Array.isArray(l)?i?!l.some(r=>c(r,a,false)):l.some(r=>c(r,a,false)):c(l,a,i)}return i?t[n]!==s:t[n]===s}),T={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},R=class{level;prefix;constructor(e={}){this.level=e.level??T.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=T.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=T.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=T.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=T.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=T.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},ee=t=>new R(t);export{V as a,$ as b,o as c,m as d,y as e,v as f,q as g,p as h,N as i,D as j,W as k,L as l,P as m,x as n,k as o,g as p,H as q,f as r,z as s,h as t,B as u,Z as v,C as w,c as x,T as y,ee as z};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import 'react/jsx-runtime';
|
|
1
|
+
export { e as Client, d as ClientEvents, C as ClientOptions, c as ConnectionStateChangeEvent, M as MessageReceivedEvent, f as createClient, u as useLiveQuery, b as useLoadData } from './index-BiZR-P7f.js';
|
|
3
2
|
import 'zod';
|
|
4
3
|
import 'zod/v3';
|
|
5
4
|
import 'zod/v4/core';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,c,a,f,e,b}from'./chunk-RCXJM33Z.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 ae from'fast-deep-equal';import {openDB}from'idb';var g=l=>xxHash32(JSON.stringify(l)).toString(32);var m=(l,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(o=>m(l,o,t));if(i==="$or")return s.some(o=>m(l,o,t));let n=(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 r=l[i];return r===void 0?false:t?!s.$in.includes(r):s.$in.includes(r)}if(s.$not!==void 0&&!t)return m(l,{[i]:s.$not},true);if(s.$gt!==void 0){let r=l[i];return typeof r!="number"?false:t?r<=s.$gt:r>s.$gt}if(s.$gte!==void 0){let r=l[i];return typeof r!="number"?false:t?r<s.$gte:r>=s.$gte}if(s.$lt!==void 0){let r=l[i];return typeof r!="number"?false:t?r>=s.$lt:r<s.$lt}if(s.$lte!==void 0){let r=l[i];return typeof r!="number"?false:t?r>s.$lte:r<=s.$lte}let o=l[i];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?t?!o.some(r=>m(r,s,false)):o.some(r=>m(r,s,false)):m(o,s,t)}return t?l[i]!==n:l[i]===n}),y={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},C=class{level;prefix;constructor(e={}){this.level=e.level??y.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=y.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=y.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=y.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=y.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=y.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},T=l=>new C(l);var j=class{subscriptions=new Map;getOrStoreSubscription(e){let t=g(e);return this.subscriptions.has(t)?this.subscriptions.get(t).subscribe:(this.subscriptions.set(t,{subscribe:i=>{var n;(n=this.subscriptions.get(t))==null||n.callbacks.add(i);let s=e.subscribe(()=>{var o;(o=this.subscriptions.get(t))==null||o.callbacks.forEach(r=>{r();});});return ()=>{var o;(o=this.subscriptions.get(t))==null||o.callbacks.delete(i),setTimeout(()=>{var r;((r=this.subscriptions.get(t))==null?void 0:r.callbacks.size)===0&&(this.subscriptions.delete(t),s());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},J=new j,de=l=>useSyncExternalStore(J.getOrStoreSubscription(l),l.get),he=({children:l,client:e})=>(useEffect(()=>{e.subscribe();},[e.subscribe]),jsx(Fragment,{children:l}));var x=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.coerce.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),k=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()})),X=k.superRefine((l,e)=>{l.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()}),W=U.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:X});z.union([W,A]);var S=z.string(),ee=x.extend({id:S,type:z.literal("SUBSCRIBE")}),te=x.extend({id:S,type:z.literal("QUERY")}),H=W.extend({id:S}),ie=A.extend({id:S}),se=z.union([ie,H]);z.union([ee,te,se]);var ne=z.object({id:S,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),re=z.object({id:S,type:z.literal("REPLY"),data:z.any()}),Q=z.union([ne,re,H]),K=z.object({resource:z.string(),data:z.array(k)});var E=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 w=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(n=>[n,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 n=s.referencedBy.get(i.type);n&&n instanceof Set?n.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 n=this.nodes.get(s);if(!n)return;let o=n.referencedBy.get(i.type);o&&(o instanceof Set?o.delete(e):n.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(o=>{let r=this.nodes.get(o);!r||!r.references.get(i)||(r.references.delete(i),this.notifySubscribers(o));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(n){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,n);}});}getAllNodes(){return Array.from(this.nodes.values())}};var P="__meta",O="databases",R=class{db;async init(e,t){var p,h;if(typeof window>"u")return;let s=((p=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:p.version)??1,n=await g(e),o=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,d])=>[c,await g(d)]))),r=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(O)||c.createObjectStore(O);}}),a=(h=await this.getAll(r,O))==null?void 0:h[t];(a==null?void 0:a.schemaHash)!==n&&s++,this.db=await openDB(t,s,{async upgrade(c){[...Object.keys(e),P].forEach(d=>{(a==null?void 0:a.objectHashes[d])!==o[d]&&c.objectStoreNames.contains(d)&&c.deleteObjectStore(d),c.objectStoreNames.contains(d)||c.createObjectStore(d);}),await r.put(O,{schemaHash:n,objectHashes:o},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(P,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(P,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((n,o)=>[s[o],n]))}};var L=class{constructor(e,t,i,s){this.schema=e;this.logger=i,this.optimisticObjGraph=new w(i),this.kvStorage=new R,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,s==null||s(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([n])=>{this.kvStorage.get(n).then(o=>{if(!o||Object.keys(o).length===0)return;let r=Object.values(o);this.loadConsolidatedState(n,r);});});}).catch(n=>{i.debug("Storage initialization failed (may not be available in this environment):",n);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph;optimisticRawObjPool={};logger;collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var o;let s=t??g(e$1);if(this.querySnapshots[s]&&!i){let r=this.querySnapshots[s];if(r)return r}let n=((o=e$1.where)!=null&&o.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(r=>{let a=f(this.materializeOneWithInclude(r,e$1.include));return a?[a]:[]});if(e$1.sort&&e$1.sort.length>0){let r=(a,p)=>{for(let h of e$1.sort){let c=a[h.key],d=p[h.key];if(c<d)return h.direction==="asc"?-1:1;if(c>d)return h.direction==="asc"?1:-1}return 0};n.sort(r);}if(e$1.where||e$1.limit){let r=e$1.where?a=>m(a,e$1.where):()=>true;n=e(n,r,e$1.limit);}return i||(this.querySnapshots[s]=n),n}subscribe(e,t){var n;let i=g(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(n=this.collectionSubscriptions.get(i))==null||n.callbacks.add(t),()=>{var o,r;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((r=this.collectionSubscriptions.get(i))==null?void 0:r.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var o,r,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let n=(o=this.optimisticRawObjPool[e])==null?void 0:o[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(r=this.optimisticMutationStack)==null?void 0:r[e])==null?void 0:a.filter(c=>c.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 h=p.value;delete h.id,this.kvStorage.set(e,t.resourceId,h);}this.kvStorage.setMeta("mutationStack",this.optimisticMutationStack),this.updateRawObjPool(e,t.resourceId,t.payload,n);}undoMutation(e,t){var o,r;if(!this.optimisticMutationStack[e])return;let i=(o=this.optimisticMutationStack[e])==null?void 0:o.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let n=(r=this.optimisticRawObjPool[e])==null?void 0:r[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:{}}])),n);}loadConsolidatedState(e,t){t.forEach(i=>{var n;let s=(n=i.id)==null?void 0:n.value;s&&this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:i});});}updateRawObjPool(e,t,i,s){var r;if(!this.schema[e])return;let n=(r=this.rawObjPool[e])==null?void 0:r[t],o=(this.optimisticMutationStack[e]??[]).reduce((a,p)=>p.resourceId!==t?a:this.schema[e].mergeMutation("set",p.payload,a)[0],n);if(this.optimisticRawObjPool[e]??={},o?this.optimisticRawObjPool[e][t]={value:{...o.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!o)){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(([p,h])=>h.type==="one"?[[h.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,h])=>{let c=this.schema[e].relations[a[p]];if(!a[p])return;let d=s==null?void 0:s.value[p],[,b]=c.mergeMutation("set",h,d);if(b){if(!this.optimisticObjGraph.hasNode(b.value)){let M=c.entity.name;this.optimisticObjGraph.createNode(b.value,M,Object.values(this.schema[M].relations).flatMap(D=>D.type==="many"?[D.entity.name]:[]));}d!=null&&d.value&&this.optimisticObjGraph.removeLink(t,c.entity.name),this.optimisticObjGraph.createLink(t,b.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,n=(a=this.optimisticRawObjPool[s])==null?void 0:a[e];if(!n)return;let[o,r]=Object.entries(t).reduce((p,[h,c])=>{let d=this.schema[s].relations[h];return d&&(d.type==="one"?p[0].push([h,d.entity.name,c??true]):d.type==="many"&&p[1].push([h,d.entity.name,c??true])),p},[[],[]]);return {value:{...n.value,...Object.fromEntries(o.map(([p,h,c])=>[p,this.materializeOneWithInclude(i.references.get(h),typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(r.map(([p,h,c])=>{let d=i.referencedBy.get(h),b=d instanceof Set;return [p,b?{value:Array.from(d.values()).map(M=>this.materializeOneWithInclude(M,typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(d,typeof c=="object"&&c!==null?c:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=g(t.query),s=this.querySnapshots[i],n=this.get(t.query,void 0,true);if(ae(n,s))return;this.querySnapshots[i]=n,t.callbacks.forEach(o=>{o(n);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,n])=>{var a;let o=(a=this.schema[t])==null?void 0:a.relations[s];if(!o)return;let r=o.entity.name;i.push(r),typeof n=="object"&&n!==null&&i.push(...this.flattenIncludes(n,r));}),Array.from(new Set(i))}};var I=class{url;ws;store;logger;remoteSubCounters={};eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,n;this.url=e.url,this.logger=T({level:e.logLevel??y.INFO}),this.store=new L(e.schema,e.storage,this.logger,o=>{var r,a;(a=(r=Object.values(o))==null?void 0:r.flat())==null||a.forEach(p=>{this.sendWsMessage(p);});}),this.ws=new E({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(n=e.connection)==null?void 0:n.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",o=>{this.handleServerMessage(o.data);}),this.ws.addEventListener("connectionChange",o=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:o.open}),o.open&&(Object.keys(this.store.schema).forEach(r=>{this.sendWsMessage({id:a(),type:"QUERY",resource:r});}),Object.entries(this.remoteSubCounters).forEach(([r,a$1])=>{a$1>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:r});}),Object.values(this.store.optimisticMutationStack).forEach(r=>{r&&r.forEach(a=>{this.sendWsMessage(a);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{this.logger.debug("Message received from the server:",e);let t=Q.parse(JSON.parse(e));if(this.logger.debug("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){this.logger.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 n=K.parse(s);this.store.loadConsolidatedState(n.resource,n.data);}}catch(t){this.logger.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 o;let n={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i};(o=this.store)==null||o.addMutation(e,n,true),this.sendWsMessage(n);}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((n,o)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],o(new Error("Reply timeout"));},5e3),handler:r=>{delete this.replyHandlers[s.id],n(r);}};})}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);});}},Qe=l=>{let e=new I(l),t=T({level:l.logLevel??y.INFO,prefix:"Client"});return {client:{ws:e.ws,subscribe:i=>{let s=[];for(let n of i??Object.keys(e.store.schema))s.push(e.subscribeToRemote(n));return ()=>{t.debug("Removing listeners",s),s.forEach(n=>{n();});}},addEventListener:i=>e.addEventListener(i)},store:{query:Object.entries(l.schema).reduce((i,[s,n])=>(i[s]=c._init(n,e),i),{}),mutate:d(()=>{},{apply:(i,s,n)=>{if(s.length<2)return;if(s.length>2)throw new Error("Trying to access an invalid path");let[o,r]=s;if(r==="insert"){let{id:a,...p}=n[0];return e.mutate(o,a,"INSERT",p)}if(r==="update"){let[a,p]=n;return e.mutate(o,a,"UPDATE",p)}return e.genericMutate(o,r,n[0])}})}}};export{he as SubscriptionProvider,Qe as createClient,de as useLiveQuery};
|
|
1
|
+
import {d,c,a,f,e,b as b$1}from'./chunk-AHF6GNMI.js';import {useSyncExternalStore,useEffect}from'react';import {xxHash32}from'js-xxhash';import {z}from'zod';import {stringify}from'qs';import le from'fast-deep-equal';import {openDB}from'idb';var g=u=>xxHash32(JSON.stringify(u)).toString(32);var b=(u,e,t=false)=>Object.entries(e).every(([i,s])=>{if(i==="$and")return s.every(o=>b(u,o,t));if(i==="$or")return s.some(o=>b(u,o,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=u[i];return n===void 0?false:t?!s.$in.includes(n):s.$in.includes(n)}if(s.$not!==void 0&&!t)return b(u,{[i]:s.$not},true);if(s.$gt!==void 0){let n=u[i];return typeof n!="number"?false:t?n<=s.$gt:n>s.$gt}if(s.$gte!==void 0){let n=u[i];return typeof n!="number"?false:t?n<s.$gte:n>=s.$gte}if(s.$lt!==void 0){let n=u[i];return typeof n!="number"?false:t?n>=s.$lt:n<s.$lt}if(s.$lte!==void 0){let n=u[i];return typeof n!="number"?false:t?n>s.$lte:n<=s.$lte}let o=u[i];return !o||typeof o!="object"&&!Array.isArray(o)?false:Array.isArray(o)?t?!o.some(n=>b(n,s,false)):o.some(n=>b(n,s,false)):b(o,s,t)}return t?u[i]!==r:u[i]===r}),v={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},j=class{level;prefix;constructor(e={}){this.level=e.level??v.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=v.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=v.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=v.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=v.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=v.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},G=u=>new j(u);var x=class{subscriptions=new Map;getOrStoreSubscription(e){let t=g(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 o;(o=this.subscriptions.get(t))==null||o.callbacks.forEach(n=>{n();});});return ()=>{var o;(o=this.subscriptions.get(t))==null||o.callbacks.delete(i),setTimeout(()=>{var n;((n=this.subscriptions.get(t))==null?void 0:n.callbacks.size)===0&&(this.subscriptions.delete(t),s());},10);}},callbacks:new Set}),this.subscriptions.get(t).subscribe)}},X=new x,ye=u=>useSyncExternalStore(X.getOrStoreSubscription(u),u.get),fe=(u,e)=>{useEffect(()=>{let t=u.load(e.buildQueryRequest());return ()=>{t();}},[e,u.load]);};var w=z.object({resource:z.string(),where:z.record(z.string(),z.any()).optional(),include:z.record(z.string(),z.any()).optional(),lastSyncedAt:z.string().optional(),limit:z.coerce.number().optional(),sort:z.array(z.object({key:z.string(),direction:z.enum(["asc","desc"])})).optional()}),A=z.record(z.string(),z.object({value:z.any().nullable(),_meta:z.object({timestamp:z.string().optional().nullable()}).optional()})),ee=A.superRefine((u,e)=>{u.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()}),k=U.extend({procedure:z.string(),payload:z.any().optional()}),P=U.extend({procedure:z.enum(["INSERT","UPDATE"]),payload:ee});z.union([P,k]);var M=z.string(),te=w.extend({id:M,type:z.literal("SUBSCRIBE")}),ie=w.extend({id:M,type:z.literal("UNSUBSCRIBE")}),se=w.extend({id:M,type:z.literal("QUERY")}),Q=P.extend({id:M}),ne=k.extend({id:M}),re=z.union([ne,Q]);z.union([te,se,re,ie]);var oe=z.object({id:M,type:z.literal("REJECT"),resource:z.string(),message:z.string().optional()}),ae=z.object({id:M,type:z.literal("REPLY"),data:z.any()}),H=z.union([oe,ae,Q]),q=z.object({resource:z.string(),data:z.array(A)});var O=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(s=>{s(t);});}};var R=class{constructor(e){this.logger=e;this.nodes=new Map;}nodes;createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let s={id:e,type:t,referencedBy:new Map(i.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,s),s}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t){let i=this.nodes.get(e),s=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);i.references.set(s.type,t);let r=s.referencedBy.get(i.type);r&&r instanceof Set?r.add(e):s.referencedBy.set(i.type,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let s=i.references.get(t);if(!s)return;i.references.delete(t);let r=this.nodes.get(s);if(!r)return;let o=r.referencedBy.get(i.type);o&&(o instanceof Set?o.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(o=>{let n=this.nodes.get(o);!n||!n.references.get(i)||(n.references.delete(i),this.notifySubscribers(o));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{var s;try{i(e);}catch(r){(s=this.logger)==null||s.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var W="__meta",L="databases",C=class{db;async init(e,t){var p,d;if(typeof window>"u")return;let s=((p=(await window.indexedDB.databases()).find(c=>c.name===t))==null?void 0:p.version)??1,r=await g(e),o=Object.fromEntries(await Promise.all(Object.entries(e).map(async([c,l])=>[c,await g(l)]))),n=await openDB("live-state-databases",1,{upgrade(c){c.objectStoreNames.contains(L)||c.createObjectStore(L);}}),a=(d=await this.getAll(n,L))==null?void 0:d[t];(a==null?void 0:a.schemaHash)!==r&&s++,this.db=await openDB(t,s,{async upgrade(c){[...Object.keys(e),W].forEach(l=>{(a==null?void 0:a.objectHashes[l])!==o[l]&&c.objectStoreNames.contains(l)&&c.deleteObjectStore(l),c.objectStoreNames.contains(l)||c.createObjectStore(l);}),await n.put(L,{schemaHash:r,objectHashes:o},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(W,e):new Promise(t=>t(void 0))}setMeta(e,t){var i;return (i=this.db)==null?void 0:i.put(W,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,o)=>[s[o],r]))}};var T=class{constructor(e,t,i,s){this.schema=e;this.logger=i,this.optimisticObjGraph=new R(i),this.kvStorage=new C,t!==false&&this.kvStorage.init(this.schema,t.name).then(()=>{this.kvStorage.getMeta("mutationStack").then(r=>{!r||Object.keys(r).length===0||(this.optimisticMutationStack=r,s==null||s(this.optimisticMutationStack));}).then(()=>{Object.entries(this.schema).forEach(([r])=>{this.kvStorage.get(r).then(o=>{if(!o||Object.keys(o).length===0)return;let n=Object.values(o);this.loadConsolidatedState(r,n);});});}).catch(r=>{i.debug("Storage initialization failed (may not be available in this environment):",r);});});}rawObjPool={};optimisticMutationStack={};optimisticObjGraph;optimisticRawObjPool={};logger;collectionSubscriptions=new Map;querySnapshots={};kvStorage;get(e$1,t,i=false){var o;let s=t??g(e$1);if(this.querySnapshots[s]&&!i){let n=this.querySnapshots[s];if(n)return n}let r=((o=e$1.where)!=null&&o.id?[e$1.where.id]:Object.keys(this.optimisticRawObjPool[e$1.resource]??{})).flatMap(n=>{let a=f(this.materializeOneWithInclude(n,e$1.include));return a?[a]:[]});if(e$1.sort&&e$1.sort.length>0){let n=(a,p)=>{for(let d of e$1.sort){let c=a[d.key],l=p[d.key];if(c<l)return d.direction==="asc"?-1:1;if(c>l)return d.direction==="asc"?1:-1}return 0};r.sort(n);}if(e$1.where||e$1.limit){let n=e$1.where?a=>b(a,e$1.where):()=>true;r=e(r,n,e$1.limit);}return i||(this.querySnapshots[s]=r),r}subscribe(e,t){var r;let i=g(e);return this.collectionSubscriptions.get(i)||this.collectionSubscriptions.set(i,{callbacks:new Set,query:e,flatInclude:e.include?this.flattenIncludes(e.include,e.resource):void 0}),(r=this.collectionSubscriptions.get(i))==null||r.callbacks.add(t),()=>{var o,n;(o=this.collectionSubscriptions.get(i))==null||o.callbacks.delete(t),((n=this.collectionSubscriptions.get(i))==null?void 0:n.callbacks.size)===0&&(this.collectionSubscriptions.delete(i),delete this.querySnapshots[i]);}}addMutation(e,t,i=false){var o,n,a;let s=this.schema[e];if(this.logger.debug("Adding mutation",t),!s)throw new Error("Schema not found");let r=(o=this.optimisticRawObjPool[e])==null?void 0:o[t.resourceId];if(i)this.optimisticMutationStack[e]??=[],this.optimisticMutationStack[e].push(t);else {this.optimisticMutationStack[e]=((a=(n=this.optimisticMutationStack)==null?void 0:n[e])==null?void 0:a.filter(c=>c.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,r);}undoMutation(e,t){var o,n;if(!this.optimisticMutationStack[e])return;let i=(o=this.optimisticMutationStack[e])==null?void 0:o.findIndex(a=>a.id===t);if(i===-1)return;let s=this.optimisticMutationStack[e][i];this.logger.debug("Removing mutation",s);let r=(n=this.optimisticRawObjPool[e])==null?void 0:n[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){t.forEach(i=>{var n;let s=(n=i.id)==null?void 0:n.value;if(!s)return;let{cleanedPayload:r,nestedMutations:o}=this.extractNestedRelations(e,i);o.forEach(a=>{this.addMutation(a.resource,a);}),this.addMutation(e,{id:s,type:"MUTATE",resource:e,resourceId:s,procedure:"INSERT",payload:r});});}extractNestedRelations(e,t){let i=this.schema[e],s={...t},r=[];return i!=null&&i.relations?(Object.entries(t).forEach(([o,n])=>{var c;let a=i.relations[o];if(!a)return;let p=a.entity.name,d=n==null?void 0:n.value;if(a.type==="one"){if(d&&typeof d=="object"&&!Array.isArray(d)&&((c=d.id)!=null&&c.value)){let l=d.id.value,f={...d},{cleanedPayload:m,nestedMutations:S}=this.extractNestedRelations(p,f);r.push(...S),r.push({id:l,type:"MUTATE",resource:p,resourceId:l,procedure:"INSERT",payload:m}),delete s[o];}}else a.type==="many"&&Array.isArray(d)&&(d.forEach(l=>{var f,m;if(l&&typeof l=="object"&&!Array.isArray(l)&&((m=(f=l.value)==null?void 0:f.id)!=null&&m.value)){let S=l.value.id.value,_={...l.value},{cleanedPayload:F,nestedMutations:V}=this.extractNestedRelations(p,_);r.push(...V),r.push({id:S,type:"MUTATE",resource:p,resourceId:S,procedure:"INSERT",payload:F});}}),delete s[o]);}),{cleanedPayload:s,nestedMutations:r}):{cleanedPayload:s,nestedMutations:r}}updateRawObjPool(e,t,i,s){var n;if(!this.schema[e])return;let r=(n=this.rawObjPool[e])==null?void 0:n[t],o=(this.optimisticMutationStack[e]??[]).reduce((a,p)=>p.resourceId!==t?a:this.schema[e].mergeMutation("set",p.payload,a)[0],r);if(this.optimisticRawObjPool[e]??={},o?this.optimisticRawObjPool[e][t]={value:{...o.value,id:{value:t}}}:delete this.optimisticRawObjPool[e][t],!(!this.optimisticObjGraph.hasNode(t)&&!o)){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(([p,d])=>d.type==="one"?[[d.relationalColumn,p]]:[]));Object.entries(i).forEach(([p,d])=>{let c=this.schema[e].relations[a[p]];if(!a[p])return;let l=s==null?void 0:s.value[p],[,f]=c.mergeMutation("set",d,l);if(f){if(!this.optimisticObjGraph.hasNode(f.value)){let m=c.entity.name;this.optimisticObjGraph.createNode(f.value,m,Object.values(this.schema[m].relations).flatMap(S=>S.type==="many"?[S.entity.name]:[]));}l!=null&&l.value&&this.optimisticObjGraph.removeLink(t,c.entity.name),this.optimisticObjGraph.createLink(t,f.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[o,n]=Object.entries(t).reduce((p,[d,c])=>{let l=this.schema[s].relations[d];return l&&(l.type==="one"?p[0].push([d,l.entity.name,c??true]):l.type==="many"&&p[1].push([d,l.entity.name,c??true])),p},[[],[]]);return {value:{...r.value,...Object.fromEntries(o.map(([p,d,c])=>[p,this.materializeOneWithInclude(i.references.get(d),typeof c=="object"&&c!==null?c:{})])),...Object.fromEntries(n.map(([p,d,c])=>{let l=i.referencedBy.get(d),f=l instanceof Set;return [p,f?{value:Array.from(l.values()).map(m=>this.materializeOneWithInclude(m,typeof c=="object"&&c!==null?c:{}))}:this.materializeOneWithInclude(l,typeof c=="object"&&c!==null?c:{})]}))}}}notifyCollectionSubscribers(e){this.collectionSubscriptions.forEach(t=>{if(t.query.resource===e||t.flatInclude&&t.flatInclude.includes(e)){let i=g(t.query),s=this.querySnapshots[i],r=this.get(t.query,void 0,true);if(le(r,s))return;this.querySnapshots[i]=r,t.callbacks.forEach(o=>{o(r);});}});}flattenIncludes(e,t){let i=[];return Object.entries(e).forEach(([s,r])=>{var a;let o=(a=this.schema[t])==null?void 0:a.relations[s];if(!o)return;let n=o.entity.name;i.push(n),typeof r=="object"&&r!==null&&i.push(...this.flattenIncludes(r,n));}),Array.from(new Set(i))}};var D=class{url;ws;store;logger;remoteSubscriptions=new Map;eventListeners=new Set;replyHandlers={};constructor(e){var t,i,s,r;this.url=e.url,this.logger=G({level:e.logLevel??v.INFO}),this.store=new T(e.schema,e.storage,this.logger,o=>{var n,a;(a=(n=Object.values(o))==null?void 0:n.flat())==null||a.forEach(p=>{this.sendWsMessage(p);});}),this.ws=new O({url:e.url,autoConnect:((t=e.connection)==null?void 0:t.autoConnect)??true,autoReconnect:((i=e.connection)==null?void 0:i.autoReconnect)??true,reconnectTimeout:((s=e.connection)==null?void 0:s.reconnectTimeout)??5e3,reconnectLimit:(r=e.connection)==null?void 0:r.maxReconnectAttempts,credentials:e.credentials}),this.ws.addEventListener("message",o=>{this.handleServerMessage(o.data);}),this.ws.addEventListener("connectionChange",o=>{this.emitEvent({type:"CONNECTION_STATE_CHANGE",open:o.open}),o.open&&(Array.from(this.remoteSubscriptions.values()).forEach(({query:n})=>{this.sendWsMessage({id:a(),type:"SUBSCRIBE",...n});}),Object.values(this.store.optimisticMutationStack).forEach(n=>{n&&n.forEach(a=>{this.sendWsMessage(a);});}));});}get(e){return this.store.get(e)}handleServerMessage(e){try{this.logger.debug("Message received from the server:",e);let t=H.parse(JSON.parse(e));if(this.logger.debug("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){this.logger.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=q.parse(s);this.store.loadConsolidatedState(r.resource,r.data);}}catch(t){this.logger.error("Error parsing message from the server:",t);}}load(e){this.sendWsMessage({id:a(),type:"SUBSCRIBE",...e});let t=g(e);return this.remoteSubscriptions.has(t)?this.remoteSubscriptions.get(t).subCounter+=1:this.remoteSubscriptions.set(t,{query:e,subCounter:1}),()=>{this.remoteSubscriptions.has(t)&&(this.remoteSubscriptions.get(t).subCounter-=1,this.remoteSubscriptions.get(t).subCounter<=0&&(this.remoteSubscriptions.delete(t),this.sendWsMessage({id:a(),type:"UNSUBSCRIBE",...e})));}}subscribe(e,t){return this.store.subscribe(e,t)}mutate(e,t,i,s){var o;let r={id:a(),type:"MUTATE",resource:e,payload:this.store.schema[e].encodeMutation("set",s,new Date().toISOString()),resourceId:t,procedure:i};(o=this.store)==null||o.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,o)=>{this.replyHandlers[s.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[s.id],o(new Error("Reply timeout"));},5e3),handler:n=>{delete this.replyHandlers[s.id],r(n);}};})}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);});}},qe=u=>{let e=new D(u);return {client:{ws:e.ws,load:t=>e.load(t),addEventListener:t=>e.addEventListener(t)},store:{query:Object.entries(u.schema).reduce((t,[i,s])=>(t[i]=c._init(s,e),t),{}),mutate:d(()=>{},{apply:(t,i,s)=>{if(i.length<2)return;if(i.length>2)throw new Error("Trying to access an invalid path");let[r,o]=i;if(o==="insert"){let{id:n,...a}=s[0];return e.mutate(r,n,"INSERT",a)}if(o==="update"){let[n,a]=s;return e.mutate(r,n,"UPDATE",a)}return e.genericMutate(r,o,s[0])}})}}};export{qe as createClient,ye as useLiveQuery,fe as useLoadData};
|
package/dist/fetch-client.d.ts
CHANGED
package/dist/fetch-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {d,b,c,f as f$1}from'./chunk-
|
|
1
|
+
import {d,b,c,f as f$1}from'./chunk-AHF6GNMI.js';import {stringify}from'qs';var f=async(e,c,r)=>{let n=o=>{if(!o)return {};if(o instanceof Headers){let y={};return o.forEach((d,b)=>{y[b]=d;}),y}return Array.isArray(o)?Object.fromEntries(o):o},s=n(r==null?void 0:r.headers),u=n(c==null?void 0:c.headers),a={...r,...c,headers:{...s,...u}},t=await fetch(e,a),i;try{i=await t.json();}catch{i=await t.text().catch(()=>{});}if(!t.ok)throw new Error(`Failed to fetch: ${t.status} ${t.statusText}`,{cause:i});return i},h=e=>{if(e===null)return "null";if(Array.isArray(e))return e.map(h);if(typeof e=="object"&&e!==null&&e.constructor===Object){let c={};for(let[r,n]of Object.entries(e))c[r]=h(n);return c}return e},C=e=>{let c$1={get:async r=>{let n=h(r),s=stringify(n),u=await b(e.credentials)??{},a=await f(`${e.url}/${r.resource}${s?`?${s}`:""}`,{headers:{...u,"Content-Type":"application/json"}},e.fetchOptions);return !a||typeof a!="object"?[]:Array.isArray(a)?a.map(t=>{var y,d;let i=f$1(t),o=((d=(y=t==null?void 0:t.value)==null?void 0:y.id)==null?void 0:d.value)??(t==null?void 0:t.id);return {...i,id:o}}):Object.entries(a).map(([t,i])=>({...f$1(i),id:t}))},subscribe:()=>{throw new Error("Fetch client does not support subscriptions")}};return {query:Object.entries(e.schema).reduce((r,[n,s])=>(r[n]=c._init(s,c$1,true),r),{}),mutate:d(()=>{},{apply:async(r,n,s)=>{if(n.length<2)return;if(n.length>2)throw new Error("Trying to access an invalid path");let[u,a]=n,t=await b(e.credentials)??{};if(a==="insert"){let{id:i,...o}=s[0];await f(`${e.url}/${u}/insert`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({resourceId:i,payload:e.schema[u].encodeMutation("set",o,new Date().toISOString())})},e.fetchOptions);return}if(a==="update"){let[i,o]=s,{id:y,...d}=o;await f(`${e.url}/${u}/update`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({resourceId:i,payload:e.schema[u].encodeMutation("set",d,new Date().toISOString())})},e.fetchOptions);return}return await f(`${e.url}/${u}/${a}`,{method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify({payload:s[0]})},e.fetchOptions)}})}};export{C as createClient};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
import * as z3 from 'zod/v3';
|
|
4
3
|
import * as z4 from 'zod/v4/core';
|
|
@@ -221,9 +220,9 @@ type InferInsert<T extends LiveObjectAny> = {
|
|
|
221
220
|
};
|
|
222
221
|
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
223
222
|
|
|
224
|
-
type Promisify<T> = T extends Promise<
|
|
223
|
+
type Promisify<T> = T extends Promise<unknown> ? T : Promise<T>;
|
|
225
224
|
type ConditionalPromise<T, P extends boolean> = P extends true ? Promise<T> : T;
|
|
226
|
-
type
|
|
225
|
+
type PromiseOrSync<T> = T | Promise<T>;
|
|
227
226
|
type Generatable<T, Arg = never> = T | ((arg: Arg) => T);
|
|
228
227
|
|
|
229
228
|
type Simplify<T> = T extends Record<string, unknown> ? {
|
|
@@ -260,10 +259,12 @@ type RawQueryRequest = z.infer<typeof querySchema>;
|
|
|
260
259
|
type RouteRecord = Record<string, AnyRoute>;
|
|
261
260
|
declare class Router<TRoutes extends RouteRecord> {
|
|
262
261
|
readonly routes: TRoutes;
|
|
262
|
+
private readonly hooksRegistry;
|
|
263
263
|
private constructor();
|
|
264
264
|
static create<TRoutes extends RouteRecord>(opts: {
|
|
265
265
|
routes: TRoutes;
|
|
266
266
|
}): Router<TRoutes>;
|
|
267
|
+
getHooks(resourceName: string): Hooks<any> | undefined;
|
|
267
268
|
}
|
|
268
269
|
type AnyRouter = Router<any>;
|
|
269
270
|
type Mutation<TInputValidator extends z3.ZodTypeAny | z4.$ZodType, // TODO use StandardSchema instead
|
|
@@ -292,55 +293,80 @@ type Authorization<TShape extends LiveObjectAny> = {
|
|
|
292
293
|
postMutation?: MutationAuthorizationHandler<TShape>;
|
|
293
294
|
};
|
|
294
295
|
};
|
|
296
|
+
type BeforeInsertHook<TShape extends LiveObjectAny> = (opts: {
|
|
297
|
+
ctx?: Record<string, any>;
|
|
298
|
+
value: MaterializedLiveType<TShape>;
|
|
299
|
+
db: Storage;
|
|
300
|
+
}) => Promise<MaterializedLiveType<TShape> | void> | MaterializedLiveType<TShape> | void;
|
|
301
|
+
type AfterInsertHook<TShape extends LiveObjectAny> = (opts: {
|
|
302
|
+
ctx?: Record<string, any>;
|
|
303
|
+
value: MaterializedLiveType<TShape>;
|
|
304
|
+
db: Storage;
|
|
305
|
+
}) => Promise<void> | void;
|
|
306
|
+
type BeforeUpdateHook<TShape extends LiveObjectAny> = (opts: {
|
|
307
|
+
ctx?: Record<string, any>;
|
|
308
|
+
value: MaterializedLiveType<TShape>;
|
|
309
|
+
previousValue?: MaterializedLiveType<TShape>;
|
|
310
|
+
db: Storage;
|
|
311
|
+
}) => Promise<MaterializedLiveType<TShape> | void> | MaterializedLiveType<TShape> | void;
|
|
312
|
+
type AfterUpdateHook<TShape extends LiveObjectAny> = (opts: {
|
|
313
|
+
ctx?: Record<string, any>;
|
|
314
|
+
value: MaterializedLiveType<TShape>;
|
|
315
|
+
previousValue?: MaterializedLiveType<TShape>;
|
|
316
|
+
db: Storage;
|
|
317
|
+
}) => Promise<void> | void;
|
|
318
|
+
type Hooks<TShape extends LiveObjectAny> = {
|
|
319
|
+
beforeInsert?: BeforeInsertHook<TShape>;
|
|
320
|
+
afterInsert?: AfterInsertHook<TShape>;
|
|
321
|
+
beforeUpdate?: BeforeUpdateHook<TShape>;
|
|
322
|
+
afterUpdate?: AfterUpdateHook<TShape>;
|
|
323
|
+
};
|
|
295
324
|
declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends Middleware<any>, TCustomMutations extends Record<string, Mutation<any, any>>> {
|
|
296
325
|
readonly resourceSchema: TResourceSchema;
|
|
297
326
|
readonly middlewares: Set<TMiddleware>;
|
|
298
327
|
readonly customMutations: TCustomMutations;
|
|
299
328
|
readonly authorization?: Authorization<TResourceSchema>;
|
|
300
|
-
|
|
329
|
+
readonly hooks?: Hooks<TResourceSchema>;
|
|
330
|
+
constructor(resourceSchema: TResourceSchema, customMutations?: TCustomMutations, authorization?: Authorization<TResourceSchema>, hooks?: Hooks<TResourceSchema>);
|
|
301
331
|
use(...middlewares: TMiddleware[]): this;
|
|
302
332
|
withMutations<T extends Record<string, Mutation<any, any>>>(mutationFactory: (opts: {
|
|
303
333
|
mutation: typeof mutationCreator;
|
|
304
334
|
}) => T): Route<TResourceSchema, TMiddleware, T>;
|
|
335
|
+
withHooks(hooks: Hooks<TResourceSchema>): Route<TResourceSchema, TMiddleware, TCustomMutations>;
|
|
336
|
+
getAuthorizationClause(req: QueryRequest): WhereClause<TResourceSchema> | undefined | boolean;
|
|
305
337
|
private handleSet;
|
|
306
338
|
private wrapInMiddlewares;
|
|
307
339
|
}
|
|
308
340
|
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
|
|
309
341
|
|
|
310
|
-
/** biome-ignore-all lint/
|
|
342
|
+
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
311
343
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
private _client;
|
|
319
|
-
private _where;
|
|
320
|
-
private _include;
|
|
321
|
-
private _limit?;
|
|
322
|
-
private _single?;
|
|
323
|
-
private _sort?;
|
|
324
|
-
private _shouldAwait?;
|
|
325
|
-
private constructor();
|
|
326
|
-
where(where: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
327
|
-
include<TNewInclude extends IncludeClause<TCollection>>(include: TNewInclude): QueryBuilder<TCollection, TInclude & TNewInclude, TSingle, TShouldAwait>;
|
|
328
|
-
get(): ConditionalPromise<InferQueryResult<TCollection, TInclude, TSingle>, TShouldAwait>;
|
|
329
|
-
subscribe(callback: (value: InferQueryResult<TCollection, TInclude, TSingle>) => void): () => void;
|
|
330
|
-
limit(limit: number): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
331
|
-
one(id: string): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
332
|
-
first(where?: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
333
|
-
orderBy(key: keyof TCollection["fields"], direction?: "asc" | "desc"): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
334
|
-
toJSON(): {
|
|
344
|
+
declare class Batcher {
|
|
345
|
+
private storage;
|
|
346
|
+
private queue;
|
|
347
|
+
private scheduled;
|
|
348
|
+
constructor(storage: Storage);
|
|
349
|
+
rawFind<T extends LiveObjectAny>({ resource, commonWhere, uniqueWhere, ...rest }: {
|
|
335
350
|
resource: string;
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
351
|
+
commonWhere?: Record<string, any>;
|
|
352
|
+
uniqueWhere?: Record<string, any>;
|
|
353
|
+
include?: Record<string, any>;
|
|
354
|
+
limit?: number;
|
|
355
|
+
sort?: {
|
|
340
356
|
key: string;
|
|
341
357
|
direction: "asc" | "desc";
|
|
342
|
-
}[]
|
|
343
|
-
}
|
|
358
|
+
}[];
|
|
359
|
+
}): Promise<MaterializedLiveType<T>[]>;
|
|
360
|
+
private getBatchKey;
|
|
361
|
+
private processBatch;
|
|
362
|
+
private executeBatchedRequests;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
interface DataSource {
|
|
366
|
+
get(query: RawQueryRequest, extra?: {
|
|
367
|
+
context?: any;
|
|
368
|
+
batcher?: Batcher;
|
|
369
|
+
}): PromiseOrSync<any[]>;
|
|
344
370
|
}
|
|
345
371
|
|
|
346
372
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
@@ -359,7 +385,7 @@ declare abstract class Storage implements DataSource {
|
|
|
359
385
|
}[];
|
|
360
386
|
}): Promise<InferLiveObject<T>[]>;
|
|
361
387
|
insert<T extends LiveObjectAny>(resource: T, value: Simplify<InferInsert<T>>): Promise<InferLiveObject<T>>;
|
|
362
|
-
update<T extends LiveObjectAny>(resource: T, resourceId: string, value: InferUpdate<T>): Promise<InferLiveObject<T
|
|
388
|
+
update<T extends LiveObjectAny>(resource: T, resourceId: string, value: InferUpdate<T>): Promise<Partial<InferLiveObject<T>>>;
|
|
363
389
|
abstract transaction<T>(fn: (opts: {
|
|
364
390
|
trx: Storage;
|
|
365
391
|
commit: () => Promise<void>;
|
|
@@ -367,8 +393,6 @@ declare abstract class Storage implements DataSource {
|
|
|
367
393
|
}) => Promise<T>): Promise<T>;
|
|
368
394
|
}
|
|
369
395
|
|
|
370
|
-
/** biome-ignore-all lint/suspicious/noExplicitAny: any's are actually used correctly */
|
|
371
|
-
|
|
372
396
|
interface BaseRequest {
|
|
373
397
|
headers: Record<string, string>;
|
|
374
398
|
cookies: Record<string, string>;
|
|
@@ -386,20 +410,51 @@ interface MutationRequest<TInput = any> extends BaseRequest {
|
|
|
386
410
|
procedure: string;
|
|
387
411
|
}
|
|
388
412
|
type Request = QueryRequest | MutationRequest;
|
|
389
|
-
type NextFunction<O, R = Request> = (req: R) =>
|
|
413
|
+
type NextFunction<O, R = Request> = (req: R) => PromiseOrSync<O>;
|
|
390
414
|
type Middleware<T = any> = (opts: {
|
|
391
415
|
req: Request;
|
|
392
416
|
next: NextFunction<T>;
|
|
393
417
|
}) => ReturnType<NextFunction<T>>;
|
|
394
418
|
|
|
419
|
+
/** biome-ignore-all lint/complexity/noBannedTypes: <explanation> */
|
|
420
|
+
|
|
421
|
+
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>>[];
|
|
422
|
+
declare class QueryBuilder<TCollection extends LiveObjectAny, TInclude extends IncludeClause<TCollection> = {}, TSingle extends boolean = false, TShouldAwait extends boolean = false> {
|
|
423
|
+
private _collection;
|
|
424
|
+
private _client;
|
|
425
|
+
private _where;
|
|
426
|
+
private _include;
|
|
427
|
+
private _limit?;
|
|
428
|
+
private _single?;
|
|
429
|
+
private _sort?;
|
|
430
|
+
private _shouldAwait?;
|
|
431
|
+
private constructor();
|
|
432
|
+
where(where: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
433
|
+
include<TNewInclude extends IncludeClause<TCollection>>(include: TNewInclude): QueryBuilder<TCollection, TInclude & TNewInclude, TSingle, TShouldAwait>;
|
|
434
|
+
limit(limit: number): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
435
|
+
one(id: string): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
436
|
+
first(where?: WhereClause<TCollection>): QueryBuilder<TCollection, TInclude, true, TShouldAwait>;
|
|
437
|
+
orderBy(key: keyof TCollection["fields"], direction?: "asc" | "desc"): QueryBuilder<TCollection, TInclude, TSingle, TShouldAwait>;
|
|
438
|
+
toJSON(): {
|
|
439
|
+
resource: string;
|
|
440
|
+
where: WhereClause<TCollection>;
|
|
441
|
+
include: TInclude;
|
|
442
|
+
limit: number | undefined;
|
|
443
|
+
sort: {
|
|
444
|
+
key: string;
|
|
445
|
+
direction: "asc" | "desc";
|
|
446
|
+
}[] | undefined;
|
|
447
|
+
};
|
|
448
|
+
buildQueryRequest(): RawQueryRequest;
|
|
449
|
+
get(): ConditionalPromise<InferQueryResult<TCollection, TInclude, TSingle>, TShouldAwait>;
|
|
450
|
+
subscribe(callback: (value: InferQueryResult<TCollection, TInclude, TSingle>) => void): () => void;
|
|
451
|
+
}
|
|
452
|
+
|
|
395
453
|
declare const useLiveQuery: <T extends {
|
|
396
454
|
get: () => U;
|
|
397
455
|
subscribe: (cb: (v: U) => void) => () => void;
|
|
398
456
|
}, U>(observable: T) => ReturnType<T["get"]>;
|
|
399
|
-
declare const
|
|
400
|
-
children: React.ReactNode;
|
|
401
|
-
client: Client<AnyRouter>["client"];
|
|
402
|
-
}) => react_jsx_runtime.JSX.Element;
|
|
457
|
+
declare const useLoadData: (client: Client<AnyRouter>["client"], query: QueryBuilder<any, any>) => void;
|
|
403
458
|
|
|
404
459
|
declare const serverMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
405
460
|
id: z.ZodString;
|
|
@@ -419,7 +474,7 @@ declare const serverMessageSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
419
474
|
UPDATE: "UPDATE";
|
|
420
475
|
}>;
|
|
421
476
|
payload: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
422
|
-
value: z.ZodNullable<z.
|
|
477
|
+
value: z.ZodNullable<z.ZodAny>;
|
|
423
478
|
_meta: z.ZodOptional<z.ZodObject<{
|
|
424
479
|
timestamp: z.ZodNullable<z.ZodOptional<z.ZodString>>;
|
|
425
480
|
}, z.core.$strip>>;
|
|
@@ -501,8 +556,8 @@ type ClientEvents = ConnectionStateChangeEvent | MessageReceivedEvent;
|
|
|
501
556
|
type Client<TRouter extends AnyRouter> = {
|
|
502
557
|
client: {
|
|
503
558
|
ws: WebSocketClient;
|
|
504
|
-
subscribe: (resourceType?: string[]) => () => void;
|
|
505
559
|
addEventListener: (listener: (event: ClientEvents) => void) => () => void;
|
|
560
|
+
load: (query: RawQueryRequest) => () => void;
|
|
506
561
|
};
|
|
507
562
|
store: Client$1<TRouter>;
|
|
508
563
|
};
|
|
@@ -511,11 +566,11 @@ declare const createClient: <TRouter extends AnyRouter>(opts: WebSocketClientOpt
|
|
|
511
566
|
type ClientOptions = {
|
|
512
567
|
url: string;
|
|
513
568
|
schema: Schema<any>;
|
|
514
|
-
credentials?: Generatable<
|
|
569
|
+
credentials?: Generatable<PromiseOrSync<Record<string, string>>>;
|
|
515
570
|
storage: {
|
|
516
571
|
name: string;
|
|
517
572
|
} | false;
|
|
518
573
|
logLevel?: LogLevel;
|
|
519
574
|
};
|
|
520
575
|
|
|
521
|
-
export { type AnyRouter as A, type ClientOptions as C, type MessageReceivedEvent as M,
|
|
576
|
+
export { type AnyRouter as A, type ClientOptions as C, type MessageReceivedEvent as M, type Client$1 as a, useLoadData as b, type ConnectionStateChangeEvent as c, type ClientEvents as d, type Client as e, createClient as f, useLiveQuery as u };
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';require('js-xxhash');var s=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends s{inner;constructor(
|
|
1
|
+
'use strict';require('js-xxhash');var s=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends s{inner;constructor(t){super(),this.inner=t;}encodeMutation(t,n,e){return this.inner.encodeMutation(t,n,e)}mergeMutation(t,n,e){return this.inner.mergeMutation(t,n,e)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class i extends s{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(t,n,e,a,r,u,y){super(),this.storageType=t,this.convertFunc=n,this.isIndex=e??false,this.isUnique=a??false,this.defaultValue=r,this.foreignReference=u,this.isPrimary=y??false;}encodeMutation(t,n,e){return {value:n,_meta:{timestamp:e}}}mergeMutation(t,n,e){return e&&e._meta.timestamp&&n._meta.timestamp&&e._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[e,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 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(t){return new i(this.storageType,this.convertFunc,this.isIndex,this.isUnique,t,this.foreignReference,this.isPrimary)}primary(){return new i(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}nullable(){return new T(this)}},d=class i extends l{constructor(){super("integer",t=>Number(t));}static create(){return new i}},b=d.create,o=class i extends l{constructor(t){super("varchar",void 0,void 0,void 0,void 0,t);}static create(){return new i}static createId(){return new i().index().unique().primary()}static createReference(t){return new i(t)}},I=o.create,O=o.createId,K=o.createReference,p=class i extends l{constructor(){super("boolean",t=>typeof t=="string"?t.toLowerCase()==="true":!!t);}static create(){return new i}},A=p.create,f=class i extends l{constructor(){super("timestamp",t=>typeof t=="string"?new Date(t):t);}static create(){return new i}},j=f.create;var v=class i extends s{name;fields;relations;constructor(t,n,e){super(),this.name=t,this.fields=n,this.relations=e??{};}encodeMutation(t,n,e){return Object.fromEntries(Object.entries(n).map(([a,r])=>[a,(this.fields[a]??this.relations[a]).encodeMutation("set",r,e)]))}mergeMutation(t,n,e){let a={};return [{value:{...(e==null?void 0:e.value)??{},...Object.fromEntries(Object.entries(n).map(([r,u])=>{let y=this.fields[r]??this.relations[r];if(!y)return [r,u];let[x,L]=y.mergeMutation(t,u,e==null?void 0:e.value[r]);return L&&(a[r]=L),[r,x]}))}},a]}setRelations(t){return new i(this.name,this.fields,t)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(t,n){return new i(t,n)}},w=v.create,c=class i extends s{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(t,n,e,a,r){super(),this.entity=t,this.type=n,this.required=r??false,this.relationalColumn=e,this.foreignColumn=a;}encodeMutation(t,n,e){if(t!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:n,_meta:{timestamp:e}}}mergeMutation(t,n,e){var a;return this.type==="many"?e?[e,null]:[n,n]:(a=e==null?void 0:e._meta)!=null&&a.timestamp&&n._meta.timestamp&&e._meta.timestamp.localeCompare(n._meta.timestamp)>=0?[e,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 (t,n,e)=>new i(t,"one",n,void 0,e??false)}static createManyFactory(){return (t,n,e)=>new i(t,"many",void 0,n,e??false)}},C=(i,t)=>({$type:"relations",objectName:i.name,relations:t({one:c.createOneFactory(),many:c.createManyFactory()})}),m=i=>i?Array.isArray(i.value)?i.value.map(n=>m(n)):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([n,e])=>Array.isArray(e)?[n,e.map(a=>m(a))]:[n,m(e)])):void 0,V=i=>Object.fromEntries(Object.entries(i).flatMap(([t,n])=>{if(n.$type==="relations")return [];let e=n,a=Object.values(i).find(r=>r.$type==="relations"&&r.objectName===n.name);return a&&(e=e.setRelations(a.relations)),[[e.name,e]]}));var h={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4};exports.LiveAtomicType=l;exports.LiveBoolean=p;exports.LiveNumber=d;exports.LiveObject=v;exports.LiveString=o;exports.LiveTimestamp=f;exports.LiveType=s;exports.LogLevel=h;exports.NullableLiveType=T;exports.Relation=c;exports.boolean=A;exports.createRelations=C;exports.createSchema=V;exports.id=O;exports.inferValue=m;exports.number=b;exports.object=w;exports.reference=K;exports.string=I;exports.timestamp=j;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{e as LiveAtomicType,l as LiveBoolean,f as LiveNumber,p as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,y as LogLevel,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-
|
|
1
|
+
export{e as LiveAtomicType,l as LiveBoolean,f as LiveNumber,p as LiveObject,h as LiveString,n as LiveTimestamp,c as LiveType,y as LogLevel,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-IT5UC7TA.js';
|