@live-state/sync 0.0.4-beta.8 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-NJ7LXJAY.js +1 -0
- package/dist/{chunk-WZ7JXHZL.js → chunk-RCXJM33Z.js} +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +1 -1
- package/dist/fetch-client.js +1 -1
- package/dist/index-BtsKDfTE.d.cts +282 -0
- package/dist/index-BtsKDfTE.d.ts +282 -0
- package/dist/{index-BgowrRDR.d.ts → index-D8jFoiy6.d.ts} +14 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -244
- package/dist/index.d.ts +1 -244
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +4 -5
- package/dist/server.d.ts +4 -5
- package/dist/server.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-XNKBHWSC.js +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,244 +1 @@
|
|
|
1
|
-
|
|
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 NullableLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | null, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
|
|
38
|
-
readonly inner: T;
|
|
39
|
-
constructor(inner: T);
|
|
40
|
-
encodeMutation(mutationType: MutationType, input: T["_value"] | null, timestamp: string): T["_decodeInput"];
|
|
41
|
-
mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>> | undefined): [
|
|
42
|
-
MaterializedLiveType<LiveType<T["_value"] | null, T["_meta"], T["_value"] | Partial<T["_value"] | null>, T["_decodeInput"]>>,
|
|
43
|
-
T["_decodeInput"] | null
|
|
44
|
-
];
|
|
45
|
-
getStorageFieldType(): StorageFieldType;
|
|
46
|
-
}
|
|
47
|
-
type LiveAtomicTypeMeta = {
|
|
48
|
-
timestamp: string | null;
|
|
49
|
-
} & LiveTypeMeta;
|
|
50
|
-
declare class LiveAtomicType<Value, DefaultValue = undefined> 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: DefaultValue;
|
|
59
|
-
readonly foreignReference?: string;
|
|
60
|
-
readonly isPrimary: boolean;
|
|
61
|
-
constructor(storageType: string, convertFunc?: (value: any) => Value, index?: boolean, unique?: boolean, defaultValue?: DefaultValue, 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, undefined>;
|
|
84
|
-
index(): LiveAtomicType<Value, undefined>;
|
|
85
|
-
default(value: Value): LiveAtomicType<Value, Value>;
|
|
86
|
-
primary(): LiveAtomicType<Value, undefined>;
|
|
87
|
-
nullable(): NullableLiveType<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, undefined>;
|
|
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
|
-
declare class LiveBoolean extends LiveAtomicType<boolean> {
|
|
104
|
-
private constructor();
|
|
105
|
-
static create(): LiveBoolean;
|
|
106
|
-
}
|
|
107
|
-
declare const boolean: typeof LiveBoolean.create;
|
|
108
|
-
declare class LiveTimestamp extends LiveAtomicType<Date> {
|
|
109
|
-
private constructor();
|
|
110
|
-
static create(): LiveTimestamp;
|
|
111
|
-
}
|
|
112
|
-
declare const timestamp: typeof LiveTimestamp.create;
|
|
113
|
-
|
|
114
|
-
/** biome-ignore-all lint/complexity/noBannedTypes: false positive */
|
|
115
|
-
|
|
116
|
-
type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
117
|
-
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
118
|
-
};
|
|
119
|
-
type InferLiveObject<T extends LiveObjectAny, Include extends IncludeClause<T> | undefined = undefined> = InferLiveObjectWithoutRelations<T> & (Include extends IncludeClause<T> ? {
|
|
120
|
-
[K in keyof T["relations"] as Include[K] extends true ? K : never]: T["relations"][K]["type"] extends "one" ? T["fields"][Exclude<T["relations"][K]["relationalColumn"], undefined>] extends NullableLiveType<any> ? InferLiveObject<T["relations"][K]["entity"]> | null : InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
121
|
-
} : {});
|
|
122
|
-
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
123
|
-
[K in keyof T as T[K]["type"] extends "many" ? never : T[K]["relationalColumn"]]: T[K]["required"] extends true ? InferIndex<T[K]["entity"]> : InferIndex<T[K]["entity"]> | null;
|
|
124
|
-
};
|
|
125
|
-
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
126
|
-
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = Partial<InferLiveObjectWithRelationalIds<TSchema>>;
|
|
127
|
-
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>>> {
|
|
128
|
-
readonly name: TName;
|
|
129
|
-
readonly fields: TSchema;
|
|
130
|
-
readonly relations: TRelations;
|
|
131
|
-
constructor(name: TName, fields: TSchema, relations?: TRelations);
|
|
132
|
-
encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
|
|
133
|
-
mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
|
|
134
|
-
setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
|
|
135
|
-
getStorageFieldType(): StorageFieldType;
|
|
136
|
-
static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
|
|
137
|
-
}
|
|
138
|
-
declare const object: typeof LiveObject.create;
|
|
139
|
-
type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
|
|
140
|
-
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>, {
|
|
141
|
-
timestamp: string | null;
|
|
142
|
-
} & LiveTypeMeta> {
|
|
143
|
-
readonly entity: TEntity;
|
|
144
|
-
readonly type: TType;
|
|
145
|
-
readonly required: TRequired;
|
|
146
|
-
readonly relationalColumn?: TRelationalColumn;
|
|
147
|
-
readonly foreignColumn?: TForeignColumn;
|
|
148
|
-
readonly sourceEntity: TSourceEntity;
|
|
149
|
-
private constructor();
|
|
150
|
-
encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
|
|
151
|
-
value: string;
|
|
152
|
-
_meta: {
|
|
153
|
-
timestamp: string;
|
|
154
|
-
};
|
|
155
|
-
};
|
|
156
|
-
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
157
|
-
value: string;
|
|
158
|
-
_meta: {
|
|
159
|
-
timestamp: string;
|
|
160
|
-
};
|
|
161
|
-
}, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
|
|
162
|
-
MaterializedLiveType<LiveString>,
|
|
163
|
-
{
|
|
164
|
-
value: string;
|
|
165
|
-
_meta: {
|
|
166
|
-
timestamp: string;
|
|
167
|
-
};
|
|
168
|
-
} | null
|
|
169
|
-
];
|
|
170
|
-
getStorageFieldType(): StorageFieldType;
|
|
171
|
-
toJSON(): {
|
|
172
|
-
entityName: string;
|
|
173
|
-
type: TType;
|
|
174
|
-
required: TRequired;
|
|
175
|
-
relationalColumn: TRelationalColumn | undefined;
|
|
176
|
-
foreignColumn: TForeignColumn | undefined;
|
|
177
|
-
};
|
|
178
|
-
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>;
|
|
179
|
-
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>;
|
|
180
|
-
}
|
|
181
|
-
type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
|
|
182
|
-
declare const createRelations: <TSourceObject extends LiveObjectAny, TRelations extends Record<string, RelationAny>>(liveObject: TSourceObject, factory: (connectors: {
|
|
183
|
-
one: ReturnType<typeof Relation.createOneFactory<TSourceObject>>;
|
|
184
|
-
many: ReturnType<typeof Relation.createManyFactory<TSourceObject>>;
|
|
185
|
-
}) => TRelations) => RelationsDecl<TSourceObject["name"], TRelations>;
|
|
186
|
-
type MaterializedLiveType<T extends LiveTypeAny> = {
|
|
187
|
-
value: T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
188
|
-
[K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
|
|
189
|
-
} : T["_value"];
|
|
190
|
-
_meta: T["_meta"];
|
|
191
|
-
};
|
|
192
|
-
declare const inferValue: <T extends LiveTypeAny>(type?: MaterializedLiveType<T>) => InferLiveType<T> | undefined;
|
|
193
|
-
type ExtractObjectValues<T> = T[keyof T];
|
|
194
|
-
type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
|
|
195
|
-
$type: "relations";
|
|
196
|
-
objectName: TObjectName;
|
|
197
|
-
relations: TRelations;
|
|
198
|
-
};
|
|
199
|
-
type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
200
|
-
[K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
|
|
201
|
-
[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"]>;
|
|
202
|
-
} : never : never;
|
|
203
|
-
}>;
|
|
204
|
-
type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
205
|
-
[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;
|
|
206
|
-
}>;
|
|
207
|
-
type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
|
|
208
|
-
type Schema<TRawSchema extends RawSchema> = {
|
|
209
|
-
[K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
|
|
210
|
-
};
|
|
211
|
-
declare const createSchema: <TRawSchema extends RawSchema>(schema: TRawSchema) => Schema<TRawSchema>;
|
|
212
|
-
type WhereClause<T extends LiveObjectAny> = ({
|
|
213
|
-
[K in keyof T["fields"]]?: InferLiveType<T["fields"][K]> | ({
|
|
214
|
-
$eq?: InferLiveType<T["fields"][K]>;
|
|
215
|
-
$in?: InferLiveType<T["fields"][K]>[];
|
|
216
|
-
$not?: InferLiveType<T["fields"][K]> | {
|
|
217
|
-
$in?: InferLiveType<T["fields"][K]>[];
|
|
218
|
-
$eq?: InferLiveType<T["fields"][K]>;
|
|
219
|
-
};
|
|
220
|
-
} & (Exclude<InferLiveType<T["fields"][K]>, null | undefined> extends number | Date ? {
|
|
221
|
-
$gt?: InferLiveType<T["fields"][K]>;
|
|
222
|
-
$gte?: InferLiveType<T["fields"][K]>;
|
|
223
|
-
$lt?: InferLiveType<T["fields"][K]>;
|
|
224
|
-
$lte?: InferLiveType<T["fields"][K]>;
|
|
225
|
-
} : {}));
|
|
226
|
-
} & {
|
|
227
|
-
[K in keyof T["relations"]]?: WhereClause<T["relations"][K]["entity"]>;
|
|
228
|
-
}) | {
|
|
229
|
-
$and?: WhereClause<T>[];
|
|
230
|
-
$or?: WhereClause<T>[];
|
|
231
|
-
};
|
|
232
|
-
type IncludeClause<T extends LiveObjectAny> = {
|
|
233
|
-
[K in keyof T["relations"]]?: boolean | IncludeClause<T["relations"][K]["entity"]>;
|
|
234
|
-
};
|
|
235
|
-
type GetFieldType<T> = T extends NullableLiveType<any> ? T["inner"] : T;
|
|
236
|
-
type HasDefaultValue<T> = T extends LiveAtomicType<any, undefined> ? false : true;
|
|
237
|
-
type InferInsert<T extends LiveObjectAny> = {
|
|
238
|
-
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends true ? never : K]: InferLiveType<T["fields"][K]>;
|
|
239
|
-
} & {
|
|
240
|
-
[K in keyof T["fields"] as HasDefaultValue<GetFieldType<T["fields"][K]>> extends false ? never : K]?: InferLiveType<T["fields"][K]>;
|
|
241
|
-
};
|
|
242
|
-
type InferUpdate<T extends LiveObjectAny> = Omit<LiveObjectMutationInput<T>, "id">;
|
|
243
|
-
|
|
244
|
-
export { type IncludeClause, type InferIndex, type InferInsert, type InferLiveObject, type InferLiveObjectWithRelationalIds, type InferLiveObjectWithoutRelations, type InferLiveType, type InferUpdate, LiveAtomicType, LiveBoolean, LiveNumber, LiveObject, type LiveObjectAny, type LiveObjectMutationInput, LiveString, LiveTimestamp, LiveType, type LiveTypeAny, type LiveTypeMeta, type MaterializedLiveType, type MutationType, NullableLiveType, Relation, type Schema, type StorageFieldType, type WhereClause, boolean, createRelations, createSchema, id, inferValue, number, object, reference, string, timestamp };
|
|
1
|
+
export { b as IncludeClause, F as InferIndex, d as InferInsert, c as InferLiveObject, I as InferLiveObjectWithRelationalIds, h as InferLiveObjectWithoutRelations, E as InferLiveType, e as InferUpdate, n as LiveAtomicType, v as LiveBoolean, p as LiveNumber, j as LiveObject, L as LiveObjectAny, i as LiveObjectMutationInput, r as LiveString, x as LiveTimestamp, C as LiveType, D as LiveTypeAny, z as LiveTypeMeta, g as LogLevel, M as MaterializedLiveType, A as MutationType, N as NullableLiveType, R as Relation, a as Schema, B as StorageFieldType, W as WhereClause, w as boolean, k as createRelations, m as createSchema, t as id, l as inferValue, q as number, o as object, u as reference, s as string, y as timestamp } from './index-BtsKDfTE.js';
|
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,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,x 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-NJ7LXJAY.js';
|
package/dist/server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var P=require('crypto'),Ye=require('qs'),zod=require('zod');require('js-xxhash');var kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var P__default=/*#__PURE__*/_interopDefault(P);var Ye__default=/*#__PURE__*/_interopDefault(Ye);var Ie=Object.create;var ie=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var Ae=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var Ee=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var $e=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Oe(e))!je.call(r,i)&&i!==t&&ie(r,i,{get:()=>e[i],enumerable:!(n=Le(e,i))||n.enumerable});return r};var ae=(r,e,t)=>(t=r!=null?Ie(Ae(r)):{},$e(ie(t,"default",{value:r,enumerable:true}),r));var U=Ee(V=>{Object.defineProperty(V,"__esModule",{value:true});V.parse=Be;V.serialize=Qe;var Fe=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Ke=/^[\u0021-\u003A\u003C-\u007E]*$/,De=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Ue=/^[\u0020-\u003A\u003D-\u007E]*$/,We=Object.prototype.toString,ke=(()=>{let r=function(){};return r.prototype=Object.create(null),r})();function Be(r,e){let t=new ke,n=r.length;if(n<2)return t;let i=(e==null?void 0:e.decode)||Ge,a=0;do{let o=r.indexOf("=",a);if(o===-1)break;let c=r.indexOf(";",a),s=c===-1?n:c;if(o>s){a=r.lastIndexOf(";",o-1)+1;continue}let m=le(r,a,o),y=de(r,o,m),d=r.slice(m,y);if(t[d]===void 0){let l=le(r,o+1,s),p=de(r,s,l),u=i(r.slice(l,p));t[d]=u;}a=s+1;}while(a<n);return t}function le(r,e,t){do{let n=r.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<t);return t}function de(r,e,t){for(;e>t;){let n=r.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return t}function Qe(r,e,t){let n=(t==null?void 0:t.encode)||encodeURIComponent;if(!Fe.test(r))throw new TypeError(`argument name is invalid: ${r}`);let i=n(e);if(!Ke.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(!De.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Ue.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!Ze(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 Ge(r){if(r.indexOf("%")===-1)return r;try{return decodeURIComponent(r)}catch{return r}}function Ze(r){return We.call(r)==="[object Date]"}});var se="0123456789ABCDEFGHJKMNPQRSTVWXYZ",O=32;var Ce=16,ce=10,oe=0xffffffffffff;var w;(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";})(w||(w={}));var v=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function Pe(r){let e=Math.floor(r()*O);return e===O&&(e=O-1),se.charAt(e)}function Ne(r){var n;let e=ze(),t=e&&(e.crypto||e.msCrypto)||(typeof P__default.default<"u"?P__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return t.getRandomValues(i),i[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((n=P__default.default)!=null&&n.randomBytes)return ()=>P__default.default.randomBytes(1).readUInt8()/255;throw new v(w.PRNGDetectFailure,"Failed to find a reliable PRNG")}function ze(){return qe()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function Ve(r,e){let t="";for(;r>0;r--)t=Pe(e)+t;return t}function _e(r,e=ce){if(isNaN(r))throw new v(w.EncodeTimeValueMalformed,`Time must be a number: ${r}`);if(r>oe)throw new v(w.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${oe}: ${r}`);if(r<0)throw new v(w.EncodeTimeNegative,`Time must be positive: ${r}`);if(Number.isInteger(r)===false)throw new v(w.EncodeTimeValueMalformed,`Time must be an integer: ${r}`);let t,n="";for(let i=e;i>0;i--)t=r%O,n=se.charAt(t)+n,r=(r-t)/O;return n}function qe(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function ue(r,e){let t=Ne(),n=Date.now();return _e(n,ce)+Ve(Ce,t)}var D=()=>ue().toLowerCase();var N=(...r)=>{let e=r.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var z=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:n,...i}){return new Promise((a,o)=>{let c=this.getBatchKey({resource:e,commonWhere:t,...i}),s={resource:e,commonWhere:t,uniqueWhere:n,...i,resolve:a,reject:o};this.queue.has(c)||this.queue.set(c,[]);let m=this.queue.get(c);m&&m.push(s),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:n,...i}=e;return `${t}:${JSON.stringify(n??{})}:${JSON.stringify(i??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(n){t.forEach(i=>{i.reject(n);});}}async executeBatchedRequests(e){var l,p;if(e.length===0)return;let t=e[0],{resource:n,commonWhere:i,include:a,sort:o}=t,c=e.length===1?t.limit:void 0,s=e.map(u=>u.uniqueWhere).filter(u=>u!==void 0),m=i,y=(l=Object.entries(s[0]??{})[0])==null?void 0:l[0];if(s.length>0){let u=s.map(f=>f[y]).filter(f=>f!=null);u.length>0&&(m=N(i,{[y]:{$in:u}}));}let d=await this.storage.rawFind({resource:n,where:m,include:a,sort:o,limit:c});for(let u of e){let f={};if(u.uniqueWhere){let[h,R]=Object.entries(u.uniqueWhere)[0];for(let[M,C]of Object.entries(d))((p=C.value[h])==null?void 0:p.value)===R&&(f[M]=C);}else Object.assign(f,d);u.resolve(f);}}};var me=ae(U());var _=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),W=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),He=W.superRefine((r,e)=>{r.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),ye=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),A=ye.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),j=ye.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:He});zod.z.union([j,A]);var pe=_.omit({resource:true}),k=A.omit({id:true,type:true,resource:true,procedure:true}),B=j.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([B,k]);var fe=r=>async e=>{var t;try{let n=typeof e.headers.getSetCookie=="function"?Object.fromEntries(e.headers):e.headers,i={headers:n,cookies:n.cookie?me.default.parse(n.cookie):{}},a=new URL(e.url),o=a.pathname.split("/"),c=a.searchParams,s=Ye__default.default.parse(c.toString()),m=await((t=r.contextProvider)==null?void 0:t.call(r,{transport:"HTTP",headers:i.headers,cookies:i.cookies,queryParams:s}))??{};if(e.method==="GET"){let y=o[o.length-1],{success:d,data:l,error:p}=pe.safeParse(s);if(!d)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:p},{status:400});let u=await r.handleQuery({req:{...i,...l,type:"QUERY",resource:y,context:m,queryParams:s}});return !u||!u.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(u.data)}if(e.method==="POST")try{let y=o[o.length-1],d=o[o.length-2],l=e.body?await e.json():{},p;if(y==="insert"||y==="update"){let{success:f,data:h,error:R}=B.safeParse(l);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=h;}else {let{success:f,data:h,error:R}=k.safeParse(l);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:R},{status:400});p=h;}let u=await r.handleMutation({req:{...i,type:"MUTATE",resource:d,input:p.payload,context:m,resourceId:p.resourceId,procedure:y==="insert"||y==="update"?y.toUpperCase():y,queryParams:{}}});return Response.json(u)}catch(y){return console.error("Error parsing mutation from the client:",y),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 ge=ae(U());var I=zod.z.string(),Xe=zod.z.object({id:I,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),et=_.extend({id:I,type:zod.z.literal("QUERY")}),Te=j.extend({id:I}),tt=A.extend({id:I}),nt=zod.z.union([tt,Te]),he=zod.z.union([Xe,et,nt]),rt=zod.z.object({id:I,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),it=zod.z.object({id:I,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([rt,it,Te]);zod.z.object({resource:zod.z.string(),data:zod.z.record(zod.z.string(),W)});var Re=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,o])=>{var c;(c=e[a])==null||c.send(JSON.stringify({...i,id:i.id??D()}));}));}),(n,i)=>{var y;let a=d=>{n.send(JSON.stringify(d));},o=D(),c={headers:i.headers,cookies:typeof i.headers.cookie=="string"?ge.default.parse(i.headers.cookie):{}},s=Ye.parse(i.url.split("?")[1]),m=(y=r.contextProvider)==null?void 0:y.call(r,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,queryParams:s});e[o]=n,console.log("Client connected:",o),n.on("message",async d=>{try{console.log("Message received from the client:",d);let l=he.parse(JSON.parse(d.toString()));if(l.type==="SUBSCRIBE"){let{resource:p}=l;t[p]||(t[p]={}),t[p][o]={};}else if(l.type==="QUERY"){let{resource:p}=l,u=await r.handleQuery({req:{...c,type:"QUERY",resource:p,context:await m??{},queryParams:s}});if(!u||!u.data)throw new Error("Invalid resource");a({id:l.id,type:"REPLY",data:{resource:p,data:Object.fromEntries(Object.entries(u.data??{}).map(([f,h])=>[f,h.value]))}});}else if(l.type==="MUTATE"){let{resource:p}=l;console.log("Received mutation from client:",l);try{let u=await r.handleMutation({req:{...c,type:"MUTATE",resource:p,input:l.payload,context:{messageId:l.id,...await m??{}},resourceId:l.resourceId,procedure:l.procedure,queryParams:s}});l.procedure&&l.procedure!=="INSERT"&&l.procedure!=="UPDATE"&&a({id:l.id,type:"REPLY",data:u});}catch(u){a({id:l.id,type:"REJECT",resource:p,message:u.message}),console.error("Error parsing mutation from the client:",u);}}}catch(l){console.error("Error handling message from the client:",l);}}),n.on("close",()=>{console.log("Connection closed",o),delete e[o];for(let d of Object.values(t))delete d[o];});}};function xe(r){let e=`${r.protocol}://${r.hostname}${r.url}`,t=new Headers;return Object.entries(r.headers).forEach(([n,i])=>{i&&t.set(n,Array.isArray(i)?i.join(","):i);}),new Request(e,{method:r.method,headers:t,body:r.body&&r.method!=="GET"?JSON.stringify(r.body):void 0})}var Kt=(r,e,t)=>{r.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Re(e)),r.use(`${(t==null?void 0:t.basePath)??""}/`,(n,i)=>{fe(e)(xe(n)).then(o=>o.json().then(c=>i.status(o.status).send(c)));});};var x=r=>{if(r)return Array.isArray(r.value)?r.value.map(e=>x(e)):typeof r.value!="object"||r.value===null||r.value instanceof Date?r.value:Object.fromEntries(Object.entries(r.value).map(([e,t])=>[e,x(t)]))};var b=(r,e,t=false)=>Object.entries(e).every(([n,i])=>{if(n==="$and")return i.every(o=>b(r,o,t));if(n==="$or")return i.some(o=>b(r,o,t));let a=(i==null?void 0:i.$eq)!==void 0?i==null?void 0:i.$eq:i;if(typeof i=="object"&&i!==null&&(i==null?void 0:i.$eq)===void 0){if(i.$in!==void 0){let o=r[n];return o===void 0?false:t?!i.$in.includes(o):i.$in.includes(o)}if(i.$not!==void 0&&!t)return b(r,{[n]:i.$not},true);if(i.$gt!==void 0){let o=r[n];return typeof o!="number"?false:t?o<=i.$gt:o>i.$gt}if(i.$gte!==void 0){let o=r[n];return typeof o!="number"?false:t?o<i.$gte:o>=i.$gte}if(i.$lt!==void 0){let o=r[n];return typeof o!="number"?false:t?o>=i.$lt:o<i.$lt}if(i.$lte!==void 0){let o=r[n];return typeof o!="number"?false:t?o>i.$lte:o<=i.$lte}return !r[n]||typeof r[n]!="object"?false:b(r[n],i,t)}return t?r[n]!==a:r[n]===a});var Y=class r{routes;constructor(e){this.routes=e.routes;}static create(e){return new r(e)}},dn=r=>Y.create({...r}),st=r=>({handler:e=>({inputValidator:r??zod.z.undefined(),handler:e})}),X=class r{resourceSchema;middlewares;customMutations;authorization;constructor(e,t,n){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=n;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new r(this.resourceSchema,e({mutation:st}))}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async n=>{var a,o;let i=(o=(a=this.authorization)==null?void 0:a.read)==null?void 0:o.call(a,{ctx:n.context});if(typeof i=="boolean"&&!i)throw new Error("Not authorized");return {data:await t.rawFind({resource:n.resource,commonWhere:N(n.where,typeof i=="object"?i:void 0),uniqueWhere:n.relationalWhere,include:n.include,limit:n.limit,sort:n.sort})}})(e);handleMutation=async({req:e,db:t})=>await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let i=this.customMutations[n.procedure];if(i){let a=i.inputValidator.parse(n.input);return n.input=a,i.handler({req:n,db:t})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:t,operation:n.procedure});throw new Error(`Unknown procedure: ${n.procedure}`)}})(e);handleSet=async({req:e,db:t,operation:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let i=await t.rawFindById(e.resource,e.resourceId);if(n==="INSERT"&&i)throw new Error("Resource already exists");if(n==="UPDATE"&&!i)throw new Error("Resource not found");return t.transaction(async({trx:a})=>{var m,y,d,l,p;let[o,c]=this.resourceSchema.mergeMutation("set",e.input,i);if(!c)throw new Error("Mutation rejected");if(n==="INSERT"){let u=await a.rawInsert(e.resource,e.resourceId,o);if((m=this.authorization)!=null&&m.insert){let f=x(u);f.id=f.id??e.resourceId;let h=this.authorization.insert({ctx:e.context,value:f});if(!(typeof h=="boolean"?h:b(f,h)))throw new Error("Not authorized")}return {data:u,acceptedValues:c}}if((d=(y=this.authorization)==null?void 0:y.update)!=null&&d.preMutation){let u=x(i);u.id=u.id??e.resourceId;let f=this.authorization.update.preMutation({ctx:e.context,value:u});if(!(typeof f=="boolean"?f:b(u,f)))throw new Error("Not authorized")}let s=await a.rawUpdate(e.resource,e.resourceId,o);if((p=(l=this.authorization)==null?void 0:l.update)!=null&&p.postMutation){let u=x(s);u.id=u.id??e.resourceId;let f=this.authorization.update.postMutation({ctx:e.context,value:u});if(!(typeof f=="boolean"?f:b(u,f)))throw new Error("Not authorized")}return {data:s,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),e)(t)}},ee=class r{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new X(e,void 0,t).use(...this.middlewares)}use(...e){return new r([...this.middlewares,...e])}static create(){return new r}},yn=ee.create;var $=class{async insert(e,t){let n=new Date().toISOString();return x(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([i,a])=>[i,{value:a,_meta:{timestamp:n}}]))}))}async update(e,t,n){let i=new Date().toISOString(),{id:a,...o}=n;return x(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(o).map(([c,s])=>[c,{value:s,_meta:{timestamp:i}}]))}))}};function q(r,e,t,n){if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error("Resource not found");let a=n.$or,o=n.$and;return (a?t.or:t.and)(a?n.$or.map(c=>q(r,e,t,c)):o?n.$and.map(c=>q(r,e,t,c)):Object.entries(n).map(([c,s])=>{var m,y;if(i.fields[c])return (s==null?void 0:s.$eq)!==void 0?t(`${e}.${c}`,s.$eq===null?"is":"=",s.$eq):(s==null?void 0:s.$in)!==void 0?t(`${e}.${c}`,"in",s.$in):(s==null?void 0:s.$not)!==void 0?((m=s==null?void 0:s.$not)==null?void 0:m.$in)!==void 0?t(`${e}.${c}`,"not in",s.$not.$in):((y=s==null?void 0:s.$not)==null?void 0:y.$eq)!==void 0?t(`${e}.${c}`,s.$not.$eq===null?"is not":"!=",s.$not.$eq):t(`${e}.${c}`,s.$not===null?"is not":"!=",s.$not):(s==null?void 0:s.$gt)!==void 0?t(`${e}.${c}`,">",s.$gt):(s==null?void 0:s.$gte)!==void 0?t(`${e}.${c}`,">=",s.$gte):(s==null?void 0:s.$lt)!==void 0?t(`${e}.${c}`,"<",s.$lt):(s==null?void 0:s.$lte)!==void 0?t(`${e}.${c}`,"<=",s.$lte):t(`${e}.${c}`,s===null?"is":"=",s);if(i.relations[c]){let d=i.relations[c],l=d.entity.name;return d.type==="many"?t.exists(te(r,l,t.selectFrom(l).select("id").whereRef(d.foreignColumn,"=",`${e}.id`),s)):q(r,l,t,s)}return null}).filter(Boolean))}function F(r,e,t,n){let i=r[e];if(!i)throw new Error("Resource not found");if(!n)return t;if(n.$and){for(let a of n.$and)t=F(r,e,t,a);return t}else if(n.$or){for(let a of n.$or)t=F(r,e,t,a);return t}for(let[a,o]of Object.entries(n)){if(!i.relations[a])continue;let c=i.relations[a],s=c.entity.name,m=c.type==="one"?"id":c.foreignColumn,y=c.type==="one"?c.relationalColumn:"id";t=t.leftJoin(s,`${s}.${m}`,`${e}.${y}`),o instanceof Object&&!Array.isArray(o)&&o!==null&&(t=F(r,s,t,o));}return t}function te(r,e,t,n){return !n||Object.keys(n).length===0?t:(t=F(r,e,t,n),t.where(i=>q(r,e,i,n)))}function K(r,e,t,n){if(!n)return t;if(!r)throw new Error("Schema not initialized");let i=r[e];if(!i)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(n)){if(!i.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let o=i.relations[a],c=o.entity.name,s=n[a],m=o.type==="one"?"id":o.foreignColumn,y=o.type==="one"?o.relationalColumn:"id",d=o.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom,l=typeof s=="object"&&s!==null;t=t.select(p=>{let u=p.selectFrom(c).selectAll(c).whereRef(`${c}.${m}`,"=",`${e}.${y}`).select(f=>postgres.jsonObjectFrom(f.selectFrom(`${c}_meta`).selectAll(`${c}_meta`).whereRef(`${c}_meta.id`,"=",`${c}.id`)).as("_meta"));return l&&(u=K(r,c,u,s)),d(u).as(a)});}return t}var ne=class r extends ${db;schema;constructor(e,t){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async updateSchema(e){this.schema=e;let t=await this.db.introspection.getTables();for(let[n,i]of Object.entries(e)){let a=t.find(s=>s.name===n);a||await this.db.schema.createTable(n).ifNotExists().execute();let o=`${n}_meta`,c=t.find(s=>s.name===o);c||await this.db.schema.createTable(o).ifNotExists().execute();for(let[s,m]of Object.entries(i.fields)){let y=a==null?void 0:a.columns.find(p=>p.name===s),d=m.getStorageFieldType();y?y.dataType!==d.type&&console.error("Column type mismatch:",s,"expected to have type:",d.type,"but has type:",y.dataType):(await this.db.schema.alterTable(n).addColumn(s,d.type,p=>{let u=p;return d.unique&&(u=u.unique()),d.nullable||(u=u.notNull()),d.references&&(u=u.references(d.references)),d.primary&&(u=u.primaryKey()),d.default!==void 0&&(u=u.defaultTo(d.default)),u}).execute().catch(p=>{throw console.error("Error adding column",s,p),p}),d.index&&await this.db.schema.createIndex(`${n}_${s}_index`).on(n).column(s).execute().catch(()=>{})),(c==null?void 0:c.columns.find(p=>p.name===s))||await this.db.schema.alterTable(o).addColumn(s,"varchar",p=>{let u=p;return d.primary&&(u=u.primaryKey().references(`${n}.${s}`)),u}).execute();}}}async rawFindById(e,t,n){if(!this.schema)throw new Error("Schema not initialized");let i=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(o=>postgres.jsonObjectFrom(o.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));i=K(this.schema,e,i,n);let a=await i.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,n){let i=await this.rawFindById(e.name,t,n==null?void 0:n.include);if(i)return x(i)}async rawFind(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:n,include:i,limit:a,sort:o}=e,c=this.db.selectFrom(t).selectAll(t).select(d=>postgres.jsonObjectFrom(d.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));c=te(this.schema,t,c,n),c=K(this.schema,t,c,i),a!==void 0&&(c=c.limit(a)),o!==void 0&&o.forEach(d=>{c=c.orderBy(d.key,d.direction);});let s=await c.execute(),m=Object.fromEntries(s.map(d=>{let{id:l}=d;return [l,d]}));return Object.keys(m).length===0?{}:Object.entries(m).reduce((d,[l,p])=>(d[l]=this.convertToMaterializedLiveType(p),d),{})}async find(e,t){let n=await this.rawFind({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort});return Object.fromEntries(Object.entries(n).map(([i,a])=>[i,x(a)]))}async rawInsert(e,t,n){var o;let i={},a={};for(let[c,s]of Object.entries(n.value)){let m=(o=s._meta)==null?void 0:o.timestamp;m&&(i[c]=s.value,a[c]=m);}return await this.db.insertInto(e).values({...i,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),n}async rawUpdate(e,t,n){var o;let i={},a={};for(let[c,s]of Object.entries(n.value)){let m=(o=s._meta)==null?void 0:o.timestamp;m&&(i[c]=s.value,a[c]=m);}return await Promise.all([this.db.updateTable(e).set(i).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(c=>c.column("id").doUpdateSet(a)).execute()]),n}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let n=Math.random().toString(36).substring(2,15),i=await this.db.savepoint(n).execute();try{return await e({trx:this,commit:()=>i.releaseSavepoint(n).execute().then(()=>{}),rollback:()=>i.rollbackToSavepoint(n).execute().then(()=>{})}).then(a=>i.isCommitted||i.isRolledBack?a:i.releaseSavepoint(n).execute().then(()=>a))}catch(a){throw await i.rollbackToSavepoint(n).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new r(t,this.schema),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(n=>t.isCommitted||t.isRolledBack?n:t.commit().execute().then(()=>n))}catch(n){throw await t.rollback().execute(),n}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[n,i])=>{var a,o,c;return n==="_meta"||(n==="id"?t[n]={value:i}:Array.isArray(i)?t[n]={value:i.map(s=>this.convertToMaterializedLiveType(s)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[n]}}:typeof i=="object"&&i!==null&&!(i instanceof Date)?t[n]={...this.convertToMaterializedLiveType(i),_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[n]}}:t[n]={value:i,_meta:{timestamp:(c=e==null?void 0:e._meta)==null?void 0:c[n]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,n=typeof t.selectFrom=="function",i=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",o=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return n&&i||a&&o}};var re=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);}}handleQuery(e){let t=new z(this.storage);return this.wrapInMiddlewares(async n=>{var m;let i=Se(n,this.schema,{stepId:"query",collectionName:n.resource,included:Object.keys(n.include??{})}),a={headers:n.headers,cookies:n.cookies,queryParams:n.queryParams,context:n.context},o={};for(let y=0;y<i.length;y++){let d=i[y],l=this.router.routes[d.resource];if(!l)throw new Error("Invalid resource");let p=d.getWhere&&d.referenceGetter?d.referenceGetter(o).map(d.getWhere):[void 0],u=(m=o[d.prevStepId??""])==null?void 0:m.flatMap(R=>{var M;return Object.keys(((M=R==null?void 0:R.result)==null?void 0:M.data)??{})}),h=(await Promise.allSettled(p.map(async(R,M)=>{let C=u==null?void 0:u[M],Me=await l.handleQuery({req:{type:"QUERY",...d,...a,where:d.where,relationalWhere:R},batcher:t});return {includedBy:C,result:Me}}))).flatMap(R=>R.status==="fulfilled"?[R.value]:[]);o[d.stepId]=h;}let c=Object.fromEntries(Object.entries(o).flatMap(([y,d],l)=>d.flatMap(p=>Object.entries(p.result.data).map(([u,f])=>[`${y}.${u}`,{data:f,includedBy:y!=="query"&&p.includedBy?`${y.split(".").slice(0,-1).join(".")}.${p.includedBy}`:void 0,path:y.split(".").slice(-1)[0],isMany:i[l].isMany,collectionName:i[l].collectionName,included:i[l].included}]))));return Object.keys(c).reduceRight((y,d)=>{var u,f;let l=c[d],p=l.path;if(p==="query"&&(y.data[d]=l.data),l.included.length)for(let h of l.included)l.data.value[h]??=((f=(u=this.schema[l.collectionName])==null?void 0:u.relations[h])==null?void 0:f.type)==="many"?{value:[]}:{value:null};if(l.includedBy){let h=c[l.includedBy];if(!h)return y;l.isMany?(h.data.value[p]??={value:[]},h.data.value[p].value.push(l.data)):h.data.value[p]=l.data;}return y},{data:{}})})(e.req)}async handleMutation(e){let t=await this.wrapInMiddlewares(async n=>{let i=this.router.routes[n.resource];if(!i)throw new Error("Invalid resource");return i.handleMutation({req:n,db:this.storage})})(e.req);if(t&&e.req.type==="MUTATE"&&t.acceptedValues&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&e.req.resourceId){let i=t.acceptedValues??{},a=e.req,o=a.resourceId;Object.keys(i).length&&o&&this.mutationSubscriptions.forEach(c=>{c({id:e.req.context.messageId,type:"MUTATE",resource:a.resource,payload:i,resourceId:o,procedure:a.procedure});});}return t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((n,i)=>a=>i({req:a,next:n}),e)(t)}},On=re.create;function Se(r,e,t){let{include:n,...i}=r,{stepId:a}=t,o=[{...i,...t}];if(n&&typeof n=="object"&&Object.keys(n).length>0){let c=e[i.resource];if(!c)throw new Error(`Resource ${i.resource} not found`);o.push(...Object.entries(n).flatMap(([s,m])=>{let y=c.relations[s];if(!y)throw new Error(`Relation ${s} not found for resource ${i.resource}`);let d=y.entity.name;return Se({...i,resource:d,include:m},e,{getWhere:y.type==="one"?l=>({id:l}):l=>({[y.foreignColumn]:l}),referenceGetter:l=>l[a].flatMap(p=>p.result.data?y.type==="one"?Object.values(p.result.data).map(u=>{var f,h;return (h=(f=u.value)==null?void 0:f[y.relationalColumn])==null?void 0:h.value}):Object.keys(p.result.data):[]),stepId:`${a}.${s}`,prevStepId:a,isMany:y.type==="many",collectionName:d,included:typeof m=="object"?Object.keys(m):[]})}));}return o}
|
|
2
|
-
exports.Route=
|
|
1
|
+
'use strict';require('js-xxhash');var V=require('crypto'),rt=require('qs'),zod=require('zod'),kysely=require('kysely'),postgres=require('kysely/helpers/postgres');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var V__default=/*#__PURE__*/_interopDefault(V);var rt__default=/*#__PURE__*/_interopDefault(rt);var je=Object.create;var ce=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var Ne=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ze=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $e(e))!Pe.call(i,n)&&n!==t&&ce(i,n,{get:()=>e[n],enumerable:!(r=Ee(e,n))||r.enumerable});return i};var ue=(i,e,t)=>(t=i!=null?je(Ce(i)):{},ze(ce(t,"default",{value:i,enumerable:true}),i));var Q=Ne(K=>{Object.defineProperty(K,"__esModule",{value:true});K.parse=He;K.serialize=Je;var Ue=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,ke=/^[\u0021-\u003A\u003C-\u007E]*$/,Be=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Qe=/^[\u0020-\u003A\u003D-\u007E]*$/,Ge=Object.prototype.toString,Ze=(()=>{let i=function(){};return i.prototype=Object.create(null),i})();function He(i,e){let t=new Ze,r=i.length;if(r<2)return t;let n=(e==null?void 0:e.decode)||Ye,a=0;do{let s=i.indexOf("=",a);if(s===-1)break;let o=i.indexOf(";",a),c=o===-1?r:o;if(s>c){a=i.lastIndexOf(";",s-1)+1;continue}let m=fe(i,a,s),y=he(i,s,m),l=i.slice(m,y);if(t[l]===void 0){let p=fe(i,s+1,c),u=he(i,c,p),h=n(i.slice(p,u));t[l]=h;}a=c+1;}while(a<r);return t}function fe(i,e,t){do{let r=i.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}function he(i,e,t){for(;e>t;){let r=i.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}function Je(i,e,t){let r=(t==null?void 0:t.encode)||encodeURIComponent;if(!Ue.test(i))throw new TypeError(`argument name is invalid: ${i}`);let n=r(e);if(!ke.test(n))throw new TypeError(`argument val is invalid: ${e}`);let a=i+"="+n;if(!t)return a;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);a+="; Max-Age="+t.maxAge;}if(t.domain){if(!Be.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);a+="; Domain="+t.domain;}if(t.path){if(!Qe.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);a+="; Path="+t.path;}if(t.expires){if(!Xe(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 Ye(i){if(i.indexOf("%")===-1)return i;try{return decodeURIComponent(i)}catch{return i}}function Xe(i){return Ge.call(i)==="[object Date]"}});var E=(i,e,t)=>{let r={},n=t[e];if(!n)return r;let a=s=>{s.$and?s.$and.forEach(a):s.$or?s.$or.forEach(a):Object.entries(s).forEach(([o,c])=>{var m;if((m=n.relations)!=null&&m[o]&&(r[o]=true,typeof c=="object"&&c!==null&&!Array.isArray(c))){let y=E(c,n.relations[o].entity.name,t);Object.keys(y).length>0&&(r[o]=y);}});};return a(i),r},w=(i,e,t=false)=>Object.entries(e).every(([r,n])=>{if(r==="$and")return n.every(s=>w(i,s,t));if(r==="$or")return n.some(s=>w(i,s,t));let a=(n==null?void 0:n.$eq)!==void 0?n==null?void 0:n.$eq:n;if(typeof n=="object"&&n!==null&&(n==null?void 0:n.$eq)===void 0){if(n.$in!==void 0){let o=i[r];return o===void 0?false:t?!n.$in.includes(o):n.$in.includes(o)}if(n.$not!==void 0&&!t)return w(i,{[r]:n.$not},true);if(n.$gt!==void 0){let o=i[r];return typeof o!="number"?false:t?o<=n.$gt:o>n.$gt}if(n.$gte!==void 0){let o=i[r];return typeof o!="number"?false:t?o<n.$gte:o>=n.$gte}if(n.$lt!==void 0){let o=i[r];return typeof o!="number"?false:t?o>=n.$lt:o<n.$lt}if(n.$lte!==void 0){let o=i[r];return typeof o!="number"?false:t?o>n.$lte:o<=n.$lte}let s=i[r];return !s||typeof s!="object"&&!Array.isArray(s)?false:Array.isArray(s)?t?!s.some(o=>w(o,n,false)):s.some(o=>w(o,n,false)):w(s,n,t)}return t?i[r]!==a:i[r]===a}),S={CRITICAL:0,ERROR:1,WARN:2,INFO:3,DEBUG:4},k=class{level;prefix;constructor(e={}){this.level=e.level??S.INFO,this.prefix=e.prefix?`[${e.prefix}] `:"";}critical(...e){this.level>=S.CRITICAL&&console.error(`${this.prefix}[CRITICAL]`,...e);}error(...e){this.level>=S.ERROR&&console.error(`${this.prefix}[ERROR]`,...e);}warn(...e){this.level>=S.WARN&&console.warn(`${this.prefix}[WARN]`,...e);}info(...e){this.level>=S.INFO&&console.log(`${this.prefix}[INFO]`,...e);}debug(...e){this.level>=S.DEBUG&&console.log(`${this.prefix}[DEBUG]`,...e);}setLevel(e){this.level=e;}getLevel(){return this.level}},le=i=>new k(i);var ye="0123456789ABCDEFGHJKMNPQRSTVWXYZ",$=32;var Ve=16,pe=10,de=0xffffffffffff;var L;(function(i){i.Base32IncorrectEncoding="B32_ENC_INVALID",i.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",i.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",i.EncodeTimeNegative="ENC_TIME_NEG",i.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",i.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",i.PRNGDetectFailure="PRNG_DETECT",i.ULIDInvalid="ULID_INVALID",i.Unexpected="UNEXPECTED",i.UUIDInvalid="UUID_INVALID";})(L||(L={}));var M=class extends Error{constructor(e,t){super(`${t} (${e})`),this.name="ULIDError",this.code=e;}};function _e(i){let e=Math.floor(i()*$);return e===$&&(e=$-1),ye.charAt(e)}function Fe(i){var r;let e=Ke(),t=e&&(e.crypto||e.msCrypto)||(typeof V__default.default<"u"?V__default.default:null);if(typeof(t==null?void 0:t.getRandomValues)=="function")return ()=>{let n=new Uint8Array(1);return t.getRandomValues(n),n[0]/255};if(typeof(t==null?void 0:t.randomBytes)=="function")return ()=>t.randomBytes(1).readUInt8()/255;if((r=V__default.default)!=null&&r.randomBytes)return ()=>V__default.default.randomBytes(1).readUInt8()/255;throw new M(L.PRNGDetectFailure,"Failed to find a reliable PRNG")}function Ke(){return De()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function We(i,e){let t="";for(;i>0;i--)t=_e(e)+t;return t}function qe(i,e=pe){if(isNaN(i))throw new M(L.EncodeTimeValueMalformed,`Time must be a number: ${i}`);if(i>de)throw new M(L.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${de}: ${i}`);if(i<0)throw new M(L.EncodeTimeNegative,`Time must be positive: ${i}`);if(Number.isInteger(i)===false)throw new M(L.EncodeTimeValueMalformed,`Time must be an integer: ${i}`);let t,r="";for(let n=e;n>0;n--)t=i%$,r=ye.charAt(t)+r,i=(i-t)/$;return r}function De(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function me(i,e){let t=Fe(),r=Date.now();return qe(r,pe)+We(Ve,t)}var B=()=>me().toLowerCase();var _=(...i)=>{let e=i.filter(t=>!!t);return e.length===0?{}:e.length===1?e[0]:{$and:e}};var F=class{storage;queue=new Map;scheduled=false;constructor(e){this.storage=e;}async rawFind({resource:e,commonWhere:t,uniqueWhere:r,...n}){return new Promise((a,s)=>{let o=this.getBatchKey({resource:e,commonWhere:t,...n}),c={resource:e,commonWhere:t,uniqueWhere:r,...n,resolve:a,reject:s};this.queue.has(o)||this.queue.set(o,[]);let m=this.queue.get(o);m&&m.push(c),this.scheduled||(this.scheduled=true,setImmediate(()=>{this.processBatch();}));})}getBatchKey(e){let{resource:t,commonWhere:r,...n}=e;return `${t}:${JSON.stringify(r??{})}:${JSON.stringify(n??{})}`}async processBatch(){this.scheduled=false;let e=Array.from(this.queue.entries());this.queue.clear();for(let[,t]of e)try{await this.executeBatchedRequests(t);}catch(r){t.forEach(n=>{n.reject(r);});}}async executeBatchedRequests(e){var p,u;if(e.length===0)return;let t=e[0],{resource:r,commonWhere:n,include:a,sort:s}=t,o=e.length===1?t.limit:void 0,c=e.map(h=>h.uniqueWhere).filter(h=>h!==void 0),m=n,y=(p=Object.entries(c[0]??{})[0])==null?void 0:p[0];if(c.length>0){let h=c.map(d=>d[y]).filter(d=>d!=null);h.length>0&&(m=_(n,{[y]:{$in:h}}));}let l=await this.storage.rawFind({resource:r,where:m,include:a,sort:s,limit:o});for(let h of e){let d={};if(h.uniqueWhere){let[f,g]=Object.entries(h.uniqueWhere)[0];for(let[x,v]of Object.entries(l))((u=v.value[f])==null?void 0:u.value)===g&&(d[x]=v);}else Object.assign(d,l);h.resolve(d);}}};var Re=ue(Q());var W=zod.z.object({resource:zod.z.string(),where:zod.z.record(zod.z.string(),zod.z.any()).optional(),include:zod.z.record(zod.z.string(),zod.z.any()).optional(),lastSyncedAt:zod.z.string().optional(),limit:zod.z.coerce.number().optional(),sort:zod.z.array(zod.z.object({key:zod.z.string(),direction:zod.z.enum(["asc","desc"])})).optional()}),G=zod.z.record(zod.z.string(),zod.z.object({value:zod.z.string().or(zod.z.number()).or(zod.z.boolean()).or(zod.z.date()).nullable(),_meta:zod.z.object({timestamp:zod.z.string().optional().nullable()}).optional()})),et=G.superRefine((i,e)=>{i.id&&e.addIssue({code:zod.z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),Te=zod.z.object({id:zod.z.string().optional(),type:zod.z.literal("MUTATE"),resource:zod.z.string(),resourceId:zod.z.string().optional()}),C=Te.extend({procedure:zod.z.string(),payload:zod.z.any().optional()}),P=Te.extend({procedure:zod.z.enum(["INSERT","UPDATE"]),payload:et});zod.z.union([P,C]);var ge=W.omit({resource:true}),Z=C.omit({id:true,type:true,resource:true,procedure:true}),H=P.omit({id:true,type:true,resource:true,procedure:true});zod.z.union([H,Z]);var xe=i=>{let e=i.logger;return async t=>{var r;try{let n=typeof t.headers.getSetCookie=="function"?Object.fromEntries(t.headers):t.headers,a={headers:n,cookies:n.cookie?Re.default.parse(n.cookie):{}},s=new URL(t.url),o=s.pathname.split("/"),c=s.searchParams,m=rt__default.default.parse(c.toString()),y=await((r=i.contextProvider)==null?void 0:r.call(i,{transport:"HTTP",headers:a.headers,cookies:a.cookies,queryParams:m}))??{};if(t.method==="GET"){let l=o[o.length-1],{success:p,data:u,error:h}=ge.safeParse(m);if(!p)return Response.json({message:"Invalid query",code:"INVALID_QUERY",details:h},{status:400});let d=await i.handleQuery({req:{...a,...u,type:"QUERY",resource:l,context:y,queryParams:m}});return !d||!d.data?Response.json({message:"Invalid resource",code:"INVALID_RESOURCE"},{status:400}):Response.json(d.data)}if(t.method==="POST")try{let l=o[o.length-1],p=o[o.length-2],u=t.body?await t.json():{},h;if(l==="insert"||l==="update"){let{success:f,data:g,error:x}=H.safeParse(u);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:x},{status:400});h=g;}else {let{success:f,data:g,error:x}=Z.safeParse(u);if(!f)return Response.json({message:"Invalid mutation",code:"INVALID_REQUEST",details:x},{status:400});h=g;}let d=await i.handleMutation({req:{...a,type:"MUTATE",resource:p,input:h.payload,context:y,resourceId:h.resourceId,procedure:l==="insert"||l==="update"?l.toUpperCase():l,queryParams:{}}});return Response.json(d)}catch(l){return e.error("Error parsing mutation from the client:",l),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 e.error("Unexpected error:",n),Response.json({message:"Internal server error",code:"INTERNAL_SERVER_ERROR"},{status:500})}}};var we=ue(Q());var A=zod.z.string(),nt=zod.z.object({id:A,type:zod.z.literal("SUBSCRIBE"),resource:zod.z.string()}),it=W.extend({id:A,type:zod.z.literal("QUERY")}),be=P.extend({id:A}),at=C.extend({id:A}),ot=zod.z.union([at,be]),ve=zod.z.union([nt,it,ot]),st=zod.z.object({id:A,type:zod.z.literal("REJECT"),resource:zod.z.string(),message:zod.z.string().optional()}),ct=zod.z.object({id:A,type:zod.z.literal("REPLY"),data:zod.z.any()});zod.z.union([st,ct,be]);zod.z.object({resource:zod.z.string(),data:zod.z.record(zod.z.string(),G)});var Se=i=>{let e={},t={},r=i.logger;return i.subscribeToMutations(n=>{let a=n;!a.resourceId||!a.payload||(r.debug("Mutation propagated:",a),Object.entries(t[a.resource]??{}).forEach(([s,o])=>{var c;(c=e[s])==null||c.send(JSON.stringify({...a,id:a.id??B()}));}));}),(n,a)=>{var l;let s=p=>{n.send(JSON.stringify(p));},o=B(),c={headers:a.headers,cookies:typeof a.headers.cookie=="string"?we.default.parse(a.headers.cookie):{}},m=rt.parse(a.url.split("?")[1]),y=(l=i.contextProvider)==null?void 0:l.call(i,{transport:"WEBSOCKET",headers:c.headers,cookies:c.cookies,queryParams:m});e[o]=n,r.info("Client connected:",o),n.on("message",async p=>{try{r.debug("Message received from the client:",p);let u=ve.parse(JSON.parse(p.toString()));if(u.type==="SUBSCRIBE"){let{resource:h}=u;t[h]||(t[h]={}),t[h][o]={};}else if(u.type==="QUERY"){let{resource:h}=u,d=await i.handleQuery({req:{...c,type:"QUERY",resource:h,context:await y??{},queryParams:m}});if(!d||!d.data)throw new Error("Invalid resource");s({id:u.id,type:"REPLY",data:{resource:h,data:Object.fromEntries(Object.entries(d.data??{}).map(([f,g])=>[f,g.value]))}});}else if(u.type==="MUTATE"){let{resource:h}=u;r.debug("Received mutation from client:",u);try{let d=await i.handleMutation({req:{...c,type:"MUTATE",resource:h,input:u.payload,context:{messageId:u.id,...await y??{}},resourceId:u.resourceId,procedure:u.procedure,queryParams:m}});u.procedure&&u.procedure!=="INSERT"&&u.procedure!=="UPDATE"&&s({id:u.id,type:"REPLY",data:d});}catch(d){s({id:u.id,type:"REJECT",resource:h,message:d.message}),r.error("Error parsing mutation from the client:",d);}}}catch(u){r.error("Error handling message from the client:",u);}}),n.on("close",()=>{r.info("Connection closed",o),delete e[o];for(let p of Object.values(t))delete p[o];});}};function Ie(i){let e=`${i.protocol}://${i.hostname}${i.url}`,t=new Headers;return Object.entries(i.headers).forEach(([r,n])=>{n&&t.set(r,Array.isArray(n)?n.join(","):n);}),new Request(e,{method:i.method,headers:t,body:i.body&&i.method!=="GET"?JSON.stringify(i.body):void 0})}var Zt=(i,e,t)=>{i.ws(`${(t==null?void 0:t.basePath)??""}/ws`,Se(e)),i.use(`${(t==null?void 0:t.basePath)??""}/`,(r,n)=>{xe(e)(Ie(r)).then(s=>s.json().then(o=>n.status(s.status).send(o)));});};var b=i=>i?Array.isArray(i.value)?i.value.map(t=>b(t)):typeof i.value!="object"||i.value===null||i.value instanceof Date?i.value:Object.fromEntries(Object.entries(i.value).map(([t,r])=>Array.isArray(r)?[t,r.map(n=>b(n))]:[t,b(r)])):void 0;var re=class i{routes;constructor(e){this.routes=e.routes;}static create(e){return new i(e)}},fr=i=>re.create({...i}),dt=i=>({handler:e=>({inputValidator:i??zod.z.undefined(),handler:e})}),ne=class i{resourceSchema;middlewares;customMutations;authorization;constructor(e,t,r){this.resourceSchema=e,this.middlewares=new Set,this.customMutations=t??{},this.authorization=r;}use(...e){for(let t of e)this.middlewares.add(t);return this}withMutations(e){return new i(this.resourceSchema,e({mutation:dt}),this.authorization)}handleQuery=async({req:e,batcher:t})=>await this.wrapInMiddlewares(async r=>{var a,s;let n=(s=(a=this.authorization)==null?void 0:a.read)==null?void 0:s.call(a,{ctx:r.context});if(typeof n=="boolean"&&!n)throw new Error("Not authorized");return {data:await t.rawFind({resource:r.resource,commonWhere:_(r.where,typeof n=="object"?n:void 0),uniqueWhere:r.relationalWhere,include:r.include,limit:r.limit,sort:r.sort})}})(e);handleMutation=async({req:e,db:t,schema:r})=>await this.wrapInMiddlewares(async n=>{if(!n.procedure)throw new Error("Procedure is required for mutations");let a=this.customMutations[n.procedure];if(a){let s=a.inputValidator.parse(n.input);return n.input=s,a.handler({req:n,db:t})}else {if(n.procedure==="INSERT"||n.procedure==="UPDATE")return this.handleSet({req:n,db:t,operation:n.procedure,schema:r});throw new Error(`Unknown procedure: ${n.procedure}`)}})(e);handleSet=async({req:e,db:t,operation:r,schema:n})=>{if(!e.input)throw new Error("Payload is required");if(!e.resourceId)throw new Error("ResourceId is required");let a=await t.rawFindById(e.resource,e.resourceId);if(r==="INSERT"&&a)throw new Error("Resource already exists");if(r==="UPDATE"&&!a)throw new Error("Resource not found");return t.transaction(async({trx:s})=>{var y,l,p,u,h;let[o,c]=this.resourceSchema.mergeMutation("set",e.input,a);if(!c)throw new Error("Mutation rejected");if(r==="INSERT"){let d=await s.rawInsert(e.resource,e.resourceId,o),f=b(d);if(f.id=f.id??e.resourceId,(y=this.authorization)!=null&&y.insert){let g=this.authorization.insert({ctx:e.context,value:f});if(typeof g=="boolean"){if(!g)throw new Error("Not authorized")}else {let x=E(g,e.resource,n),v=Object.keys(x).length>0?await s.rawFindById(e.resource,e.resourceId,x):d,I=b(v);if(I.id=I.id??e.resourceId,!w(I,g))throw new Error("Not authorized")}}return {data:d,acceptedValues:c}}if((p=(l=this.authorization)==null?void 0:l.update)!=null&&p.preMutation){let d=b(a);d.id=d.id??e.resourceId;let f=this.authorization.update.preMutation({ctx:e.context,value:d});if(typeof f=="boolean"){if(!f)throw new Error("Not authorized")}else {let g=E(f,e.resource,n),x=Object.keys(g).length>0?await s.rawFindById(e.resource,e.resourceId,g):a,v=b(x);if(v.id=v.id??e.resourceId,!w(v,f))throw new Error("Not authorized")}}let m=await s.rawUpdate(e.resource,e.resourceId,o);if((h=(u=this.authorization)==null?void 0:u.update)!=null&&h.postMutation){let d=b(m);d.id=d.id??e.resourceId;let f=this.authorization.update.postMutation({ctx:e.context,value:d});if(typeof f=="boolean"){if(!f)throw new Error("Not authorized")}else {let g=E(f,e.resource,n),x=Object.keys(g).length>0?await s.rawFindById(e.resource,e.resourceId,g):m,v=b(x);if(v.id=v.id??e.resourceId,!w(v,f))throw new Error("Not authorized")}}return {data:m,acceptedValues:c}})};wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),e)(t)}},ie=class i{middlewares;constructor(e=[]){this.middlewares=e;}collectionRoute(e,t){return new ne(e,void 0,t).use(...this.middlewares)}use(...e){return new i([...this.middlewares,...e])}static create(){return new i}},hr=ie.create;var z=class{async insert(e,t){let r=new Date().toISOString();return b(await this.rawInsert(e.name,t.id,{value:Object.fromEntries(Object.entries(t).map(([n,a])=>[n,{value:a,_meta:{timestamp:r}}]))}))}async update(e,t,r){let n=new Date().toISOString(),{id:a,...s}=r;return b(await this.rawUpdate(e.name,t,{value:Object.fromEntries(Object.entries(s).map(([o,c])=>[o,{value:c,_meta:{timestamp:n}}]))}))}};function q(i,e,t,r){if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error("Resource not found");let a=r.$or,s=r.$and;return (a?t.or:t.and)(a?r.$or.map(o=>q(i,e,t,o)):s?r.$and.map(o=>q(i,e,t,o)):Object.entries(r).map(([o,c])=>{var m,y;if(n.fields[o])return (c==null?void 0:c.$eq)!==void 0?t(`${e}.${o}`,c.$eq===null?"is":"=",c.$eq):(c==null?void 0:c.$in)!==void 0?t(`${e}.${o}`,"in",c.$in):(c==null?void 0:c.$not)!==void 0?((m=c==null?void 0:c.$not)==null?void 0:m.$in)!==void 0?t(`${e}.${o}`,"not in",c.$not.$in):((y=c==null?void 0:c.$not)==null?void 0:y.$eq)!==void 0?t(`${e}.${o}`,c.$not.$eq===null?"is not":"!=",c.$not.$eq):t(`${e}.${o}`,c.$not===null?"is not":"!=",c.$not):(c==null?void 0:c.$gt)!==void 0?t(`${e}.${o}`,">",c.$gt):(c==null?void 0:c.$gte)!==void 0?t(`${e}.${o}`,">=",c.$gte):(c==null?void 0:c.$lt)!==void 0?t(`${e}.${o}`,"<",c.$lt):(c==null?void 0:c.$lte)!==void 0?t(`${e}.${o}`,"<=",c.$lte):t(`${e}.${o}`,c===null?"is":"=",c);if(n.relations[o]){let l=n.relations[o],p=l.entity.name;return l.type==="many"?t.exists(ae(i,p,t.selectFrom(p).select("id").whereRef(l.foreignColumn,"=",`${e}.id`),c)):q(i,p,t,c)}return null}).filter(Boolean))}function D(i,e,t,r){let n=i[e];if(!n)throw new Error("Resource not found");if(!r)return t;if(r.$and){for(let a of r.$and)t=D(i,e,t,a);return t}else if(r.$or){for(let a of r.$or)t=D(i,e,t,a);return t}for(let[a,s]of Object.entries(r)){if(!n.relations[a])continue;let o=n.relations[a],c=o.entity.name,m=o.type==="one"?"id":o.foreignColumn,y=o.type==="one"?o.relationalColumn:"id";t=t.leftJoin(c,`${c}.${m}`,`${e}.${y}`),s instanceof Object&&!Array.isArray(s)&&s!==null&&(t=D(i,c,t,s));}return t}function ae(i,e,t,r){return !r||Object.keys(r).length===0?t:(t=D(i,e,t,r),t.where(n=>q(i,e,n,r)))}function U(i,e,t,r){if(!r)return t;if(!i)throw new Error("Schema not initialized");let n=i[e];if(!n)throw new Error(`Resource not found: ${e}`);for(let a of Object.keys(r)){if(!n.relations[a])throw new Error(`Relation ${a} not found in resource ${e}`);let s=n.relations[a],o=s.entity.name,c=r[a],m=s.type==="one"?"id":s.foreignColumn,y=s.type==="one"?s.relationalColumn:"id",l=s.type==="one"?postgres.jsonObjectFrom:postgres.jsonArrayFrom,p=typeof c=="object"&&c!==null;t=t.select(u=>{let h=u.selectFrom(o).selectAll(o).whereRef(`${o}.${m}`,"=",`${e}.${y}`).select(d=>postgres.jsonObjectFrom(d.selectFrom(`${o}_meta`).selectAll(`${o}_meta`).whereRef(`${o}_meta.id`,"=",`${o}.id`)).as("_meta"));return p&&(h=U(i,o,h,c)),l(h).as(a)});}return t}var oe=class i extends z{db;schema;logger;constructor(e,t,r){super(),this.isKyselyLike(e)?this.db=e:this.db=new kysely.Kysely({dialect:new kysely.PostgresDialect({pool:e})}),this.schema=t,this.logger=r,this.rawInsert=this.rawInsert.bind(this),this.rawUpdate=this.rawUpdate.bind(this);}async init(e,t){var n;this.schema=e,this.logger=t;let r=await this.db.introspection.getTables();for(let[a,s]of Object.entries(e)){let o=r.find(y=>y.name===a);o||await this.db.schema.createTable(a).ifNotExists().execute();let c=`${a}_meta`,m=r.find(y=>y.name===c);m||await this.db.schema.createTable(c).ifNotExists().execute();for(let[y,l]of Object.entries(s.fields)){let p=o==null?void 0:o.columns.find(d=>d.name===y),u=l.getStorageFieldType();p?p.dataType!==u.type&&((n=this.logger)==null||n.warn("Column type mismatch:",y,"expected to have type:",u.type,"but has type:",p.dataType)):(await this.db.schema.alterTable(a).addColumn(y,u.type,d=>{let f=d;return u.unique&&(f=f.unique()),u.nullable||(f=f.notNull()),u.references&&(f=f.references(u.references)),u.primary&&(f=f.primaryKey()),u.default!==void 0&&(f=f.defaultTo(u.default)),f}).execute().catch(d=>{var f;throw (f=this.logger)==null||f.error("Error adding column",y,d),d}),u.index&&await this.db.schema.createIndex(`${a}_${y}_index`).on(a).column(y).execute().catch(()=>{})),(m==null?void 0:m.columns.find(d=>d.name===y))||await this.db.schema.alterTable(c).addColumn(y,"varchar",d=>{let f=d;return u.primary&&(f=f.primaryKey().references(`${a}.${y}`)),f}).execute();}}}async rawFindById(e,t,r){if(!this.schema)throw new Error("Schema not initialized");let n=await this.db.selectFrom(e).where("id","=",t).selectAll(e).select(s=>postgres.jsonObjectFrom(s.selectFrom(`${e}_meta`).selectAll(`${e}_meta`).whereRef(`${e}_meta.id`,"=",`${e}.id`)).as("_meta"));n=U(this.schema,e,n,r);let a=await n.executeTakeFirst();if(a)return this.convertToMaterializedLiveType(a)}async findOne(e,t,r){let n=await this.rawFindById(e.name,t,r==null?void 0:r.include);if(n)return b(n)}async rawFind(e){if(!this.schema)throw new Error("Schema not initialized");let{resource:t,where:r,include:n,limit:a,sort:s}=e,o=this.db.selectFrom(t).selectAll(t).select(l=>postgres.jsonObjectFrom(l.selectFrom(`${t}_meta`).selectAll(`${t}_meta`).whereRef(`${t}_meta.id`,"=",`${t}.id`)).as("_meta"));o=ae(this.schema,t,o,r),o=U(this.schema,t,o,n),a!==void 0&&(o=o.limit(a)),s!==void 0&&s.forEach(l=>{o=o.orderBy(l.key,l.direction);});let c=await o.execute(),m=Object.fromEntries(c.map(l=>{let{id:p}=l;return [p,l]}));return Object.keys(m).length===0?{}:Object.entries(m).reduce((l,[p,u])=>(l[p]=this.convertToMaterializedLiveType(u),l),{})}async find(e,t){let r=await this.rawFind({resource:e.name,where:t==null?void 0:t.where,include:t==null?void 0:t.include,limit:t==null?void 0:t.limit,sort:t==null?void 0:t.sort});return Object.fromEntries(Object.entries(r).map(([n,a])=>[n,b(a)]))}async rawInsert(e,t,r){var s;let n={},a={};for(let[o,c]of Object.entries(r.value)){let m=(s=c._meta)==null?void 0:s.timestamp;m&&(n[o]=c.value,a[o]=m);}return await this.db.insertInto(e).values({...n,id:t}).execute().then(()=>{this.db.insertInto(`${e}_meta`).values({...a,id:t}).execute();}),r}async rawUpdate(e,t,r){var s;let n={},a={};for(let[o,c]of Object.entries(r.value)){let m=(s=c._meta)==null?void 0:s.timestamp;m&&(n[o]=c.value,a[o]=m);}return await Promise.all([this.db.updateTable(e).set(n).where("id","=",t).execute(),this.db.insertInto(`${e}_meta`).values({...a,id:t}).onConflict(o=>o.column("id").doUpdateSet(a)).execute()]),r}async transaction(e){if(!this.schema)throw new Error("Schema not initialized");if(this.db.isTransaction){let r=Math.random().toString(36).substring(2,15),n=await this.db.savepoint(r).execute();try{return await e({trx:this,commit:()=>n.releaseSavepoint(r).execute().then(()=>{}),rollback:()=>n.rollbackToSavepoint(r).execute().then(()=>{})}).then(a=>n.isCommitted||n.isRolledBack?a:n.releaseSavepoint(r).execute().then(()=>a))}catch(a){throw await n.rollbackToSavepoint(r).execute().catch(()=>{}),a}}let t=await this.db.startTransaction().execute();try{return await e({trx:new i(t,this.schema,this.logger),commit:()=>t.commit().execute(),rollback:()=>t.rollback().execute()}).then(r=>t.isCommitted||t.isRolledBack?r:t.commit().execute().then(()=>r))}catch(r){throw await t.rollback().execute(),r}}convertToMaterializedLiveType(e){return {value:Object.entries(e).reduce((t,[r,n])=>{var a,s,o;return r==="_meta"||(r==="id"?t[r]={value:n}:Array.isArray(n)?t[r]={value:n.map(c=>this.convertToMaterializedLiveType(c)),_meta:{timestamp:(a=e==null?void 0:e._meta)==null?void 0:a[r]}}:typeof n=="object"&&n!==null&&!(n instanceof Date)?t[r]={...this.convertToMaterializedLiveType(n),_meta:{timestamp:(s=e==null?void 0:e._meta)==null?void 0:s[r]}}:t[r]={value:n,_meta:{timestamp:(o=e==null?void 0:e._meta)==null?void 0:o[r]}}),t},{})}}isKyselyLike(e){if(e instanceof kysely.Kysely)return true;if(!e||typeof e!="object")return false;let t=e,r=typeof t.selectFrom=="function",n=typeof t.startTransaction=="function",a=typeof t.savepoint=="function",s=typeof t.isTransaction=="boolean"||typeof t.isTransaction=="function";return r&&n||a&&s}};var se=class i{router;storage;schema;middlewares=new Set;logger;contextProvider;mutationSubscriptions=new Set;constructor(e){var t;this.router=e.router,this.storage=e.storage,this.schema=e.schema,this.logger=le({level:e.logLevel??S.INFO}),(t=e.middlewares)==null||t.forEach(r=>{this.middlewares.add(r);}),this.storage.init(this.schema,this.logger),this.contextProvider=e.contextProvider;}static create(e){return new i(e)}subscribeToMutations(e){return this.mutationSubscriptions.add(e),()=>{this.mutationSubscriptions.delete(e);}}handleQuery(e){let t=new F(this.storage);return this.wrapInMiddlewares(async r=>{var m;let n=Ae(r,this.schema,{stepId:"query",collectionName:r.resource,included:Object.keys(r.include??{})}),a={headers:r.headers,cookies:r.cookies,queryParams:r.queryParams,context:r.context},s={};for(let y=0;y<n.length;y++){let l=n[y],p=this.router.routes[l.resource];if(!p)throw new Error("Invalid resource");let u=l.getWhere&&l.referenceGetter?l.referenceGetter(s).map(l.getWhere):[void 0],h=(m=s[l.prevStepId??""])==null?void 0:m.flatMap(g=>{var x;return Object.keys(((x=g==null?void 0:g.result)==null?void 0:x.data)??{})}),f=(await Promise.allSettled(u.map(async(g,x)=>{let v=h==null?void 0:h[x],I=await p.handleQuery({req:{type:"QUERY",...l,...a,where:l.where,relationalWhere:g},batcher:t});return {includedBy:v,result:I}}))).flatMap(g=>g.status==="fulfilled"?[g.value]:[]);s[l.stepId]=f;}let o=Object.fromEntries(Object.entries(s).flatMap(([y,l],p)=>l.flatMap(u=>Object.entries(u.result.data).map(([h,d])=>[`${y}.${h}`,{data:d,includedBy:y!=="query"&&u.includedBy?`${y.split(".").slice(0,-1).join(".")}.${u.includedBy}`:void 0,path:y.split(".").slice(-1)[0],isMany:n[p].isMany,collectionName:n[p].collectionName,included:n[p].included}]))));return Object.keys(o).reduceRight((y,l)=>{var h,d;let p=o[l],u=p.path;if(u==="query"&&(y.data[l.replace("query.","")]=p.data),p.included.length)for(let f of p.included)p.data.value[f]??=((d=(h=this.schema[p.collectionName])==null?void 0:h.relations[f])==null?void 0:d.type)==="many"?{value:[]}:{value:null};if(p.includedBy){let f=o[p.includedBy];if(!f)return y;p.isMany?(f.data.value[u]??={value:[]},f.data.value[u].value.push(p.data)):f.data.value[u]=p.data;}return y},{data:{}})})(e.req)}async handleMutation(e){let t=await this.wrapInMiddlewares(async r=>{let n=this.router.routes[r.resource];if(!n)throw new Error("Invalid resource");return n.handleMutation({req:r,db:this.storage,schema:this.schema})})(e.req);if(t&&e.req.type==="MUTATE"&&t.acceptedValues&&(e.req.procedure==="INSERT"||e.req.procedure==="UPDATE")&&e.req.resourceId){let n=t.acceptedValues??{},a=e.req,s=a.resourceId;Object.keys(n).length&&s&&this.mutationSubscriptions.forEach(o=>{o({id:e.req.context.messageId,type:"MUTATE",resource:a.resource,payload:n,resourceId:s,procedure:a.procedure});});}return t}use(e){return this.middlewares.add(e),this}context(e){return this.contextProvider=e,this}wrapInMiddlewares(e){return t=>Array.from(this.middlewares.values()).reduceRight((r,n)=>a=>n({req:a,next:r}),e)(t)}},Cr=se.create;function Ae(i,e,t){let{include:r,where:n,...a}=i,{stepId:s}=t,o=[{...a,...t,where:n}];if(r&&typeof r=="object"&&Object.keys(r).length>0){let c=e[a.resource];if(!c)throw new Error(`Resource ${a.resource} not found`);o.push(...Object.entries(r).flatMap(([m,y])=>{let l=c.relations[m];if(!l)throw new Error(`Relation ${m} not found for resource ${a.resource}`);let p=l.entity.name;return Ae({...a,resource:p,include:y},e,{getWhere:l.type==="one"?u=>({id:u}):u=>({[l.foreignColumn]:u}),referenceGetter:u=>u[s].flatMap(h=>h.result.data?l.type==="one"?Object.values(h.result.data).map(d=>{var f,g;return (g=(f=d.value)==null?void 0:f[l.relationalColumn])==null?void 0:g.value}):Object.keys(h.result.data):[]),stepId:`${s}.${m}`,prevStepId:s,isMany:l.type==="many",collectionName:p,included:typeof y=="object"?Object.keys(y):[]})}));}return o}
|
|
2
|
+
exports.Route=ne;exports.RouteFactory=ie;exports.Router=re;exports.SQLStorage=oe;exports.Server=se;exports.Storage=z;exports.expressAdapter=Zt;exports.routeFactory=hr;exports.router=fr;exports.server=Cr;
|
package/dist/server.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { LiveObjectAny, WhereClause, InferLiveObjectWithRelationalIds, MaterializedLiveType, Schema, IncludeClause, InferLiveObject, InferInsert, InferUpdate } from './index.cjs';
|
|
2
|
+
import { L as LiveObjectAny, W as WhereClause, S as Simplify, I as InferLiveObjectWithRelationalIds, M as MaterializedLiveType, a as Schema, b as IncludeClause, c as InferLiveObject, d as InferInsert, e as InferUpdate, f as Logger, g as LogLevel } from './index-BtsKDfTE.cjs';
|
|
3
3
|
import * as z3 from 'zod/v3';
|
|
4
4
|
import * as z4 from 'zod/v4/core';
|
|
5
5
|
import { PostgresPool } from 'kysely';
|
|
@@ -42,10 +42,6 @@ type DefaultMutation = Omit<z.infer<typeof defaultMutationSchema>, "resourceId">
|
|
|
42
42
|
|
|
43
43
|
type Awaitable<T> = T | Promise<T>;
|
|
44
44
|
|
|
45
|
-
type Simplify<T> = T extends Record<string, unknown> ? {
|
|
46
|
-
[K in keyof T]: Simplify<T[K]>;
|
|
47
|
-
} : T extends Array<infer U> ? Array<Simplify<U>> : T;
|
|
48
|
-
|
|
49
45
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
50
46
|
/** biome-ignore-all lint/style/noNonNullAssertion: false positive */
|
|
51
47
|
|
|
@@ -142,6 +138,7 @@ declare abstract class Storage {
|
|
|
142
138
|
declare class SQLStorage extends Storage {
|
|
143
139
|
private db;
|
|
144
140
|
private schema?;
|
|
141
|
+
private logger?;
|
|
145
142
|
constructor(pool: PostgresPool);
|
|
146
143
|
findOne<T extends LiveObjectAny>(resource: T, id: string, options?: {
|
|
147
144
|
include?: IncludeClause<T>;
|
|
@@ -201,6 +198,7 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
201
198
|
readonly storage: Storage;
|
|
202
199
|
readonly schema: Schema<any>;
|
|
203
200
|
readonly middlewares: Set<Middleware<any>>;
|
|
201
|
+
readonly logger: Logger;
|
|
204
202
|
contextProvider?: ContextProvider;
|
|
205
203
|
private mutationSubscriptions;
|
|
206
204
|
private constructor();
|
|
@@ -210,6 +208,7 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
210
208
|
schema: Schema<any>;
|
|
211
209
|
middlewares?: Middleware<any>[];
|
|
212
210
|
contextProvider?: ContextProvider;
|
|
211
|
+
logLevel?: LogLevel;
|
|
213
212
|
}): Server<TRouter>;
|
|
214
213
|
subscribeToMutations(handler: MutationHandler): () => void;
|
|
215
214
|
handleQuery(opts: {
|
package/dist/server.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { LiveObjectAny, WhereClause, InferLiveObjectWithRelationalIds, MaterializedLiveType, Schema, IncludeClause, InferLiveObject, InferInsert, InferUpdate } from './index.js';
|
|
2
|
+
import { L as LiveObjectAny, W as WhereClause, S as Simplify, I as InferLiveObjectWithRelationalIds, M as MaterializedLiveType, a as Schema, b as IncludeClause, c as InferLiveObject, d as InferInsert, e as InferUpdate, f as Logger, g as LogLevel } from './index-BtsKDfTE.js';
|
|
3
3
|
import * as z3 from 'zod/v3';
|
|
4
4
|
import * as z4 from 'zod/v4/core';
|
|
5
5
|
import { PostgresPool } from 'kysely';
|
|
@@ -42,10 +42,6 @@ type DefaultMutation = Omit<z.infer<typeof defaultMutationSchema>, "resourceId">
|
|
|
42
42
|
|
|
43
43
|
type Awaitable<T> = T | Promise<T>;
|
|
44
44
|
|
|
45
|
-
type Simplify<T> = T extends Record<string, unknown> ? {
|
|
46
|
-
[K in keyof T]: Simplify<T[K]>;
|
|
47
|
-
} : T extends Array<infer U> ? Array<Simplify<U>> : T;
|
|
48
|
-
|
|
49
45
|
/** biome-ignore-all lint/suspicious/noExplicitAny: false positive */
|
|
50
46
|
/** biome-ignore-all lint/style/noNonNullAssertion: false positive */
|
|
51
47
|
|
|
@@ -142,6 +138,7 @@ declare abstract class Storage {
|
|
|
142
138
|
declare class SQLStorage extends Storage {
|
|
143
139
|
private db;
|
|
144
140
|
private schema?;
|
|
141
|
+
private logger?;
|
|
145
142
|
constructor(pool: PostgresPool);
|
|
146
143
|
findOne<T extends LiveObjectAny>(resource: T, id: string, options?: {
|
|
147
144
|
include?: IncludeClause<T>;
|
|
@@ -201,6 +198,7 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
201
198
|
readonly storage: Storage;
|
|
202
199
|
readonly schema: Schema<any>;
|
|
203
200
|
readonly middlewares: Set<Middleware<any>>;
|
|
201
|
+
readonly logger: Logger;
|
|
204
202
|
contextProvider?: ContextProvider;
|
|
205
203
|
private mutationSubscriptions;
|
|
206
204
|
private constructor();
|
|
@@ -210,6 +208,7 @@ declare class Server<TRouter extends AnyRouter> {
|
|
|
210
208
|
schema: Schema<any>;
|
|
211
209
|
middlewares?: Middleware<any>[];
|
|
212
210
|
contextProvider?: ContextProvider;
|
|
211
|
+
logLevel?: LogLevel;
|
|
213
212
|
}): Server<TRouter>;
|
|
214
213
|
subscribeToMutations(handler: MutationHandler): () => void;
|
|
215
214
|
handleQuery(opts: {
|