@live-state/sync 0.0.1-alpha.1 → 0.0.1-alpha.2

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/index.d.cts CHANGED
@@ -1,2 +1,199 @@
1
- export { C as ClientMessage, t as InferIndex, I as InferLiveObject, c as InferLiveObjectWithRelationalIds, r as InferLiveType, j as LiveNumber, e as LiveObject, L as LiveObjectAny, d as LiveObjectMutationInput, k as LiveString, p as LiveType, q as LiveTypeAny, l as LiveTypeMeta, g as MaterializedLiveObject, M as MaterializedLiveType, m as MutationType, R as Relation, S as Schema, b as ServerMessage, f as createRelations, h as createSchema, i as inferValue, n as number, o as object, s as string } from './index-sSVirsfN.cjs';
2
- import 'zod';
1
+ type LiveTypeMeta = {};
2
+ type MutationType = "set";
3
+ type StorageFieldType = {
4
+ type: string;
5
+ nullable: boolean;
6
+ default?: any;
7
+ unique?: boolean;
8
+ index?: boolean;
9
+ primary?: boolean;
10
+ references?: string;
11
+ };
12
+ declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
13
+ value: Value;
14
+ _meta: keyof Meta extends never ? never : Meta;
15
+ }> {
16
+ readonly _value: Value;
17
+ readonly _meta: Meta;
18
+ readonly _encodeInput: EncodeInput;
19
+ readonly _decodeInput: DecodeInput;
20
+ abstract encodeMutation(mutationType: MutationType, input: EncodeInput, timestamp: string): DecodeInput;
21
+ /**
22
+ * Merges the materialized shape with the encoded mutation
23
+ * @param mutationType The type of mutation
24
+ * @param encodedMutation The encoded mutation
25
+ * @param materializedShape The materialized shape
26
+ * @returns A tuple of the new materialized shape and the accepted diff
27
+ */
28
+ abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
29
+ abstract getStorageFieldType(): StorageFieldType;
30
+ }
31
+ type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
32
+ type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
33
+ [K in keyof T["_value"]]: InferLiveType<T["_value"][K]>;
34
+ } : T["_value"];
35
+ type InferIndex<T extends LiveTypeAny> = string;
36
+
37
+ declare class OptionalLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | undefined, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
38
+ readonly inner: T;
39
+ constructor(inner: T);
40
+ encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): T["_decodeInput"];
41
+ mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>> | undefined): [
42
+ MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>>,
43
+ T["_decodeInput"] | null
44
+ ];
45
+ getStorageFieldType(): StorageFieldType;
46
+ }
47
+ type LiveAtomicTypeMeta = {
48
+ timestamp: string;
49
+ } & LiveTypeMeta;
50
+ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
51
+ value: Value;
52
+ _meta: LiveAtomicTypeMeta;
53
+ }> {
54
+ readonly storageType: string;
55
+ readonly convertFunc?: (value: any) => Value;
56
+ readonly isIndex: boolean;
57
+ readonly isUnique: boolean;
58
+ readonly defaultValue?: Value;
59
+ readonly foreignReference?: string;
60
+ readonly isPrimary: boolean;
61
+ constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: Value, references?: string, primary?: boolean);
62
+ encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
63
+ value: Value;
64
+ _meta: LiveAtomicTypeMeta;
65
+ };
66
+ mergeMutation(mutationType: MutationType, encodedMutation: {
67
+ value: Value;
68
+ _meta: LiveAtomicTypeMeta;
69
+ }, materializedShape?: MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
70
+ value: Value;
71
+ _meta: LiveAtomicTypeMeta;
72
+ }>>): [
73
+ MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
74
+ value: Value;
75
+ _meta: LiveAtomicTypeMeta;
76
+ }>>,
77
+ {
78
+ value: Value;
79
+ _meta: LiveAtomicTypeMeta;
80
+ } | null
81
+ ];
82
+ getStorageFieldType(): StorageFieldType;
83
+ unique(): LiveAtomicType<Value>;
84
+ index(): LiveAtomicType<Value>;
85
+ default(value: Value): LiveAtomicType<Value>;
86
+ primary(): LiveAtomicType<Value>;
87
+ optional(): OptionalLiveType<this>;
88
+ }
89
+ declare class LiveNumber extends LiveAtomicType<number> {
90
+ private constructor();
91
+ static create(): LiveNumber;
92
+ }
93
+ declare const number: typeof LiveNumber.create;
94
+ declare class LiveString extends LiveAtomicType<string> {
95
+ private constructor();
96
+ static create(): LiveString;
97
+ static createId(): LiveAtomicType<string>;
98
+ static createReference(foreignField: `${string}.${string}`): LiveString;
99
+ }
100
+ declare const string: typeof LiveString.create;
101
+ declare const id: typeof LiveString.createId;
102
+ declare const reference: typeof LiveString.createReference;
103
+
104
+ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
105
+ [K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
106
+ };
107
+ type InferLiveObject<T extends LiveObjectAny> = InferLiveObjectWithoutRelations<T> & {
108
+ [K in keyof T["relations"]]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
109
+ };
110
+ type InferRelationalColumns<T extends Record<string, RelationAny>> = {
111
+ [K in keyof T as T[K] extends Relation<any, any, any, infer ColumnName, any, any> ? ColumnName extends string ? ColumnName : never : never]: T[K]["type"] extends "one" ? T[K] extends Relation<infer Entity, any, any, any, any, any> ? T[K]["required"] extends true ? InferIndex<Entity> : InferIndex<Entity> | undefined : never : never;
112
+ };
113
+ type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
114
+ type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
115
+ declare class LiveObject<TName extends string, TSchema extends Record<string, LiveTypeAny>, TRelations extends Record<string, RelationAny>> extends LiveType<TSchema, LiveTypeMeta, LiveObjectMutationInput<any>, Record<string, MaterializedLiveType<LiveTypeAny>>> {
116
+ readonly name: TName;
117
+ readonly fields: TSchema;
118
+ readonly relations: TRelations;
119
+ constructor(name: TName, fields: TSchema, relations?: TRelations);
120
+ encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
121
+ mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
122
+ setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
123
+ getStorageFieldType(): StorageFieldType;
124
+ static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
125
+ }
126
+ declare const object: typeof LiveObject.create;
127
+ type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
128
+ declare class Relation<TEntity extends LiveObjectAny, TSourceEntity extends LiveObjectAny, TType extends "one" | "many", TRelationalColumn extends keyof TSourceEntity["fields"], TForeignColumn extends keyof TEntity["fields"], TRequired extends boolean> extends LiveType<InferIndex<TEntity>, {
129
+ timestamp: string;
130
+ } & LiveTypeMeta> {
131
+ readonly entity: TEntity;
132
+ readonly type: TType;
133
+ readonly required: TRequired;
134
+ readonly relationalColumn?: TRelationalColumn;
135
+ readonly foreignColumn?: TForeignColumn;
136
+ readonly sourceEntity: TSourceEntity;
137
+ private constructor();
138
+ encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
139
+ value: string;
140
+ _meta: {
141
+ timestamp: string;
142
+ };
143
+ };
144
+ mergeMutation(mutationType: MutationType, encodedMutation: {
145
+ value: string;
146
+ _meta: {
147
+ timestamp: string;
148
+ };
149
+ }, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
150
+ MaterializedLiveType<LiveString>,
151
+ {
152
+ value: string;
153
+ _meta: {
154
+ timestamp: string;
155
+ };
156
+ } | null
157
+ ];
158
+ getStorageFieldType(): StorageFieldType;
159
+ static createOneFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TOriginEntity["fields"], TRequired extends boolean = false>(entity: TEntity, column: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "one", TColumn, never, TRequired>;
160
+ static createManyFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TEntity["fields"], TRequired extends boolean = false>(entity: TEntity, foreignColumn: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "many", never, TColumn, TRequired>;
161
+ }
162
+ type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
163
+ declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
164
+ one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
165
+ many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
166
+ }) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
167
+ type MaterializedLiveType<T extends LiveTypeAny> = {
168
+ value: T["_value"] extends Record<string, LiveTypeAny> ? {
169
+ [K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
170
+ } : T["_value"];
171
+ _meta: T["_meta"];
172
+ };
173
+ declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
174
+ type ExtractObjectValues<T> = T[keyof T];
175
+ type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
176
+ $type: "relations";
177
+ objectName: TObjectName;
178
+ relations: TRelations;
179
+ };
180
+ type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
181
+ [K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
182
+ [K2 in keyof TRawSchema[K]["relations"]]: Relation<ParseObjectFromSchema<TRawSchema, TRawSchema[K]["relations"][K2]["entity"]["name"]>, TRawSchema[K]["relations"][K2]["sourceEntity"], TRawSchema[K]["relations"][K2]["type"], Exclude<TRawSchema[K]["relations"][K2]["relationalColumn"], undefined>, Exclude<TRawSchema[K]["relations"][K2]["foreignColumn"], undefined>, TRawSchema[K]["relations"][K2]["required"]>;
183
+ } : never : never;
184
+ }>;
185
+ type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
186
+ [K in keyof TRawSchema]: TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] extends TObjectName ? LiveObject<TRawSchema[K]["name"], TRawSchema[K]["fields"], ParseRelationsFromSchema<TRawSchema, TRawSchema[K]["name"]>> : never : never;
187
+ }>;
188
+ type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
189
+ type Schema<TRawSchema extends RawSchema> = {
190
+ [K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
191
+ };
192
+ declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
193
+ type WhereClause<T extends LiveObjectAny> = {
194
+ [K in keyof T["fields"]]?: InferLiveType<T["fields"][K]>;
195
+ } & {
196
+ [K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
197
+ };
198
+
199
+ export { type InferIndex, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, createRelations, createSchema, id, inferValue, number, object, reference, string };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,199 @@
1
- export { C as ClientMessage, t as InferIndex, I as InferLiveObject, c as InferLiveObjectWithRelationalIds, r as InferLiveType, j as LiveNumber, e as LiveObject, L as LiveObjectAny, d as LiveObjectMutationInput, k as LiveString, p as LiveType, q as LiveTypeAny, l as LiveTypeMeta, g as MaterializedLiveObject, M as MaterializedLiveType, m as MutationType, R as Relation, S as Schema, b as ServerMessage, f as createRelations, h as createSchema, i as inferValue, n as number, o as object, s as string } from './index-sSVirsfN.js';
2
- import 'zod';
1
+ type LiveTypeMeta = {};
2
+ type MutationType = "set";
3
+ type StorageFieldType = {
4
+ type: string;
5
+ nullable: boolean;
6
+ default?: any;
7
+ unique?: boolean;
8
+ index?: boolean;
9
+ primary?: boolean;
10
+ references?: string;
11
+ };
12
+ declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
13
+ value: Value;
14
+ _meta: keyof Meta extends never ? never : Meta;
15
+ }> {
16
+ readonly _value: Value;
17
+ readonly _meta: Meta;
18
+ readonly _encodeInput: EncodeInput;
19
+ readonly _decodeInput: DecodeInput;
20
+ abstract encodeMutation(mutationType: MutationType, input: EncodeInput, timestamp: string): DecodeInput;
21
+ /**
22
+ * Merges the materialized shape with the encoded mutation
23
+ * @param mutationType The type of mutation
24
+ * @param encodedMutation The encoded mutation
25
+ * @param materializedShape The materialized shape
26
+ * @returns A tuple of the new materialized shape and the accepted diff
27
+ */
28
+ abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
29
+ abstract getStorageFieldType(): StorageFieldType;
30
+ }
31
+ type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
32
+ type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
33
+ [K in keyof T["_value"]]: InferLiveType<T["_value"][K]>;
34
+ } : T["_value"];
35
+ type InferIndex<T extends LiveTypeAny> = string;
36
+
37
+ declare class OptionalLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | undefined, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
38
+ readonly inner: T;
39
+ constructor(inner: T);
40
+ encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): T["_decodeInput"];
41
+ mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>> | undefined): [
42
+ MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>>,
43
+ T["_decodeInput"] | null
44
+ ];
45
+ getStorageFieldType(): StorageFieldType;
46
+ }
47
+ type LiveAtomicTypeMeta = {
48
+ timestamp: string;
49
+ } & LiveTypeMeta;
50
+ declare class LiveAtomicType<Value> extends LiveType<Value, LiveAtomicTypeMeta, Value, {
51
+ value: Value;
52
+ _meta: LiveAtomicTypeMeta;
53
+ }> {
54
+ readonly storageType: string;
55
+ readonly convertFunc?: (value: any) => Value;
56
+ readonly isIndex: boolean;
57
+ readonly isUnique: boolean;
58
+ readonly defaultValue?: Value;
59
+ readonly foreignReference?: string;
60
+ readonly isPrimary: boolean;
61
+ constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: Value, references?: string, primary?: boolean);
62
+ encodeMutation(mutationType: MutationType, input: Value, timestamp: string): {
63
+ value: Value;
64
+ _meta: LiveAtomicTypeMeta;
65
+ };
66
+ mergeMutation(mutationType: MutationType, encodedMutation: {
67
+ value: Value;
68
+ _meta: LiveAtomicTypeMeta;
69
+ }, materializedShape?: MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
70
+ value: Value;
71
+ _meta: LiveAtomicTypeMeta;
72
+ }>>): [
73
+ MaterializedLiveType<LiveType<Value, LiveAtomicTypeMeta, Value | Partial<Value>, {
74
+ value: Value;
75
+ _meta: LiveAtomicTypeMeta;
76
+ }>>,
77
+ {
78
+ value: Value;
79
+ _meta: LiveAtomicTypeMeta;
80
+ } | null
81
+ ];
82
+ getStorageFieldType(): StorageFieldType;
83
+ unique(): LiveAtomicType<Value>;
84
+ index(): LiveAtomicType<Value>;
85
+ default(value: Value): LiveAtomicType<Value>;
86
+ primary(): LiveAtomicType<Value>;
87
+ optional(): OptionalLiveType<this>;
88
+ }
89
+ declare class LiveNumber extends LiveAtomicType<number> {
90
+ private constructor();
91
+ static create(): LiveNumber;
92
+ }
93
+ declare const number: typeof LiveNumber.create;
94
+ declare class LiveString extends LiveAtomicType<string> {
95
+ private constructor();
96
+ static create(): LiveString;
97
+ static createId(): LiveAtomicType<string>;
98
+ static createReference(foreignField: `${string}.${string}`): LiveString;
99
+ }
100
+ declare const string: typeof LiveString.create;
101
+ declare const id: typeof LiveString.createId;
102
+ declare const reference: typeof LiveString.createReference;
103
+
104
+ type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
105
+ [K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
106
+ };
107
+ type InferLiveObject<T extends LiveObjectAny> = InferLiveObjectWithoutRelations<T> & {
108
+ [K in keyof T["relations"]]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
109
+ };
110
+ type InferRelationalColumns<T extends Record<string, RelationAny>> = {
111
+ [K in keyof T as T[K] extends Relation<any, any, any, infer ColumnName, any, any> ? ColumnName extends string ? ColumnName : never : never]: T[K]["type"] extends "one" ? T[K] extends Relation<infer Entity, any, any, any, any, any> ? T[K]["required"] extends true ? InferIndex<Entity> : InferIndex<Entity> | undefined : never : never;
112
+ };
113
+ type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
114
+ type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
115
+ declare class LiveObject<TName extends string, TSchema extends Record<string, LiveTypeAny>, TRelations extends Record<string, RelationAny>> extends LiveType<TSchema, LiveTypeMeta, LiveObjectMutationInput<any>, Record<string, MaterializedLiveType<LiveTypeAny>>> {
116
+ readonly name: TName;
117
+ readonly fields: TSchema;
118
+ readonly relations: TRelations;
119
+ constructor(name: TName, fields: TSchema, relations?: TRelations);
120
+ encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
121
+ mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
122
+ setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
123
+ getStorageFieldType(): StorageFieldType;
124
+ static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
125
+ }
126
+ declare const object: typeof LiveObject.create;
127
+ type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
128
+ declare class Relation<TEntity extends LiveObjectAny, TSourceEntity extends LiveObjectAny, TType extends "one" | "many", TRelationalColumn extends keyof TSourceEntity["fields"], TForeignColumn extends keyof TEntity["fields"], TRequired extends boolean> extends LiveType<InferIndex<TEntity>, {
129
+ timestamp: string;
130
+ } & LiveTypeMeta> {
131
+ readonly entity: TEntity;
132
+ readonly type: TType;
133
+ readonly required: TRequired;
134
+ readonly relationalColumn?: TRelationalColumn;
135
+ readonly foreignColumn?: TForeignColumn;
136
+ readonly sourceEntity: TSourceEntity;
137
+ private constructor();
138
+ encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
139
+ value: string;
140
+ _meta: {
141
+ timestamp: string;
142
+ };
143
+ };
144
+ mergeMutation(mutationType: MutationType, encodedMutation: {
145
+ value: string;
146
+ _meta: {
147
+ timestamp: string;
148
+ };
149
+ }, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
150
+ MaterializedLiveType<LiveString>,
151
+ {
152
+ value: string;
153
+ _meta: {
154
+ timestamp: string;
155
+ };
156
+ } | null
157
+ ];
158
+ getStorageFieldType(): StorageFieldType;
159
+ static createOneFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TOriginEntity["fields"], TRequired extends boolean = false>(entity: TEntity, column: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "one", TColumn, never, TRequired>;
160
+ static createManyFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TEntity["fields"], TRequired extends boolean = false>(entity: TEntity, foreignColumn: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "many", never, TColumn, TRequired>;
161
+ }
162
+ type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
163
+ declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
164
+ one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
165
+ many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
166
+ }) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
167
+ type MaterializedLiveType<T extends LiveTypeAny> = {
168
+ value: T["_value"] extends Record<string, LiveTypeAny> ? {
169
+ [K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
170
+ } : T["_value"];
171
+ _meta: T["_meta"];
172
+ };
173
+ declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
174
+ type ExtractObjectValues<T> = T[keyof T];
175
+ type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
176
+ $type: "relations";
177
+ objectName: TObjectName;
178
+ relations: TRelations;
179
+ };
180
+ type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
181
+ [K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
182
+ [K2 in keyof TRawSchema[K]["relations"]]: Relation<ParseObjectFromSchema<TRawSchema, TRawSchema[K]["relations"][K2]["entity"]["name"]>, TRawSchema[K]["relations"][K2]["sourceEntity"], TRawSchema[K]["relations"][K2]["type"], Exclude<TRawSchema[K]["relations"][K2]["relationalColumn"], undefined>, Exclude<TRawSchema[K]["relations"][K2]["foreignColumn"], undefined>, TRawSchema[K]["relations"][K2]["required"]>;
183
+ } : never : never;
184
+ }>;
185
+ type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
186
+ [K in keyof TRawSchema]: TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] extends TObjectName ? LiveObject<TRawSchema[K]["name"], TRawSchema[K]["fields"], ParseRelationsFromSchema<TRawSchema, TRawSchema[K]["name"]>> : never : never;
187
+ }>;
188
+ type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
189
+ type Schema<TRawSchema extends RawSchema> = {
190
+ [K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
191
+ };
192
+ declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
193
+ type WhereClause<T extends LiveObjectAny> = {
194
+ [K in keyof T["fields"]]?: InferLiveType<T["fields"][K]>;
195
+ } & {
196
+ [K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
197
+ };
198
+
199
+ export { type InferIndex, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveType, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, Relation, type Schema, type StorageFieldType, type WhereClause, createRelations, createSchema, id, inferValue, number, object, reference, string };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var o=class{_value;_meta;_encodeInput;_decodeInput};var T=class extends o{encodeMutation(n,t,e){throw new Error("Method not implemented.")}mergeMutation(n,t,e){throw new Error("Method not implemented.")}},s=class extends o{constructor(){super(),this.optional=this.optional.bind(this);}optional(){return new T}},y=class a extends s{encodeMutation(n,t,e){return {value:t,_meta:{timestamp:e}}}mergeMutation(n,t,e){return e&&e._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[e,null]:[{value:Number(t.value),_meta:t._meta},t]}static create(){return new a}},M=y.create,c=class a extends s{encodeMutation(n,t,e){return {value:t,_meta:{timestamp:e}}}mergeMutation(n,t,e){return e&&e._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[e,null]:[t,t]}static create(){return new a}},h=c.create;var u=class a extends o{name;fields;relations;constructor(n,t,e){super(),this.name=n,this.fields=t,this.relations=e??{};}encodeMutation(n,t,e){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,e)]))}mergeMutation(n,t,e){let r={};return [{value:{...(e==null?void 0:e.value)??{},...Object.fromEntries(Object.entries(t).map(([i,d])=>{let[v,m]=(this.fields[i]??this.relations[i]).mergeMutation(n,d,e==null?void 0:e.value[i]);return m&&(r[i]=m),[i,v]}))}},r]}setRelations(n){return new a(this.name,this.fields,n)}static create(n,t){return new a(n,t)}},A=u.create,l=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(n,t,e,r,i){super(),this.entity=n,this.type=t,this.required=i??false,this.relationalColumn=e,this.foreignColumn=r;}encodeMutation(n,t,e){if(n!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:e}}}mergeMutation(n,t,e){if(this.type==="many")throw new Error("Many not implemented.");return e&&e._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[e,null]:[t,t]}static createOneFactory(){return (n,t,e)=>new a(n,"one",t,void 0,e??false)}static createManyFactory(){return (n,t,e)=>new a(n,"many",void 0,t,e??false)}},K=(a,n)=>({$type:"relations",objectName:a.name,relations:n({one:l.createOneFactory(),many:l.createManyFactory()})}),p=a=>Array.isArray(a.value)?a.value.map(n=>p(n)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([n,t])=>[n,p(t)])),E=a=>Object.fromEntries(Object.entries(a).flatMap(([n,t])=>{if(t.$type==="relations")return [];let e=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(e=e.setRelations(r.relations)),[[e.name,e]]}));export{y as LiveNumber,u as LiveObject,c as LiveString,o as LiveType,l as Relation,K as createRelations,E as createSchema,p as inferValue,M as number,A as object,h as string};
1
+ import'./chunk-EK7ODJWE.js';var o=class{_value;_meta;_encodeInput;_decodeInput};var c=class extends o{inner;constructor(e){super(),this.inner=e;}encodeMutation(e,t,n){return this.inner.encodeMutation(e,t,n)}mergeMutation(e,t,n){return this.inner.mergeMutation(e,t,n)}getStorageFieldType(){return {...this.inner.getStorageFieldType(),nullable:true}}},l=class a extends o{storageType;convertFunc;isIndex;isUnique;defaultValue;foreignReference;isPrimary;constructor(e,t,n,r,i,y,T){super(),this.storageType=e,this.convertFunc=t,this.isIndex=n??false,this.isUnique=r??false,this.defaultValue=i,this.foreignReference=y,this.isPrimary=T??false;}encodeMutation(e,t,n){return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[{value:this.convertFunc?this.convertFunc(t.value):t.value,_meta:t._meta},t]}getStorageFieldType(){return {type:this.storageType,nullable:false,index:this.isIndex,unique:this.isUnique,default:this.defaultValue,references:this.foreignReference,primary:this.isPrimary}}unique(){return new a(this.storageType,this.convertFunc,this.isIndex,true,this.defaultValue,this.foreignReference,this.isPrimary)}index(){return new a(this.storageType,this.convertFunc,true,this.isUnique,this.defaultValue,this.foreignReference,this.isPrimary)}default(e){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,e,this.foreignReference,this.isPrimary)}primary(){return new a(this.storageType,this.convertFunc,this.isIndex,this.isUnique,this.defaultValue,this.foreignReference,true)}optional(){return new c(this)}},d=class a extends l{constructor(){super("integer",e=>Number(e));}static create(){return new a}},b=d.create,s=class a extends l{constructor(e){super("varchar",void 0,void 0,void 0,void 0,e);}static create(){return new a}static createId(){return new a().index().unique().primary()}static createReference(e){return new a(e)}},M=s.create,O=s.createId,j=s.createReference;var p=class a extends o{name;fields;relations;constructor(e,t,n){super(),this.name=e,this.fields=t,this.relations=n??{};}encodeMutation(e,t,n){return Object.fromEntries(Object.entries(t).map(([r,i])=>[r,(this.fields[r]??this.relations[r]).encodeMutation("set",i,n)]))}mergeMutation(e,t,n){let r={};return [{value:{...(n==null?void 0:n.value)??{},...Object.fromEntries(Object.entries(t).map(([i,y])=>{let[T,m]=(this.fields[i]??this.relations[i]).mergeMutation(e,y,n==null?void 0:n.value[i]);return m&&(r[i]=m),[i,T]}))}},r]}setRelations(e){return new a(this.name,this.fields,e)}getStorageFieldType(){throw new Error("Method not implemented.")}static create(e,t){return new a(e,t)}},F=p.create,u=class a extends o{entity;type;required;relationalColumn;foreignColumn;sourceEntity;constructor(e,t,n,r,i){super(),this.entity=e,this.type=t,this.required=i??false,this.relationalColumn=n,this.foreignColumn=r;}encodeMutation(e,t,n){if(e!=="set")throw new Error("Mutation type not implemented.");if(this.type==="many")throw new Error("Many not implemented.");return {value:t,_meta:{timestamp:n}}}mergeMutation(e,t,n){if(this.type==="many")throw new Error("Many not implemented.");return n&&n._meta.timestamp.localeCompare(t._meta.timestamp)>=0?[n,null]:[t,t]}getStorageFieldType(){return {type:"varchar",nullable:!this.required,references:`${this.entity.name}.${String(this.foreignColumn??this.relationalColumn??"id")}`}}static createOneFactory(){return (e,t,n)=>new a(e,"one",t,void 0,n??false)}static createManyFactory(){return (e,t,n)=>new a(e,"many",void 0,t,n??false)}},C=(a,e)=>({$type:"relations",objectName:a.name,relations:e({one:u.createOneFactory(),many:u.createManyFactory()})}),v=a=>{if(a)return Array.isArray(a.value)?a.value.map(e=>v(e)):typeof a.value!="object"?a.value:Object.fromEntries(Object.entries(a.value).map(([e,t])=>[e,v(t)]))},q=a=>Object.fromEntries(Object.entries(a).flatMap(([e,t])=>{if(t.$type==="relations")return [];let n=t,r=Object.values(a).find(i=>i.$type==="relations"&&i.objectName===t.name);return r&&(n=n.setRelations(r.relations)),[[n.name,n]]}));export{d as LiveNumber,p as LiveObject,s as LiveString,o as LiveType,u as Relation,C as createRelations,q as createSchema,O as id,v as inferValue,b as number,F as object,j as reference,M as string};
package/dist/server.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var nanoid=require('nanoid'),zod=require('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=zod.z.string().nanoid(),v=zod.z.object({_id:d,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),q=zod.z.object({_id:d,type:zod.z.literal("SYNC"),lastSyncedAt:zod.z.string().optional(),resources:zod.z.string().array().optional()}),R=zod.z.record(zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()),_meta:zod.z.object({timestamp:zod.z.string().optional()}).optional()})).superRefine((a,e)=>{a.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),T=zod.z.object({_id:d,type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string(),payload:R}),b=zod.z.union([v,T,q]),x=zod.z.object({_id:d,type:zod.z.literal("SYNC"),resource:zod.z.string(),data:zod.z.record(R)}),j=zod.z.object({_id:d,type:zod.z.literal("REJECT"),resource:zod.z.string()});zod.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.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.nanoid(),type:"MUTATE",resource:e.req.resourceName,payload:r.acceptedValues??{},resourceId:e.req.resourceId});}),r}},k=m.create;exports.InMemoryStorage=S;exports.Route=h;exports.Router=g;exports.Server=m;exports.Storage=y;exports.routeFactory=Z;exports.router=V;exports.server=k;exports.webSocketAdapter=_;
1
+ 'use strict';var zod=require('zod'),kysely=require('kysely'),S=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var S__default=/*#__PURE__*/_interopDefault(S);var B=Object.create;var O=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var Y=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var J=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!K.call(r,i)&&i!==t&&O(r,i,{get:()=>e[i],enumerable:!(n=G(e,i))||n.enumerable});return r};var X=(r,e,t)=>(t=r!=null?B(Q(r)):{},J(O(t,"default",{value:r,enumerable:true}),r));var U=Y(M=>{Object.defineProperty(M,"__esModule",{value:true});M.parse=de;M.serialize=le;var ie=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ae=/^[\u0021-\u003A\u003C-\u007E]*$/,oe=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,se=/^[\u0020-\u003A\u003D-\u007E]*$/,ce=Object.prototype.toString,ue=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function de(r,e){let t=new ue,n=r.length;if(n<2)return t;let i=(e==null?void 0:e.decode)||pe,a=0;do{let c=r.indexOf("=",a);if(c===-1)break;let u=r.indexOf(";",a),o=u===-1?n:u;if(c>o){a=r.lastIndexOf(";",c-1)+1;continue}let s=z(r,a,c),p=P(r,c,s),m=r.slice(s,p);if(t[m]===void 0){let b=z(r,c+1,o),y=P(r,o,b),f=i(r.slice(b,y));t[m]=f;}a=o+1;}while(a<n);return t}function z(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function P(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function le(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!ie.test(r))throw new TypeError(`argument name is invalid: ${r}`);let i=n(e);if(!ae.test(i))throw new TypeError(`argument val is invalid: ${e}`);let a=r+"="+i;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!oe.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!se.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!me(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);a+="; Expires="+t.expires.toUTCString();}if(t.httpOnly&&(a+="; HttpOnly"),t.secure&&(a+="; Secure"),t.partitioned&&(a+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case "low":a+="; Priority=Low";break;case "medium":a+="; Priority=Medium";break;case "high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case true:case "strict":a+="; SameSite=Strict";break;case "lax":a+="; SameSite=Lax";break;case "none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return a}function pe(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function me(r){return ce.call(r)==="[object Date]"}});var w=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},Oe=r=>w.create({...r}),te=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),v=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 i=await t.findById(e.resourceName,e.resourceId),[a,c]=n[this.resourceName].mergeMutation("set",e.input,i);if(!c)throw new Error("Mutation rejected");return {data:await t.upsert(e.resourceName,e.resourceId,a),acceptedValues:c}};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 i=this.customMutations[n.procedure].inputValidator.parse(n.input);return n.input=i,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,i)=>a=>i({req:a,next:n}),async n=>t(n))(e.req)}use(e){return this.middlewares.add(e),this}withMutations(e){return new r(this.resourceName,e({mutation:te}))}},je=()=>r=>new v(r.name);var R=class{},j=class extends R{storage={};async updateSchema(e){this.storage=Object.entries(e).reduce((t,[n,i])=>(t[i.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}},C=class extends R{db;schema;constructor(e){super(),this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})});}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,i]of Object.entries(e)){let a=t.find(o=>o.name===n);a||await this.db.schema.createTable(n).ifNotExists().execute();let c=`${n}_meta`,u=t.find(o=>o.name===c);u||await this.db.schema.createTable(c).ifNotExists().execute();for(let[o,s]of Object.entries(i.fields)){let p=a==null?void 0:a.columns.find(y=>y.name===o),m=s.getStorageFieldType();p?p.dataType!==m.type&&console.error("Column type mismatch:",o,"expected to have type:",m.type,"but has type:",p.dataType):(await this.db.schema.alterTable(n).addColumn(o,m.type,y=>{let f=y;return m.unique&&(f=f.unique()),m.nullable||(f=f.notNull()),m.references&&(f=f.references(m.references)),m.primary&&(f=f.primaryKey()),f}).execute().catch(y=>{throw console.error("Error adding column",o,y),y}),m.index&&await this.db.schema.createIndex(`${n}_${o}_index`).on(n).column(o).execute().catch(y=>{})),(u==null?void 0:u.columns.find(y=>y.name===o))||await this.db.schema.alterTable(c).addColumn(o,"varchar",y=>{let f=y;return m.primary&&(f=f.primaryKey().references(`${n}.${o}`)),f}).execute();}}}async findById(e,t){let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).executeTakeFirst(),i=await this.db.selectFrom(`${e}_meta`).where("id","=",t).selectAll(`${e}_meta`).executeTakeFirst();if(!(!n||!i))return this.convertToMaterializedLiveType(n,i)}async find(e,t){let i=await this.applyWhere(e,this.db.selectFrom(e).selectAll(e),t).execute(),a=Object.fromEntries(i.map(o=>{let{id:s,...p}=o;return [s,p]}));if(Object.keys(a).length===0)return {};let c=Object.fromEntries((await this.db.selectFrom(`${e}_meta`).selectAll().where("id","in",Object.keys(a)).execute()).map(o=>{let{id:s,...p}=o;return [s,p]}));return Object.entries(a).reduce((o,[s,p])=>(c[s]&&(o[s]=this.convertToMaterializedLiveType(p,c[s])),o),{})}async upsert(e,t,n){return await this.db.transaction().execute(async i=>{let a=!!await i.selectFrom(e).select("id").where("id","=",t).executeTakeFirst(),c={},u={};for(let[o,s]of Object.entries(n.value))c[o]=s.value,u[o]=s._meta.timestamp;a?await Promise.all([i.updateTable(e).set(c).where("id","=",t).execute(),i.updateTable(`${e}_meta`).set(u).where("id","=",t).execute()]):await Promise.all([i.insertInto(e).values({...c,id:t}).execute(),i.insertInto(`${e}_meta`).values({...u,id:t}).execute()]);}),n}convertToMaterializedLiveType(e,t){return {value:Object.fromEntries(Object.entries(e).flatMap(([n,i])=>t?[[n,{value:i,_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 i=this.schema[e];if(!i)throw new Error("Resource not found");for(let[a,c]of Object.entries(n))if(i.fields[a])t=t.where(`${e}.${a}`,"=",c);else if(i.relations[a]){let u=i.relations[a],o=u.entity.name,s=u.type==="one"?"id":u.foreignColumn,p=u.type==="one"?u.relationalColumn:"id";t=t.leftJoin(o,`${o}.${s}`,`${e}.${p}`),t=this.applyWhere(o,t,c);}return t}};var q=X(U());zod.z.object({type:zod.z.literal("QUERY"),resource:zod.z.string(),where:zod.z.record(zod.z.any()).optional(),include:zod.z.record(zod.z.any()).optional()});var I=zod.z.record(zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()),_meta:zod.z.object({timestamp:zod.z.string().optional()}).optional()})).superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),D=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string()}),E=D.extend({procedure:zod.z.string(),payload:zod.z.any()}),A=D.extend({resourceId:zod.z.string(),payload:I});zod.z.union([E,A]);var h=zod.z.string(),ye=zod.z.object({id:h,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),fe=zod.z.object({id:h,type:zod.z.literal("SYNC"),lastSyncedAt:zod.z.string().optional(),resources:zod.z.string().array().optional(),where:zod.z.record(zod.z.any()).optional()}),V=A.extend({id:h}),he=E.extend({id:h}),ge=zod.z.union([he,V]),$=zod.z.union([ye,fe,ge]),Te=zod.z.object({id:h,type:zod.z.literal("SYNC"),resource:zod.z.string(),data:zod.z.record(I)}),be=zod.z.object({id:h,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),xe=zod.z.object({id:h,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([Te,be,xe,V]);var _="0123456789ABCDEFGHJKMNPQRSTVWXYZ",x=32;var Re=16,F=10,k=0xffffffffffff;var g;(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";})(g||(g={}));var T=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Me(r){let e=Math.floor(r()*x);return e===x&&(e=x-1),_.charAt(e)}function Se(r){var n;let e=we(),t=e&&(e.crypto||e.msCrypto)||(typeof S__default.default<"u"?S__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return t.getRandomValues(i),i[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=S__default.default)!=null&&n.randomBytes)return ()=>S__default.default.randomBytes(1).readUInt8()/255;throw new T(g.PRNGDetectFailure,"Failed to find a reliable PRNG")}function we(){return Ee()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function ve(r,e){let t="";for(;r>0;r--)t=Me(e)+t;return t}function Ie(r,e=F){if(isNaN(r))throw new T(g.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>k)throw new T(g.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${k}: ${r}`);if(r<0)throw new T(g.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new T(g.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%x,n=_.charAt(t)+n,r=(r-t)/x;return n}function Ee(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function Z(r,e){let t=Se(),n=Date.now();return Ie(n,F)+ve(Re,t)}var L=()=>Z().toLowerCase();var tt=r=>{let e={},t={};return r.subscribeToMutations(n=>{let i=n;!i.resourceId||!i.payload||(console.log("Mutation propagated:",i),Object.entries(t[i.resource]??{}).forEach(([a,c])=>{var u;(u=e[a])==null||u.send(JSON.stringify({...i,id:i.id??L()}));}));}),(n,i)=>{let a=o=>{n.send(JSON.stringify(o));},c=L(),u={headers:i.headers,cookies:typeof i.headers.cookie=="string"?q.default.parse(i.headers.cookie):{}};e[c]=n,console.log("Client connected:",c),n.on("message",async o=>{try{console.log("Message received from the client:",o);let s=$.parse(JSON.parse(o.toString()));if(s.type==="SUBSCRIBE"){let{resource:p}=s;t[p]||(t[p]={}),t[p][c]={};}else if(s.type==="SYNC"){let{resources:p}=s,m=p??Object.keys(r.schema);console.log("Syncing resources:",m),await Promise.all(m.map(async b=>{let y=await r.handleRequest({req:{...u,type:"QUERY",resourceName:b,context:{}}});if(!y||!y.data)throw new Error("Invalid resource");a({id:s.id,type:"SYNC",resource:b,data:Object.fromEntries(Object.entries(y.data??{}).map(([f,H])=>[f,H.value]))});}));}else if(s.type==="MUTATE"){let{resource:p}=s;console.log("Received mutation from client:",s);try{let m=await r.handleRequest({req:{...u,type:"MUTATE",resourceName:p,input:s.payload,context:{messageId:s.id},resourceId:s.resourceId,procedure:s.procedure}});s.procedure&&a({id:s.id,type:"REPLY",data:m});}catch(m){a({id:s.id,type:"REJECT",resource:p,message:m.message}),console.error("Error parsing mutation from the client:",m);}}}catch(s){console.error("Error handling message from the client:",s);}}),n.on("close",()=>{console.log("Connection closed",c),delete e[c];});}};var N=class r{router;storage;schema;middlewares=new Set;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 r(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}async handleRequest(e){if(!this.router.routes[e.req.resourceName])throw new Error("Invalid resource");let t=await Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),async n=>this.router.routes[e.req.resourceName].handleRequest({req:n,db:this.storage,schema:this.schema}))(e.req);return t&&e.req.type==="MUTATE"&&t.acceptedValues&&Object.keys(t.acceptedValues).length>0&&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}},nt=N.create;exports.InMemoryStorage=j;exports.Route=v;exports.Router=w;exports.SQLStorage=C;exports.Server=N;exports.Storage=R;exports.routeFactory=je;exports.router=Oe;exports.server=nt;exports.webSocketAdapter=tt;