@live-state/sync 0.0.1-alpha.1 → 0.0.1-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/chunk-EK7ODJWE.js +1 -0
- package/dist/chunk-NIWX45UD.js +1 -0
- package/dist/client.d.ts +3 -283
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +17 -0
- package/dist/fetch-client.js +1 -0
- package/dist/index-NDRWVwih.d.ts +343 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +209 -2
- package/dist/index.d.ts +209 -2
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -1
- package/dist/server.d.cts +186 -52
- package/dist/server.d.ts +186 -52
- package/dist/server.js +2 -1
- package/package.json +22 -15
- package/dist/index-sSVirsfN.d.cts +0 -458
- package/dist/index-sSVirsfN.d.ts +0 -458
package/dist/server.d.ts
CHANGED
|
@@ -1,6 +1,148 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import '
|
|
1
|
+
import { z, ZodTypeAny } from 'zod';
|
|
2
|
+
import { LiveObjectAny, Schema, MaterializedLiveType, WhereClause } from './index.js';
|
|
3
|
+
import { PostgresPool } from 'kysely';
|
|
4
|
+
import { Application } from 'express-ws';
|
|
5
|
+
|
|
6
|
+
declare const mutationSchema: z.ZodUnion<[z.ZodObject<z.objectUtil.extendShape<{
|
|
7
|
+
id: z.ZodOptional<z.ZodString>;
|
|
8
|
+
type: z.ZodLiteral<"MUTATE">;
|
|
9
|
+
resource: z.ZodString;
|
|
10
|
+
}, {
|
|
11
|
+
procedure: z.ZodString;
|
|
12
|
+
payload: z.ZodOptional<z.ZodAny>;
|
|
13
|
+
}>, "strip", z.ZodTypeAny, {
|
|
14
|
+
procedure: string;
|
|
15
|
+
type: "MUTATE";
|
|
16
|
+
resource: string;
|
|
17
|
+
id?: string | undefined;
|
|
18
|
+
payload?: any;
|
|
19
|
+
}, {
|
|
20
|
+
procedure: string;
|
|
21
|
+
type: "MUTATE";
|
|
22
|
+
resource: string;
|
|
23
|
+
id?: string | undefined;
|
|
24
|
+
payload?: any;
|
|
25
|
+
}>, z.ZodObject<z.objectUtil.extendShape<{
|
|
26
|
+
id: z.ZodOptional<z.ZodString>;
|
|
27
|
+
type: z.ZodLiteral<"MUTATE">;
|
|
28
|
+
resource: z.ZodString;
|
|
29
|
+
}, {
|
|
30
|
+
resourceId: z.ZodString;
|
|
31
|
+
payload: z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
32
|
+
value: z.ZodUnion<[z.ZodUnion<[z.ZodUnion<[z.ZodString, z.ZodNumber]>, z.ZodBoolean]>, z.ZodDate]>;
|
|
33
|
+
_meta: z.ZodOptional<z.ZodObject<{
|
|
34
|
+
timestamp: z.ZodOptional<z.ZodString>;
|
|
35
|
+
}, "strip", z.ZodTypeAny, {
|
|
36
|
+
timestamp?: string | undefined;
|
|
37
|
+
}, {
|
|
38
|
+
timestamp?: string | undefined;
|
|
39
|
+
}>>;
|
|
40
|
+
}, "strip", z.ZodTypeAny, {
|
|
41
|
+
value: string | number | boolean | Date;
|
|
42
|
+
_meta?: {
|
|
43
|
+
timestamp?: string | undefined;
|
|
44
|
+
} | undefined;
|
|
45
|
+
}, {
|
|
46
|
+
value: string | number | boolean | Date;
|
|
47
|
+
_meta?: {
|
|
48
|
+
timestamp?: string | undefined;
|
|
49
|
+
} | undefined;
|
|
50
|
+
}>>, Record<string, {
|
|
51
|
+
value: string | number | boolean | Date;
|
|
52
|
+
_meta?: {
|
|
53
|
+
timestamp?: string | undefined;
|
|
54
|
+
} | undefined;
|
|
55
|
+
}>, Record<string, {
|
|
56
|
+
value: string | number | boolean | Date;
|
|
57
|
+
_meta?: {
|
|
58
|
+
timestamp?: string | undefined;
|
|
59
|
+
} | undefined;
|
|
60
|
+
}>>;
|
|
61
|
+
}>, "strip", z.ZodTypeAny, {
|
|
62
|
+
type: "MUTATE";
|
|
63
|
+
resourceId: string;
|
|
64
|
+
resource: string;
|
|
65
|
+
payload: Record<string, {
|
|
66
|
+
value: string | number | boolean | Date;
|
|
67
|
+
_meta?: {
|
|
68
|
+
timestamp?: string | undefined;
|
|
69
|
+
} | undefined;
|
|
70
|
+
}>;
|
|
71
|
+
id?: string | undefined;
|
|
72
|
+
}, {
|
|
73
|
+
type: "MUTATE";
|
|
74
|
+
resourceId: string;
|
|
75
|
+
resource: string;
|
|
76
|
+
payload: Record<string, {
|
|
77
|
+
value: string | number | boolean | Date;
|
|
78
|
+
_meta?: {
|
|
79
|
+
timestamp?: string | undefined;
|
|
80
|
+
} | undefined;
|
|
81
|
+
}>;
|
|
82
|
+
id?: string | undefined;
|
|
83
|
+
}>]>;
|
|
84
|
+
type RawMutationRequest = z.infer<typeof mutationSchema>;
|
|
85
|
+
|
|
86
|
+
type RouteRecord = Record<string, AnyRoute>;
|
|
87
|
+
declare class Router<TRoutes extends RouteRecord> {
|
|
88
|
+
readonly routes: TRoutes;
|
|
89
|
+
private constructor();
|
|
90
|
+
static create<TRoutes extends RouteRecord>(opts: {
|
|
91
|
+
routes: TRoutes;
|
|
92
|
+
}): Router<TRoutes>;
|
|
93
|
+
}
|
|
94
|
+
declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof TSchema, AnyRoute>>(opts: {
|
|
95
|
+
schema: TSchema;
|
|
96
|
+
routes: TRoutes;
|
|
97
|
+
}) => Router<TRoutes>;
|
|
98
|
+
type AnyRouter = Router<RouteRecord>;
|
|
99
|
+
type QueryResult<TShape extends LiveObjectAny> = {
|
|
100
|
+
data: Record<string, MaterializedLiveType<TShape>>;
|
|
101
|
+
};
|
|
102
|
+
type MutationResult<TShape extends LiveObjectAny> = {
|
|
103
|
+
data: MaterializedLiveType<TShape>;
|
|
104
|
+
acceptedValues: Record<string, any> | null;
|
|
105
|
+
};
|
|
106
|
+
type RequestHandler<TInput, TResult, TSchema extends Schema<any> = Schema<any>> = (opts: {
|
|
107
|
+
req: ParsedRequest<TInput>;
|
|
108
|
+
db: Storage;
|
|
109
|
+
schema: TSchema;
|
|
110
|
+
}) => Promise<TResult>;
|
|
111
|
+
type Mutation<TInputValidator extends ZodTypeAny, // TODO use StandardSchema instead
|
|
112
|
+
THandler extends RequestHandler<z.infer<TInputValidator>, any, any>> = {
|
|
113
|
+
inputValidator: TInputValidator;
|
|
114
|
+
handler: THandler;
|
|
115
|
+
};
|
|
116
|
+
declare const mutationCreator: <TInputValidator extends ZodTypeAny>(validator?: TInputValidator) => {
|
|
117
|
+
handler: <THandler extends RequestHandler<z.infer<TInputValidator>, any, any>>(handler: THandler) => Mutation<TInputValidator, THandler>;
|
|
118
|
+
};
|
|
119
|
+
declare class Route<TResourceSchema extends LiveObjectAny, TMiddleware extends Middleware<any>, TCustomMutations extends Record<string, Mutation<any, RequestHandler<any, any>>>> {
|
|
120
|
+
readonly _resourceSchema: TResourceSchema;
|
|
121
|
+
readonly resourceName: TResourceSchema["name"];
|
|
122
|
+
readonly middlewares: Set<TMiddleware>;
|
|
123
|
+
readonly customMutations: TCustomMutations;
|
|
124
|
+
constructor(resourceName: TResourceSchema["name"], customMutations?: TCustomMutations);
|
|
125
|
+
private handleFind;
|
|
126
|
+
private handleSet;
|
|
127
|
+
handleRequest(opts: {
|
|
128
|
+
req: ParsedRequest;
|
|
129
|
+
db: Storage;
|
|
130
|
+
schema: Schema<any>;
|
|
131
|
+
}): Promise<any>;
|
|
132
|
+
use(...middlewares: TMiddleware[]): this;
|
|
133
|
+
withMutations<T extends Record<string, Mutation<any, RequestHandler<any, any>>>>(mutationFactory: (opts: {
|
|
134
|
+
mutation: typeof mutationCreator;
|
|
135
|
+
}) => T): Route<TResourceSchema, TMiddleware, T>;
|
|
136
|
+
}
|
|
137
|
+
declare class RouteFactory {
|
|
138
|
+
private middlewares;
|
|
139
|
+
private constructor();
|
|
140
|
+
createBasicRoute<T extends LiveObjectAny>(shape: T): Route<T, Middleware<any>, Record<string, never>>;
|
|
141
|
+
use(...middlewares: Middleware<any>[]): RouteFactory;
|
|
142
|
+
static create(): RouteFactory;
|
|
143
|
+
}
|
|
144
|
+
declare const routeFactory: typeof RouteFactory.create;
|
|
145
|
+
type AnyRoute = Route<LiveObjectAny, Middleware<any>, Record<string, any>>;
|
|
4
146
|
|
|
5
147
|
declare abstract class Storage {
|
|
6
148
|
abstract updateSchema(opts: Schema<any>): Promise<void>;
|
|
@@ -15,74 +157,66 @@ declare class InMemoryStorage extends Storage {
|
|
|
15
157
|
find<T extends LiveObjectAny>(resourceName: string, where?: Record<string, any>): Promise<Record<string, MaterializedLiveType<T>>>;
|
|
16
158
|
upsert<T extends LiveObjectAny>(resourceName: string, resourceId: string, value: MaterializedLiveType<T>): Promise<MaterializedLiveType<T>>;
|
|
17
159
|
}
|
|
160
|
+
declare class SQLStorage extends Storage {
|
|
161
|
+
private db;
|
|
162
|
+
private schema?;
|
|
163
|
+
constructor(pool: PostgresPool);
|
|
164
|
+
updateSchema(opts: Schema<any>): Promise<void>;
|
|
165
|
+
findById<T extends LiveObjectAny>(resourceName: string, id: string): Promise<MaterializedLiveType<T> | undefined>;
|
|
166
|
+
find<T extends LiveObjectAny>(resourceName: string, where?: WhereClause<T>): Promise<Record<string, MaterializedLiveType<T>>>;
|
|
167
|
+
upsert<T extends LiveObjectAny>(resourceName: string, resourceId: string, value: MaterializedLiveType<T>): Promise<MaterializedLiveType<T>>;
|
|
168
|
+
private convertToMaterializedLiveType;
|
|
169
|
+
private applyWhere;
|
|
170
|
+
}
|
|
18
171
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
};
|
|
22
|
-
declare const webSocketAdapter: (server: Server<AnyRouter>) => (ws: WebSocket) => void;
|
|
172
|
+
declare const expressAdapter: (app: Application, server: Server<AnyRouter>, options?: {
|
|
173
|
+
basePath?: string;
|
|
174
|
+
}) => void;
|
|
23
175
|
|
|
24
|
-
type
|
|
176
|
+
type ParsedRequest<TInput = any> = {
|
|
177
|
+
headers: Record<string, string>;
|
|
178
|
+
cookies: Record<string, string>;
|
|
179
|
+
query: Record<string, string>;
|
|
25
180
|
resourceName: string;
|
|
181
|
+
procedure?: string;
|
|
26
182
|
context: Record<string, any>;
|
|
27
183
|
where?: Record<string, any>;
|
|
184
|
+
type: "QUERY" | "MUTATE";
|
|
185
|
+
resourceId?: string;
|
|
186
|
+
input?: TInput;
|
|
28
187
|
};
|
|
29
|
-
type
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
type
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
type RouteRecord = Record<string, Route<LiveObjectAny>>;
|
|
40
|
-
declare class Router<TSchema extends Schema<any>, TRoutes extends RouteRecord> {
|
|
41
|
-
readonly routes: TRoutes;
|
|
42
|
-
private constructor();
|
|
43
|
-
static create<TSchema extends Schema<any>, TRoutes extends RouteRecord>(opts: {
|
|
44
|
-
routes: TRoutes;
|
|
45
|
-
}): Router<TSchema, TRoutes>;
|
|
46
|
-
}
|
|
47
|
-
declare const router: <TSchema extends Schema<any>, TRoutes extends Record<keyof TSchema, Route<LiveObjectAny>>>(opts: {
|
|
48
|
-
schema: TSchema;
|
|
49
|
-
routes: TRoutes;
|
|
50
|
-
}) => Router<Schema<any>, TRoutes>;
|
|
51
|
-
type AnyRouter = Router<Schema<any>, RouteRecord>;
|
|
52
|
-
type RouteResult<TShape extends LiveObjectAny> = {
|
|
53
|
-
data: MaterializedLiveType<TShape> | Record<string, MaterializedLiveType<TShape>>;
|
|
54
|
-
acceptedValues: Record<string, any> | null;
|
|
55
|
-
};
|
|
56
|
-
declare class Route<TShape extends LiveObjectAny> {
|
|
57
|
-
readonly shape: TShape;
|
|
58
|
-
constructor(shape: TShape);
|
|
59
|
-
private handleFind;
|
|
60
|
-
private handleSet;
|
|
61
|
-
handleRequest(opts: {
|
|
62
|
-
req: Request;
|
|
63
|
-
db: Storage;
|
|
64
|
-
}): Promise<RouteResult<TShape>>;
|
|
65
|
-
}
|
|
66
|
-
declare const routeFactory: () => <T extends LiveObjectAny>(shape: T) => Route<T>;
|
|
67
|
-
type AnyRoute = Route<LiveObjectAny>;
|
|
68
|
-
type ClientId = string;
|
|
69
|
-
type MutationHandler = (mutation: MutationMessage) => void;
|
|
188
|
+
type ContextProvider = (req: Pick<ParsedRequest, "headers" | "cookies" | "query"> & {
|
|
189
|
+
transport: "HTTP" | "WEBSOCKET";
|
|
190
|
+
}) => Record<string, any>;
|
|
191
|
+
type RequestType = ParsedRequest["type"];
|
|
192
|
+
type MutationHandler = (mutation: RawMutationRequest) => void;
|
|
193
|
+
type NextFunction<T> = (req: ParsedRequest) => Promise<T> | T;
|
|
194
|
+
type Middleware<T = any> = (opts: {
|
|
195
|
+
req: ParsedRequest;
|
|
196
|
+
next: NextFunction<T>;
|
|
197
|
+
}) => ReturnType<NextFunction<T>>;
|
|
70
198
|
declare class Server<TRouter extends AnyRouter> {
|
|
71
199
|
readonly router: TRouter;
|
|
72
200
|
readonly storage: Storage;
|
|
73
201
|
readonly schema: Schema<any>;
|
|
202
|
+
readonly middlewares: Set<Middleware<any>>;
|
|
203
|
+
contextProvider?: ContextProvider;
|
|
74
204
|
private mutationSubscriptions;
|
|
75
205
|
private constructor();
|
|
76
206
|
static create<TRouter extends AnyRouter>(opts: {
|
|
77
207
|
router: TRouter;
|
|
78
208
|
storage: Storage;
|
|
79
209
|
schema: Schema<any>;
|
|
210
|
+
middlewares?: Middleware<any>[];
|
|
211
|
+
contextProvider?: ContextProvider;
|
|
80
212
|
}): Server<TRouter>;
|
|
81
213
|
subscribeToMutations(handler: MutationHandler): () => void;
|
|
82
214
|
handleRequest(opts: {
|
|
83
|
-
req:
|
|
84
|
-
}): Promise<
|
|
215
|
+
req: ParsedRequest;
|
|
216
|
+
}): Promise<any>;
|
|
217
|
+
use(middleware: Middleware<any>): this;
|
|
218
|
+
context(contextProvider: ContextProvider): this;
|
|
85
219
|
}
|
|
86
220
|
declare const server: typeof Server.create;
|
|
87
221
|
|
|
88
|
-
export { type AnyRoute, type AnyRouter, type
|
|
222
|
+
export { type AnyRoute, type AnyRouter, type ContextProvider, InMemoryStorage, type Middleware, type Mutation, type MutationHandler, type MutationResult, type NextFunction, type ParsedRequest, type QueryResult, type RequestHandler, type RequestType, Route, RouteFactory, type RouteRecord, Router, SQLStorage, Server, Storage, expressAdapter, routeFactory, router, server };
|
package/dist/server.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import {nanoid}from'nanoid';import {z}from'zod';var y=class{},S=class extends y{storage={};async updateSchema(e){console.log("Updating schema",e),this.storage=Object.entries(e).reduce((r,[s,i])=>(r[i.name]={},r),{});}async findById(e,r){var s;return (s=this.storage[e])==null?void 0:s[r]}async find(e,r){return this.storage[e]??{}}async upsert(e,r,s){return this.storage[e]??={},this.storage[e][r]=s,s}};var d=z.string().nanoid(),v=z.object({_id:d,type:z.literal("SUBSCRIBE"),resource:z.string()}),q=z.object({_id:d,type:z.literal("SYNC"),lastSyncedAt:z.string().optional(),resources:z.string().array().optional()}),R=z.record(z.object({value:z.string().or(z.number()).or(z.boolean()).or(z.date()),_meta:z.object({timestamp:z.string().optional()}).optional()})).superRefine((a,e)=>{a.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),T=z.object({_id:d,type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string(),payload:R}),b=z.union([v,T,q]),x=z.object({_id:d,type:z.literal("SYNC"),resource:z.string(),data:z.record(R)}),j=z.object({_id:d,type:z.literal("REJECT"),resource:z.string()});z.union([T,x,j]);var _=a=>{let e={},r={};return a.subscribeToMutations(s=>{console.log("Mutation propagated:",s),Object.entries(r[s.resource]??{}).forEach(([i,p])=>{var o;(o=e[i])==null||o.send(JSON.stringify(s));});}),s=>{let i=nanoid();e[i]=s,console.log("Client connected:",i),s.on("message",async p=>{try{console.log("Message received from the client:",p);let o=b.parse(JSON.parse(p.toString()));if(o.type==="SUBSCRIBE"){let{resource:n}=o;r[n]||(r[n]={}),r[n][i]={};}else if(o.type==="SYNC"){let{resources:n}=o,c=n??Object.keys(a.schema);console.log("Syncing resources:",c),await Promise.all(c.map(async u=>{let l=await a.handleRequest({req:{type:"FIND",resourceName:u,context:{}}});if(!l||!l.data)throw new Error("Invalid resource");s.send(JSON.stringify({_id:o._id,type:"SYNC",resource:u,data:Object.fromEntries(Object.entries(l.data??{}).map(([f,M])=>[f,M.value]))}));}));}else if(o.type==="MUTATE"){let{resource:n}=o;console.log("Received mutation from client:",o);try{let c=await a.handleRequest({req:{type:"SET",resourceName:n,payload:o.payload,context:{messageId:o._id},resourceId:o.resourceId}}).catch(u=>(console.error("Error handling mutation from the client:",u),null));(!c||!c.acceptedValues||Object.keys(c.acceptedValues).length===0)&&s.send(JSON.stringify({_id:o._id,type:"REJECT",resource:n}));}catch(c){s.send(JSON.stringify({_id:o._id,type:"REJECT",resource:n})),console.error("Error parsing mutation from the client:",c);}}}catch(o){console.error("Error handling message from the client:",o);}}),s.on("close",()=>{console.log("Connection closed",i),delete e[i];});}};var g=class a{routes;constructor(e){this.routes=e.routes;}static create(e){return new a(e)}},V=a=>g.create({...a}),h=class{shape;constructor(e){this.shape=e;}async handleFind(e){return {data:await e.db.find(e.req.resourceName,e.req.where),acceptedValues:null}}async handleSet(e){if(!e.req.payload)throw new Error("Payload is required");if(!e.req.resourceId)throw new Error("ResourceId is required");let r=await e.db.findById(e.req.resourceName,e.req.resourceId),[s,i]=this.shape.mergeMutation("set",e.req.payload,r);if(!i){if(!r)throw new Error("Mutation rejected");return {data:r,acceptedValues:null}}return {data:await e.db.upsert(e.req.resourceName,e.req.resourceId,s),acceptedValues:i}}async handleRequest(e){switch(e.req.type){case "FIND":return this.handleFind(e);case "SET":return this.handleSet(e);default:throw new Error("Invalid request type")}}},Z=()=>a=>new h(a),m=class a{router;storage;schema;mutationSubscriptions=new Set;constructor(e){this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.storage.updateSchema(this.schema);}static create(e){return new a(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){var s;let r=await((s=this.router.routes[e.req.resourceName])==null?void 0:s.handleRequest({req:e.req,db:this.storage}));return r&&e.req.type==="SET"&&r.acceptedValues&&Object.keys(r.acceptedValues).length>0&&this.mutationSubscriptions.forEach(i=>{i({_id:e.req.context.messageId??nanoid(),type:"MUTATE",resource:e.req.resourceName,payload:r.acceptedValues??{},resourceId:e.req.resourceId});}),r}},k=m.create;export{S as InMemoryStorage,h as Route,g as Router,m as Server,y as Storage,Z as routeFactory,V as router,k as server,_ as webSocketAdapter};
|
|
1
|
+
import {a,b}from'./chunk-EK7ODJWE.js';import he,{parse}from'qs';import {z as z$1}from'zod';import I from'node:crypto';import {Kysely,PostgresDialect}from'kysely';var P=a(E=>{Object.defineProperty(E,"__esModule",{value:true});E.parse=le;E.serialize=pe;var oe=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ie=/^[\u0021-\u003A\u003C-\u007E]*$/,se=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ce=/^[\u0020-\u003A\u003D-\u007E]*$/,ue=Object.prototype.toString,de=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function le(r,e){let t=new de,n=r.length;if(n<2)return t;let a=(e==null?void 0:e.decode)||me,o=0;do{let i=r.indexOf("=",o);if(i===-1)break;let u=r.indexOf(";",o),s=u===-1?n:u;if(i>s){o=r.lastIndexOf(";",i-1)+1;continue}let h=V(r,o,i),m=_(r,i,h),l=r.slice(h,m);if(t[l]===void 0){let p=V(r,i+1,s),d=_(r,s,p),c=a(r.slice(p,d));t[l]=c;}o=s+1;}while(o<n);return t}function V(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function _(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function pe(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!oe.test(r))throw new TypeError(`argument name is invalid: ${r}`);let a=n(e);if(!ie.test(a))throw new TypeError(`argument val is invalid: ${e}`);let o=r+"="+a;if(!t)return o;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);o+="; Max-Age="+t.maxAge;}if(t.domain){if(!se.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);o+="; Domain="+t.domain;}if(t.path){if(!ce.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);o+="; Path="+t.path;}if(t.expires){if(!ye(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);o+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(o+="; HttpOnly"),t.secure&&(o+="; Secure"),t.partitioned&&(o+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":o+="; Priority=Low";break;case "medium":o+="; Priority=Medium";break;case "high":o+="; 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":o+="; SameSite=Strict";break;case "lax":o+="; SameSite=Lax";break;case "none":o+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return o}function me(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function ye(r){return ue.call(r)==="[object Date]"}});var Z=b(P(),1);var $=z$1.object({type:z$1.literal("QUERY"),resource:z$1.string(),where:z$1.record(z$1.any()).optional(),include:z$1.record(z$1.any()).optional()}),L=z$1.record(z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()),_meta:z$1.object({timestamp:z$1.string().optional()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),q=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string()}),S=q.extend({procedure:z$1.string(),payload:z$1.any().optional()}),M=q.extend({resourceId:z$1.string(),payload:L});z$1.union([S,M]);var F=$.omit({type:true,resource:true}),N=S.omit({id:true,type:true,resource:true,procedure:true}),j=M.omit({id:true,type:true,resource:true});z$1.union([j,N]);var H=r=>async e=>{var t;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,a={headers:n,cookies:n.cookie?Z.default.parse(n.cookie):{}},o=new URL(e.url),i=o.pathname.split("/"),u=o.searchParams,s=he.parse(u.toString()),h=await((t=r.contextProvider)==null?void 0:t.call(r,{transport:"HTTP",headers:a.headers,cookies:a.cookies,query:s}))??{};if(e.method==="GET"){let m=i[i.length-1],{success:l,data:p,error:d}=F.safeParse(s);if(!l)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:d},{status:400});let c=await r.handleRequest({req:{...a,type:"QUERY",resourceName:m,context:h,where:p.where,query:s}});return !c||!c.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(c.data)}if(e.method==="POST")try{let m=i[i.length-1],l=i[i.length-2],p=e.body?await e.json():{},d;if(m==="set"){let{success:b,data:g,error:w}=j.safeParse(p);if(!b)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:w},{status:400});d=g;}else {let{success:b,data:g,error:w}=N.safeParse(p);if(!b)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:w},{status:400});d=g;}let c=await r.handleRequest({req:{...a,type:"MUTATE",resourceName:l,input:d.payload,context:h,resourceId:d.resourceId,procedure:m!=="set"?m:void 0,query:{}}});return Response.json(c)}catch(m){return console.error("Error parsing mutation from the client:",m),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 J=b(P(),1);var T=z$1.string(),ge=z$1.object({id:T,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),Te=z$1.object({id:T,type:z$1.literal("SYNC"),lastSyncedAt:z$1.string().optional(),resources:z$1.string().array().optional(),where:z$1.record(z$1.any()).optional()}),G=M.extend({id:T}),Re=S.extend({id:T}),xe=z$1.union([Re,G]),B=z$1.union([ge,Te,xe]),be=z$1.object({id:T,type:z$1.literal("SYNC"),resource:z$1.string(),data:z$1.record(L)}),we=z$1.object({id:T,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),Se=z$1.object({id:T,type:z$1.literal("REPLY"),data:z$1.any()});z$1.union([be,we,Se,G]);var W="0123456789ABCDEFGHJKMNPQRSTVWXYZ",v=32;var Me=16,K=10,Q=0xffffffffffff;var R;(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";})(R||(R={}));var x=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function ve(r){let e=Math.floor(r()*v);return e===v&&(e=v-1),W.charAt(e)}function Ee(r){var n;let e=Ie(),t=e&&(e.crypto||e.msCrypto)||(typeof I<"u"?I:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let a=new Uint8Array(1);return t.getRandomValues(a),a[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=I)!=null&&n.randomBytes)return ()=>I.randomBytes(1).readUInt8()/255;throw new x(R.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ie(){return Le()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ae(r,e){let t="";for(;r>0;r--)t=ve(e)+t;return t}function Pe(r,e=K){if(isNaN(r))throw new x(R.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>Q)throw new x(R.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${Q}: ${r}`);if(r<0)throw new x(R.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new x(R.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let a=e;a>0;a--)t=r%v,n=W.charAt(t)+n,r=(r-t)/v;return n}function Le(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Y(r,e){let t=Ee(),n=Date.now();return Pe(n,K)+Ae(Me,t)}var O=()=>Y().toLowerCase();var X=r=>{let e={},t={};return r.subscribeToMutations(n=>{let a=n;!a.resourceId||!a.payload||(console.log("Mutation propagated:",a),Object.entries(t[a.resource]??{}).forEach(([o,i])=>{var u;(u=e[o])==null||u.send(JSON.stringify({...a,id:a.id??O()}));}));}),(n,a)=>{var m;let o=l=>{n.send(JSON.stringify(l));},i=O(),u={headers:a.headers,cookies:typeof a.headers.cookie=="string"?J.default.parse(a.headers.cookie):{}},s=parse(a.url.split("?")[1]),h=(m=r.contextProvider)==null?void 0:m.call(r,{transport:"WEBSOCKET",headers:u.headers,cookies:u.cookies,query:s});e[i]=n,console.log("Client connected:",i),n.on("message",async l=>{try{console.log("Message received from the client:",l);let p=B.parse(JSON.parse(l.toString()));if(p.type==="SUBSCRIBE"){let{resource:d}=p;t[d]||(t[d]={}),t[d][i]={};}else if(p.type==="SYNC"){let{resources:d}=p,c=d??Object.keys(r.schema);console.log("Syncing resources:",c),await Promise.all(c.map(async b=>{let g=await r.handleRequest({req:{...u,type:"QUERY",resourceName:b,context:await h??{},query:s}});if(!g||!g.data)throw new Error("Invalid resource");o({id:p.id,type:"SYNC",resource:b,data:Object.fromEntries(Object.entries(g.data??{}).map(([w,ne])=>[w,ne.value]))});}));}else if(p.type==="MUTATE"){let{resource:d}=p;console.log("Received mutation from client:",p);try{let c=await r.handleRequest({req:{...u,type:"MUTATE",resourceName:d,input:p.payload,context:{messageId:p.id,...await h??{}},resourceId:p.resourceId,procedure:p.procedure,query:s}});p.procedure&&o({id:p.id,type:"REPLY",data:c});}catch(c){o({id:p.id,type:"REJECT",resource:d,message:c.message}),console.error("Error parsing mutation from the client:",c);}}}catch(p){console.error("Error handling message from the client:",p);}}),n.on("close",()=>{console.log("Connection closed",i),delete e[i];for(let l of Object.values(t))delete l[i];});}};function ee(r){let e=`${r.protocol}://${r.hostname}${r.url}`,t=new Headers;return Object.entries(r.headers).forEach(([n,a])=>{a&&t.set(n,Array.isArray(a)?a.join(","):a);}),new Request(e,{method:r.method,headers:t,body:r.body&&r.method!=="GET"?JSON.stringify(r.body):void 0})}var pt=(r,e,t)=>{r.ws(`${(t==null?void 0:t.basePath)??""}/ws`,X(e)),r.use(`${(t==null?void 0:t.basePath)??""}/`,(n,a)=>{H(e)(ee(n)).then(i=>i.json().then(u=>a.status(i.status).send(u)));});};var C=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},ht=r=>C.create({...r}),Oe=r=>({handler:e=>({inputValidator:r??z$1.undefined(),handler:e})}),z=class r{_resourceSchema;resourceName;middlewares;customMutations;constructor(e,t){this.resourceName=e,this.middlewares=new Set,this.customMutations=t??{};}handleFind=async({req:e,db:t})=>({data:await t.find(e.resourceName,e.where),acceptedValues:null});handleSet=async({req:e,db:t,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.findById(e.resourceName,e.resourceId),[o,i]=n[this.resourceName].mergeMutation("set",e.input,a);if(!i)throw new Error("Mutation rejected");return {data:await t.upsert(e.resourceName,e.resourceId,o),acceptedValues:i}};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){if(this.customMutations[n.procedure]){let a=this.customMutations[n.procedure].inputValidator.parse(n.input);return n.input=a,this.customMutations[n.procedure].handler({req:n,db:e.db,schema:e.schema})}}else return this.handleSet({req:n,db:e.db,schema:e.schema});throw new Error("Invalid request")})();return await Array.from(this.middlewares.values()).reduceRight((n,a)=>o=>a({req:o,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:Oe}))}},k=class r{middlewares;constructor(e=[]){this.middlewares=e;}createBasicRoute(e){return new z(e.name).use(...this.middlewares)}use(...e){return new r([...this.middlewares,...e])}static create(){return new r}},gt=k.create;var A=class{},te=class extends A{storage={};async updateSchema(e){this.storage=Object.entries(e).reduce((t,[n,a])=>(t[a.name]={},t),{});}async findById(e,t){var n;return (n=this.storage[e])==null?void 0:n[t]}async find(e,t){return this.storage[e]??{}}async upsert(e,t,n){return this.storage[e]??={},this.storage[e][t]=n,n}},re=class extends A{db;schema;constructor(e){super(),this.db=new Kysely({dialect:new PostgresDialect({pool:e})});}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,a]of Object.entries(e)){let o=t.find(s=>s.name===n);o||await this.db.schema.createTable(n).ifNotExists().execute();let i=`${n}_meta`,u=t.find(s=>s.name===i);u||await this.db.schema.createTable(i).ifNotExists().execute();for(let[s,h]of Object.entries(a.fields)){let m=o==null?void 0:o.columns.find(d=>d.name===s),l=h.getStorageFieldType();m?m.dataType!==l.type&&console.error("Column type mismatch:",s,"expected to have type:",l.type,"but has type:",m.dataType):(await this.db.schema.alterTable(n).addColumn(s,l.type,d=>{let c=d;return l.unique&&(c=c.unique()),l.nullable||(c=c.notNull()),l.references&&(c=c.references(l.references)),l.primary&&(c=c.primaryKey()),l.default!==void 0&&(c=c.defaultTo(l.default)),c}).execute().catch(d=>{throw console.error("Error adding column",s,d),d}),l.index&&await this.db.schema.createIndex(`${n}_${s}_index`).on(n).column(s).execute().catch(d=>{})),(u==null?void 0:u.columns.find(d=>d.name===s))||await this.db.schema.alterTable(i).addColumn(s,"varchar",d=>{let c=d;return l.primary&&(c=c.primaryKey().references(`${n}.${s}`)),c}).execute();}}}async findById(e,t){let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).executeTakeFirst(),a=await this.db.selectFrom(`${e}_meta`).where("id","=",t).selectAll(`${e}_meta`).executeTakeFirst();if(!(!n||!a))return this.convertToMaterializedLiveType(n,a)}async find(e,t){let a=await this.applyWhere(e,this.db.selectFrom(e).selectAll(e),t).execute(),o=Object.fromEntries(a.map(s=>{let{id:h,...m}=s;return [h,m]}));if(Object.keys(o).length===0)return {};let i=Object.fromEntries((await this.db.selectFrom(`${e}_meta`).selectAll().where("id","in",Object.keys(o)).execute()).map(s=>{let{id:h,...m}=s;return [h,m]}));return Object.entries(o).reduce((s,[h,m])=>(i[h]&&(s[h]=this.convertToMaterializedLiveType(m,i[h])),s),{})}async upsert(e,t,n){return await this.db.transaction().execute(async a=>{let o=!!await a.selectFrom(e).select("id").where("id","=",t).executeTakeFirst(),i={},u={};for(let[s,h]of Object.entries(n.value))i[s]=h.value,u[s]=h._meta.timestamp;o?await Promise.all([a.updateTable(e).set(i).where("id","=",t).execute(),a.updateTable(`${e}_meta`).set(u).where("id","=",t).execute()]):await Promise.all([a.insertInto(e).values({...i,id:t}).execute(),a.insertInto(`${e}_meta`).values({...u,id:t}).execute()]);}),n}convertToMaterializedLiveType(e,t){return {value:Object.fromEntries(Object.entries(e).flatMap(([n,a])=>t?[[n,{value:a,_meta:{timestamp:t==null?void 0:t[n]}}]]:[]))}}applyWhere(e,t,n){if(!n)return t;if(!this.schema)throw new Error("Schema not initialized");let a=this.schema[e];if(!a)throw new Error("Resource not found");for(let[o,i]of Object.entries(n))if(a.fields[o])t=t.where(`${e}.${o}`,"=",i);else if(a.relations[o]){let u=a.relations[o],s=u.entity.name,h=u.type==="one"?"id":u.foreignColumn,m=u.type==="one"?u.relationalColumn:"id";t=t.leftJoin(s,`${s}.${h}`,`${e}.${m}`),t=this.applyWhere(s,t,i);}return t}};var D=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,a)=>o=>a({req:o,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&&this.mutationSubscriptions.forEach(n=>{n({id:e.req.context.messageId,type:"MUTATE",resource:e.req.resourceName,payload:t.acceptedValues??{},resourceId:e.req.resourceId});}),t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}},St=D.create;
|
|
2
|
+
export{te as InMemoryStorage,z as Route,k as RouteFactory,C as Router,re as SQLStorage,D as Server,A as Storage,pt as expressAdapter,gt as routeFactory,ht as router,St as server};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@live-state/sync",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -20,27 +20,23 @@
|
|
|
20
20
|
"dist/**"
|
|
21
21
|
],
|
|
22
22
|
"type": "module",
|
|
23
|
-
"scripts": {
|
|
24
|
-
"build": "tsup",
|
|
25
|
-
"dev": "tsup --watch",
|
|
26
|
-
"lint": "eslint src/",
|
|
27
|
-
"typecheck": "tsc --noEmit",
|
|
28
|
-
"test": "jest"
|
|
29
|
-
},
|
|
30
23
|
"devDependencies": {
|
|
31
|
-
"@
|
|
32
|
-
"@repo/typescript-config": "workspace:*",
|
|
24
|
+
"@types/express": "^4.17.21",
|
|
33
25
|
"@types/express-ws": "^3.0.5",
|
|
34
26
|
"@types/node": "^20.11.24",
|
|
27
|
+
"@types/qs": "^6.14.0",
|
|
35
28
|
"@types/ws": "^8.5.13",
|
|
36
|
-
"
|
|
29
|
+
"cookie": "^1.0.2",
|
|
30
|
+
"express": "^4.21.2",
|
|
37
31
|
"react": "18.0.0",
|
|
38
32
|
"tsup": "^8.0.2",
|
|
39
|
-
"typescript": "5.5.4"
|
|
33
|
+
"typescript": "5.5.4",
|
|
34
|
+
"ulid": "^3.0.0",
|
|
35
|
+
"@repo/typescript-config": "0.0.0"
|
|
40
36
|
},
|
|
41
37
|
"dependencies": {
|
|
42
|
-
"
|
|
43
|
-
"
|
|
38
|
+
"kysely": "^0.28.2",
|
|
39
|
+
"qs": "^6.14.0",
|
|
44
40
|
"ws": "^8.18.0",
|
|
45
41
|
"zod": "^3.24.1"
|
|
46
42
|
},
|
|
@@ -59,6 +55,11 @@
|
|
|
59
55
|
"types": "./src/client/index.ts",
|
|
60
56
|
"import": "./dist/client.js",
|
|
61
57
|
"require": "./dist/client.js"
|
|
58
|
+
},
|
|
59
|
+
"./client/fetch": {
|
|
60
|
+
"types": "./src/client/fetch-client.ts",
|
|
61
|
+
"import": "./dist/fetch-client.js",
|
|
62
|
+
"require": "./dist/fetch-client.js"
|
|
62
63
|
}
|
|
63
64
|
},
|
|
64
65
|
"peerDependencies": {
|
|
@@ -72,5 +73,11 @@
|
|
|
72
73
|
"@types/react": {
|
|
73
74
|
"optional": true
|
|
74
75
|
}
|
|
76
|
+
},
|
|
77
|
+
"scripts": {
|
|
78
|
+
"build": "tsup",
|
|
79
|
+
"dev": "tsup --watch",
|
|
80
|
+
"lint": "eslint src/",
|
|
81
|
+
"typecheck": "tsc --noEmit"
|
|
75
82
|
}
|
|
76
|
-
}
|
|
83
|
+
}
|