@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 438 lines 13.4 KB
Raw
1 import type { Contract } from "@prisma/orm-postgres/contract/types";
2 import type { SqlStorage } from "@prisma/orm-postgres/family-contract/types";
3 import type {
4 AggregateBuilder,
5 AggregateResult,
6 AggregateSpec,
7 Collection,
8 CollectionTypeState,
9 DefaultCollectionTypeState,
10 DefaultModelRow,
11 GroupedCollection,
12 RelatedModelName,
13 RelationNames,
14 RelationsOf,
15 } from "@prisma/orm-postgres/orm-client";
16 import type { PostgresClient } from "@prisma/orm-postgres/runtime";
17 import * as Effect from "effect/Effect";
18 import * as Stream from "effect/Stream";
19 import { type ClientError, wrapPrismaError } from "./Errors.ts";
20
21 type AnyContract = Contract<SqlStorage>;
22 type Simplify<T> = { [K in keyof T]: T[K] } & {};
23 type InitialState<Ns extends string> = Omit<DefaultCollectionTypeState, "nsId"> & {
24 readonly nsId: Ns;
25 };
26 type WithState<S extends CollectionTypeState, Patch> = Omit<S, keyof Patch> & Patch;
27 type Args<F> = F extends {
28 (...args: infer A): unknown;
29 (...args: infer B): unknown;
30 (...args: infer C): unknown;
31 (...args: infer D): unknown;
32 }
33 ? A | B | C | D
34 : never;
35 type Native<
36 C extends AnyContract,
37 M extends string,
38 Row,
39 S extends CollectionTypeState,
40 > = Collection<C, M, Row, S>;
41 type NativeRow<T> = T extends { readonly _row?: infer Row } ? Row : never;
42 type Root<
43 C extends AnyContract,
44 Ns extends string,
45 M extends string,
46 > = Ns extends keyof PostgresClient<C>["orm"]
47 ? M extends keyof PostgresClient<C>["orm"][Ns]
48 ? PostgresClient<C>["orm"][Ns][M]
49 : never
50 : never;
51
52 type RootRow<C extends AnyContract, Ns extends string, M extends string> = [
53 Root<C, Ns, M>,
54 ] extends [never]
55 ? DefaultModelRow<C, M, Ns>
56 : NativeRow<Root<C, Ns, M>>;
57
58 export type WhereFilter<C extends AnyContract, M extends string, Ns extends string> = Args<
59 Native<C, M, DefaultModelRow<C, M, Ns>, InitialState<Ns>>["where"]
60 >[0];
61
62 /** Buffer a query with `yield*`, or consume its rows incrementally through `stream`. */
63 export interface QueryResult<Row, E, R> extends Effect.Effect<Row[], E, R> {
64 readonly stream: Stream.Stream<Row, E, R>;
65 }
66
67 type Relation<
68 C extends AnyContract,
69 Ns extends string,
70 M extends string,
71 Rel extends string,
72 > = Rel extends keyof RelationsOf<C, M, Ns> ? RelationsOf<C, M, Ns>[Rel] : never;
73 type TargetNamespace<C extends AnyContract, Rel, Ns extends string> = Rel extends {
74 readonly to: { readonly namespace: infer Target extends string };
75 }
76 ? {
77 [K in keyof C["domain"]["namespaces"] & string]: Target extends K ? K : never;
78 }[keyof C["domain"]["namespaces"] & string]
79 : Ns;
80 type RelatedRow<
81 C extends AnyContract,
82 Ns extends string,
83 M extends string,
84 Rel extends string,
85 > = RootRow<
86 C,
87 TargetNamespace<C, Relation<C, Ns, M, Rel>, Ns>,
88 RelatedModelName<C, M, Rel, Ns> & string
89 >;
90 type IncludeOwner<
91 C extends AnyContract,
92 Ns extends string,
93 M extends string,
94 Rel extends string,
95 S extends CollectionTypeState,
96 > = Rel extends RelationNames<C, M, Ns> ? M : S["variantName"] & string;
97 type KeysOfUnion<T> = T extends unknown ? keyof T : never;
98 type Cardinality<Rel> = Rel extends { readonly cardinality: infer Card } ? Card : "1:N";
99 type RelationValue<Rel, Row, Refined extends boolean = false> =
100 Cardinality<Rel> extends "1:1" | "N:1"
101 ? Refined extends true
102 ? Row | null
103 : Rel extends { readonly nullable: false }
104 ? Row
105 : Row | null
106 : Row[];
107 type Terminal =
108 | "all"
109 | "first"
110 | "aggregate"
111 | "groupBy"
112 | "create"
113 | "createAll"
114 | "createAndCount"
115 | "upsert"
116 | "update"
117 | "updateAll"
118 | "updateAndCount"
119 | "delete"
120 | "deleteAll"
121 | "deleteAndCount";
122 type Refinement<
123 C extends AnyContract,
124 Ns extends string,
125 M extends string,
126 Rel extends string,
127 > = Omit<
128 Native<
129 C,
130 RelatedModelName<C, M, Rel, Ns> & string,
131 RelatedRow<C, Ns, M, Rel>,
132 InitialState<TargetNamespace<C, Relation<C, Ns, M, Rel>, Ns>>
133 >,
134 | Terminal
135 | (Cardinality<Relation<C, Ns, M, Rel>> extends "1:1" | "N:1"
136 ?
137 | "combine"
138 | (string extends keyof AggregateBuilder<C, M, Ns>
139 ? never
140 : keyof AggregateBuilder<C, M, Ns>)
141 : never)
142 >;
143 type RefinedValue<Rel, T> = T extends {
144 readonly kind: "includeScalar" | "includeCombine";
145 }
146 ? T[Extract<keyof T, symbol>]
147 : RelationValue<Rel, NativeRow<T>, true>;
148 type RefinementResult =
149 | { readonly _row?: unknown }
150 | { readonly kind: "includeScalar" | "includeCombine" };
151 type Model<
152 C extends AnyContract,
153 Ns extends string,
154 M extends string,
155 > = Ns extends keyof C["domain"]["namespaces"]
156 ? M extends keyof C["domain"]["namespaces"][Ns]["models"]
157 ? C["domain"]["namespaces"][Ns]["models"][M]
158 : never
159 : never;
160 type VariantRow<C extends AnyContract, Ns extends string, M extends string, V extends string> =
161 Model<C, Ns, M> extends {
162 readonly discriminator: { readonly field: infer Field extends string };
163 readonly variants: infer Variants;
164 }
165 ? V extends keyof Variants
166 ? Variants[V] extends { readonly value: infer Value }
167 ? Simplify<
168 Omit<DefaultModelRow<C, M, Ns>, Field> &
169 DefaultModelRow<C, V, Ns> & { [K in Field]: Value }
170 >
171 : never
172 : never
173 : never;
174
175 /** Prisma's fluent collection, with native parameter types and Effect terminals. */
176 export interface EffectCollection<
177 C extends AnyContract,
178 Ns extends string,
179 M extends string,
180 Row,
181 S extends CollectionTypeState = InitialState<Ns>,
182 E = never,
183 R = never,
184 > {
185 where(
186 ...args: Args<Native<C, M, Row, S>["where"]>
187 ): EffectCollection<C, Ns, M, Row, WithState<S, { readonly hasWhere: true }>, E, R>;
188 variant<V extends Parameters<Native<C, M, Row, S>["variant"]>[0]>(
189 name: V,
190 ): EffectCollection<
191 C,
192 Ns,
193 M,
194 VariantRow<C, Ns, M, V>,
195 WithState<S, { readonly hasWhere: true; readonly variantName: V }>,
196 E,
197 R
198 >;
199 include<Rel extends Parameters<Native<C, M, Row, S>["include"]>[0]>(
200 relation: Rel,
201 ): EffectCollection<
202 C,
203 Ns,
204 M,
205 Simplify<
206 Row & {
207 [K in Rel]: RelationValue<
208 Relation<C, Ns, IncludeOwner<C, Ns, M, K, S>, K>,
209 RelatedRow<C, Ns, IncludeOwner<C, Ns, M, K, S>, K>
210 >;
211 }
212 >,
213 S,
214 E,
215 R
216 >;
217 include<
218 Rel extends Parameters<Native<C, M, Row, S>["include"]>[0],
219 Refined extends (Cardinality<Relation<C, Ns, IncludeOwner<C, Ns, M, Rel, S>, Rel>> extends
220 | "1:1"
221 | "N:1"
222 ? { readonly _row?: unknown }
223 : RefinementResult),
224 >(
225 relation: Rel,
226 refine: (collection: Refinement<C, Ns, IncludeOwner<C, Ns, M, Rel, S>, Rel>) => Refined,
227 ): EffectCollection<
228 C,
229 Ns,
230 M,
231 Simplify<
232 Row & {
233 [K in Rel]: RefinedValue<Relation<C, Ns, IncludeOwner<C, Ns, M, K, S>, K>, Refined>;
234 }
235 >,
236 S,
237 E,
238 R
239 >;
240 select<
241 const Fields extends readonly [
242 keyof DefaultModelRow<C, M, Ns> & string,
243 ...(keyof DefaultModelRow<C, M, Ns> & string)[],
244 ],
245 >(
246 ...fields: Fields
247 ): EffectCollection<
248 C,
249 Ns,
250 M,
251 Simplify<
252 Pick<DefaultModelRow<C, M, Ns>, Fields[number]> & Omit<Row, KeysOfUnion<RootRow<C, Ns, M>>>
253 >,
254 S,
255 E,
256 R
257 >;
258 orderBy(
259 ...args: Parameters<Native<C, M, Row, S>["orderBy"]>
260 ): EffectCollection<C, Ns, M, Row, WithState<S, { readonly hasOrderBy: true }>, E, R>;
261 cursor(
262 ...args: Parameters<Native<C, M, Row, S>["cursor"]>
263 ): EffectCollection<C, Ns, M, Row, S, E, R>;
264 distinct(
265 ...fields: Parameters<Native<C, M, Row, S>["distinct"]>
266 ): EffectCollection<C, Ns, M, Row, S, E, R>;
267 distinctOn(
268 ...fields: Parameters<Native<C, M, Row, S>["distinctOn"]>
269 ): EffectCollection<C, Ns, M, Row, S, E, R>;
270 limit(n: number): EffectCollection<C, Ns, M, Row, S, E, R>;
271 offset(n: number): EffectCollection<C, Ns, M, Row, S, E, R>;
272 groupBy<
273 const Fields extends readonly [
274 keyof DefaultModelRow<C, M, Ns> & string,
275 ...(keyof DefaultModelRow<C, M, Ns> & string)[],
276 ],
277 >(
278 ...fields: Fields
279 ): EffectGroupedCollection<C, Ns, M, Fields, false, E, R>;
280 all(...args: Parameters<Native<C, M, Row, S>["all"]>): QueryResult<Row, ClientError | E, R>;
281 first(
282 ...args: Args<Native<C, M, Row, S>["first"]>
283 ): Effect.Effect<Row | null, ClientError | E, R>;
284 aggregate<Spec extends AggregateSpec>(
285 fn: (aggregate: AggregateBuilder<C, M, Ns>) => Spec,
286 ...configure: Parameters<Native<C, M, Row, S>["aggregate"]> extends [unknown, ...infer Rest]
287 ? Rest
288 : never
289 ): Effect.Effect<AggregateResult<Spec>, ClientError | E, R>;
290 create(...args: Args<Native<C, M, Row, S>["create"]>): Effect.Effect<Row, ClientError | E, R>;
291 createAll(
292 ...args: Parameters<Native<C, M, Row, S>["createAll"]>
293 ): QueryResult<Row, ClientError | E, R>;
294 createAndCount(
295 ...args: Parameters<Native<C, M, Row, S>["createAndCount"]>
296 ): Effect.Effect<number, ClientError | E, R>;
297 upsert(
298 ...args: Parameters<Native<C, M, Row, S>["upsert"]>
299 ): Effect.Effect<Row, ClientError | E, R>;
300 update(
301 ...args: Parameters<Native<C, M, Row, S>["update"]>
302 ): Effect.Effect<Row | null, ClientError | E, R>;
303 updateAll(
304 ...args: Parameters<Native<C, M, Row, S>["updateAll"]>
305 ): QueryResult<Row, ClientError | E, R>;
306 updateAndCount(
307 ...args: Parameters<Native<C, M, Row, S>["updateAndCount"]>
308 ): Effect.Effect<number, ClientError | E, R>;
309 delete(
310 this: S["hasWhere"] extends true ? EffectCollection<C, Ns, M, Row, S, E, R> : never,
311 ...args: Parameters<Native<C, M, Row, S>["delete"]>
312 ): Effect.Effect<Row | null, ClientError | E, R>;
313 deleteAll(
314 this: S["hasWhere"] extends true ? EffectCollection<C, Ns, M, Row, S, E, R> : never,
315 ...args: Parameters<Native<C, M, Row, S>["deleteAll"]>
316 ): QueryResult<Row, ClientError | E, R>;
317 deleteAndCount(
318 this: S["hasWhere"] extends true ? EffectCollection<C, Ns, M, Row, S, E, R> : never,
319 ...args: Parameters<Native<C, M, Row, S>["deleteAndCount"]>
320 ): Effect.Effect<number, ClientError | E, R>;
321 }
322
323 /** Grouped aggregates retain their selected keys and ordering requirements. */
324 export interface EffectGroupedCollection<
325 C extends AnyContract,
326 Ns extends string,
327 M extends string,
328 Fields extends readonly (keyof DefaultModelRow<C, M, Ns> & string)[],
329 Ordered extends boolean = false,
330 E = never,
331 R = never,
332 > {
333 having(
334 ...args: Parameters<GroupedCollection<C, M, Fields, Ns, Ordered>["having"]>
335 ): EffectGroupedCollection<C, Ns, M, Fields, Ordered, E, R>;
336 orderBy(
337 ...args: Parameters<GroupedCollection<C, M, Fields, Ns, Ordered>["orderBy"]>
338 ): EffectGroupedCollection<C, Ns, M, Fields, true, E, R>;
339 limit(
340 n: Ordered extends true ? number : never,
341 ): EffectGroupedCollection<C, Ns, M, Fields, Ordered, E, R>;
342 offset(
343 n: Ordered extends true ? number : never,
344 ): EffectGroupedCollection<C, Ns, M, Fields, Ordered, E, R>;
345 aggregate<Spec extends AggregateSpec>(
346 fn: (aggregate: AggregateBuilder<C, M, Ns>) => Spec,
347 ...configure: Parameters<GroupedCollection<C, M, Fields, Ns, Ordered>["aggregate"]> extends [
348 unknown,
349 ...infer Rest,
350 ]
351 ? Rest
352 : never
353 ): Effect.Effect<
354 Array<Simplify<Pick<DefaultModelRow<C, M, Ns>, Fields[number]> & AggregateResult<Spec>>>,
355 ClientError | E,
356 R
357 >;
358 }
359
360 export type EffectOrm<C extends AnyContract, E = never, R = never> = {
361 readonly [Ns in keyof C["domain"]["namespaces"] & string]: {
362 readonly [M in keyof C["domain"]["namespaces"][Ns]["models"] & string]: EffectCollection<
363 C,
364 Ns,
365 M,
366 NativeRow<Root<C, Ns, M>>,
367 InitialState<Ns>,
368 E,
369 R
370 >;
371 };
372 };
373
374 const TERMINALS = new Set([
375 "all",
376 "first",
377 "aggregate",
378 "create",
379 "createAll",
380 "createAndCount",
381 "upsert",
382 "update",
383 "updateAll",
384 "updateAndCount",
385 "delete",
386 "deleteAll",
387 "deleteAndCount",
388 ]);
389 const STREAMING_TERMINALS = new Set(["all", "createAll", "updateAll", "deleteAll"]);
390 interface PathStep {
391 readonly prop: string;
392 readonly args?: readonly unknown[];
393 }
394 const replayPath = (base: unknown, path: readonly PathStep[]): unknown =>
395 path.reduce<any>(
396 (current, step) =>
397 step.args === undefined ? current[step.prop] : current[step.prop](...step.args),
398 base,
399 );
400
401 const node = (root: Effect.Effect<unknown, any, any>, path: readonly PathStep[]): any =>
402 new Proxy(function () {}, {
403 get: (_target, prop) => {
404 if (typeof prop !== "string" || prop === "then") return undefined;
405 return node(root, [...path, { prop }]);
406 },
407 apply: (_target, _this, args: unknown[]) => {
408 const last = path[path.length - 1]!;
409 const called = [...path.slice(0, -1), { prop: last.prop, args }];
410 if (!TERMINALS.has(last.prop)) return node(root, called);
411 const effect = Effect.flatMap(root, (base) =>
412 Effect.tryPromise({
413 try: () => Promise.resolve(replayPath(base, called)),
414 catch: wrapPrismaError,
415 }),
416 );
417 if (!STREAMING_TERMINALS.has(last.prop)) return effect;
418 return Object.assign(effect, {
419 stream: Stream.unwrap(
420 Effect.flatMap(root, (base) =>
421 Effect.try({
422 try: () =>
423 Stream.fromAsyncIterable(
424 replayPath(base, called) as AsyncIterable<unknown>,
425 wrapPrismaError,
426 ),
427 catch: wrapPrismaError,
428 }),
429 ),
430 ),
431 });
432 },
433 });
434
435 /** Replays native builders per execution; refinement callbacks stay native and pure. */
436 export const makeOrmProxy = <C extends AnyContract, E, R>(
437 root: Effect.Effect<unknown, E, R>,
438 ): EffectOrm<C, E, R> => node(root, []);