cloesce 0.0.5-unstable.4 → 0.0.5-unstable.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"wasm.d.ts","sourceRoot":"","sources":["../../src/router/wasm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,UAAU,EAAS,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAK/C,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAEzC;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC;IAC3B,cAAc,IAAI,MAAM,CAAC;IACzB,cAAc,IAAI,MAAM,CAAC;IACzB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/C,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;IAC3B,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IAExC,OAAO,CACL,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,EACpB,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;IAEX,YAAY,CACV,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,MAAM,EACtB,aAAa,EAAE,MAAM,EACrB,aAAa,EAAE,MAAM,EACrB,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;IAEX,WAAW,CACT,cAAc,EAAE,MAAM,EACtB,cAAc,EAAE,MAAM,EACtB,gBAAgB,EAAE,MAAM,EACxB,gBAAgB,EAAE,MAAM,EACxB,WAAW,EAAE,MAAM,EACnB,WAAW,EA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AAE,MAAM,EAAE,KAAK,OAAO,EAClC,IAAI,EAAE,YAAY,EAAE,EACpB,IAAI,EAAE,cAAc,GACnB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkBxB"}
@@ -1,10 +1,6 @@
1
- import { RuntimeContainer } from "./router.js";
2
- // Requires the ORM binary to have been built
1
+ import { Either } from "../common.js";
2
+ // NOTE: Requires the ORM binary to have been built
3
3
  import mod from "../orm.wasm";
4
- import { Either } from "../ui/common.js";
5
- /**
6
- * RAII for wasm memory
7
- */
8
4
  export class WasmResource {
9
5
  wasm;
10
6
  ptr;
@@ -18,9 +14,12 @@ export class WasmResource {
18
14
  this.wasm.dealloc(this.ptr, this.len);
19
15
  }
20
16
  /**
21
- * Copies a value from TS memory to WASM memory. A subsequent `free` is necessary.
17
+ * Copies a value from TS memory to WASM memory.
18
+ *
19
+ * A subsequent call to `free` is necessary.
22
20
  */
23
21
  static fromString(str, wasm) {
22
+ // TODO: Would be interesting to optimize this to avoid the intermediate copy
24
23
  const encoder = new TextEncoder();
25
24
  const bytes = encoder.encode(str);
26
25
  const ptr = wasm.alloc(bytes.length);
@@ -36,7 +35,10 @@ export async function loadOrmWasm(ast, wasm) {
36
35
  const modelMeta = WasmResource.fromString(JSON.stringify(ast.models), wasmInstance.exports);
37
36
  if (wasmInstance.exports.set_meta_ptr(modelMeta.ptr, modelMeta.len) != 0) {
38
37
  modelMeta.free();
39
- throw Error("The WASM Module failed to load due to an invalid CIDL");
38
+ const resPtr = wasmInstance.exports.get_return_ptr();
39
+ const resLen = wasmInstance.exports.get_return_len();
40
+ const errorMsg = new TextDecoder().decode(new Uint8Array(wasmInstance.exports.memory.buffer, resPtr, resLen));
41
+ throw Error(`"The WASM Module failed to load due to an invalid CIDL: ${errorMsg}`);
40
42
  }
41
43
  // Intentionally leak `modelMeta`, it should exist for the programs lifetime.
42
44
  return wasmInstance.exports;
@@ -63,44 +65,3 @@ export function invokeOrmWasm(fn, args, wasm) {
63
65
  wasm.dealloc(resPtr, resLen);
64
66
  }
65
67
  }
66
- /**
67
- * Calls the object relational mapping function to turn a row of SQL records into
68
- * an instantiated object.
69
- */
70
- export function mapSql(ctor, records, includeTree) {
71
- const { ast, constructorRegistry, wasm } = RuntimeContainer.get();
72
- const args = [
73
- WasmResource.fromString(ctor.name, wasm),
74
- WasmResource.fromString(JSON.stringify(records), wasm),
75
- WasmResource.fromString(JSON.stringify(includeTree), wasm),
76
- ];
77
- const jsonResults = invokeOrmWasm(wasm.map_sql, args, wasm);
78
- if (jsonResults.isLeft())
79
- return jsonResults;
80
- const parsed = JSON.parse(jsonResults.value);
81
- return Either.right(parsed.map((obj) => instantiateDepthFirst(obj, ast.models[ctor.name], includeTree)));
82
- // TODO: Lazy instantiation via Proxy?
83
- function instantiateDepthFirst(m, meta, includeTree) {
84
- m = Object.assign(new constructorRegistry[meta.name](), m);
85
- if (!includeTree) {
86
- return m;
87
- }
88
- for (const navProp of meta.navigation_properties) {
89
- const nestedIncludeTree = includeTree[navProp.var_name];
90
- if (!nestedIncludeTree)
91
- continue;
92
- const nestedMeta = ast.models[navProp.model_name];
93
- // One to Many, Many to Many
94
- if (Array.isArray(m[navProp.var_name])) {
95
- for (let i = 0; i < m[navProp.var_name].length; i++) {
96
- m[navProp.var_name][i] = instantiateDepthFirst(m[navProp.var_name][i], nestedMeta, nestedIncludeTree);
97
- }
98
- }
99
- // One to one
100
- else if (m[navProp.var_name]) {
101
- m[navProp.var_name] = instantiateDepthFirst(m[navProp.var_name], nestedMeta, nestedIncludeTree);
102
- }
103
- }
104
- return m;
105
- }
106
- }
@@ -1,63 +1,111 @@
1
- import { D1Database } from "@cloudflare/workers-types/experimental/index.js";
2
- import { DeepPartial, Either, KeysOfType } from "./common.js";
3
- import { CrudKind } from "../ast.js";
1
+ import { CrudKind, MediaType } from "../ast.js";
4
2
  /**
5
3
  * cloesce/backend
6
4
  */
7
- export { CloesceApp, DependencyContainer as DependencyInjector, } from "../router/router.js";
5
+ export { CloesceApp, DependencyContainer } from "../router/router.js";
8
6
  export type { MiddlewareFn, ResultMiddlewareFn } from "../router/router.js";
9
- export { HttpResult, Either, Stream } from "./common.js";
10
- export type { DeepPartial } from "./common.js";
11
7
  export type { CrudKind } from "../ast.js";
8
+ export { Orm } from "../router/orm.js";
9
+ export { R2ObjectBody } from "@cloudflare/workers-types";
12
10
  /**
13
- * Marks a class as a D1-backed SQL model.
11
+ * Base class for a Cloudflare KV model or navigation property.
14
12
  *
15
- * Classes annotated with `@D1` are compiled into:
16
- * - a D1 table definition (via `cloesce migrate`)
17
- * - backend API endpoints (Workers)
18
- * - a frontend client API
19
- * - Cloudflare Wrangler configurations
13
+ * Consists of a `key`, `value`, and optional `metadata`.
20
14
  *
21
- * Each `@D1` class must define exactly one `@PrimaryKey`.
15
+ * @template V The type of the value stored in the KValue. Note that KV is schema-less,
16
+ * so this type is not enforced at runtime, but serves as the type the client expects.
22
17
  *
23
- * Example:
24
- *```ts
25
- * @D1
26
- * export class Horse {
27
- * @PrimaryKey id: number;
28
- * name: string;
29
- * }
30
- * ```
18
+ * @remarks
19
+ * - The `key` is a string that uniquely identifies the entry in the KV store.
20
+ * - The `value` is of generic type `V`, allowing flexibility in the type of data stored.
21
+ * - `V` must be serializable to JSON.
22
+ * - The `metadata` can hold any additional information associated with the KV entry.
31
23
  */
32
- export declare const D1: ClassDecorator;
33
- export declare const Service: ClassDecorator;
24
+ export declare class KValue<V> {
25
+ key: string;
26
+ raw: unknown | null;
27
+ metadata: unknown | null;
28
+ get value(): V | null;
29
+ }
34
30
  /**
35
- * Marks a class as a plain serializable object.
31
+ * The result of a Workers endpoint.
36
32
  *
37
- * `@PlainOldObject` types represent data that can be safely
38
- * returned from a model method or API endpoint without being
39
- * treated as a database model.
33
+ * @param ok True if `status` < 400
34
+ * @param status The HTTP Status of a Workers request
35
+ * @param headers All headers that the result is to be sent with or was received with
36
+ * @param data JSON data yielded from a request, undefined if the request was not `ok`.
37
+ * @param message An error text set if the request was not `ok`.
40
38
  *
41
- * Example:
39
+ * @remarks If `status` is 204 `data` will always be undefined.
40
+ *
41
+ */
42
+ export declare class HttpResult<T = unknown> {
43
+ ok: boolean;
44
+ status: number;
45
+ headers: Headers;
46
+ data?: T | undefined;
47
+ message?: string | undefined;
48
+ mediaType?: MediaType | undefined;
49
+ constructor(ok: boolean, status: number, headers: Headers, data?: T | undefined, message?: string | undefined, mediaType?: MediaType | undefined);
50
+ static ok<T>(status: number, data?: T, init?: HeadersInit): HttpResult;
51
+ static fail(status: number, message?: string, init?: HeadersInit): HttpResult<never>;
52
+ toResponse(): Response;
53
+ setMediaType(mediaType: MediaType): this;
54
+ }
55
+ type DeepPartialInner<T> = T extends (infer U)[] ? DeepPartialInner<U>[] : T extends object ? {
56
+ [K in keyof T]?: DeepPartialInner<T[K]>;
57
+ } : T | (null extends T ? null : never);
58
+ /**
59
+ * Recursively makes all properties of a type optional — including nested objects and arrays.
60
+ *
61
+ * Similar to TypeScript's built-in `Partial<T>`, but applies the transformation deeply across
62
+ * all nested structures. Useful for defining "patch" or "update" objects where only a subset
63
+ * of properties may be provided.
64
+ *
65
+ * **Apart of the Cloesce method grammar**, meaning the type can be apart of method parameters
66
+ * or return types and the generated workers and client API will act accordingly.
67
+ *
68
+ * @template T
69
+ * The target type to make deeply partial.
70
+ *
71
+ * @remarks
72
+ * - **Objects:** All properties become optional, and their values are recursively wrapped in `DeepPartial`.
73
+ * - **Arrays:** Arrays are preserved, but their elements are recursively made partial.
74
+ * - **Scalars:** Primitive values (string, number, boolean, etc.) remain unchanged.
75
+ * - **Nullable types:** If `null` is assignable to the type, it remains allowed.
76
+ *
77
+ * @example
42
78
  * ```ts
43
- * @PlainOldObject
44
- * export class CatStuff {
45
- * catFacts: string[];
46
- * catNames: string[];
79
+ * class User {
80
+ * id: string;
81
+ * profile: {
82
+ * name: string;
83
+ * age: number;
84
+ * };
85
+ * tags: string[];
47
86
  * }
48
87
  *
49
- * // in a method...
50
- * foo(): CatStuff {
51
- * return {
52
- * catFacts: ["cats sleep 16 hours a day"],
53
- * catNames: ["Whiskers", "Fluffy"]
54
- * };
55
- *
56
- * // which generates an API like:
57
- * async function foo(): Promise<HttpResult<CatStuff>> { ... }
88
+ * // The resulting type:
89
+ * // {
90
+ * // id?: string;
91
+ * // profile?: { name?: string; age?: number };
92
+ * // tags?: (string | undefined)[];
93
+ * // }
94
+ * type PartialUser = DeepPartial<User>;
95
+ *
96
+ * const patch: PartialUser = {
97
+ * profile: { age: 30 } // ok
98
+ * };
58
99
  * ```
59
100
  */
60
- export declare const PlainOldObject: ClassDecorator;
101
+ export type DeepPartial<T> = DeepPartialInner<T> & {
102
+ __brand?: "Partial";
103
+ };
104
+ export type KeysOfType<T, U> = {
105
+ [K in keyof T]: T[K] extends U ? (K extends string ? K : never) : never;
106
+ }[keyof T];
107
+ export declare const Model: (_kinds?: CrudKind[]) => ClassDecorator;
108
+ export declare const Service: ClassDecorator;
61
109
  /**
62
110
  * Declares a Wrangler environment definition.
63
111
  *
@@ -97,6 +145,9 @@ export declare const WranglerEnv: ClassDecorator;
97
145
  * ```
98
146
  */
99
147
  export declare const PrimaryKey: PropertyDecorator;
148
+ export declare const KeyParam: PropertyDecorator;
149
+ export declare const KV: (_keyFormat?: string, _namespaceBinding?: string) => PropertyDecorator;
150
+ export declare const R2: (_keyFormat?: string, _bucketBinding?: string) => PropertyDecorator;
100
151
  /**
101
152
  * Exposes a class method as an HTTP GET endpoint.
102
153
  * The method will appear in both backend and generated client APIs.
@@ -122,100 +173,8 @@ export declare const PATCH: MethodDecorator;
122
173
  * The method will appear in both backend and generated client APIs.
123
174
  */
124
175
  export declare const DELETE: MethodDecorator;
125
- /**
126
- * Declares a static property as a data source.
127
- *
128
- * Data sources describe SQL left joins related to each
129
- * models navigation properties.
130
- *
131
- * Example:
132
- * ```ts
133
- * @D1
134
- * export class Dog {
135
- * @PrimaryKey
136
- * id: number;
137
- *
138
- * name: string;
139
- * }
140
- *
141
- * @D1
142
- * export class Person {
143
- * @PrimaryKey
144
- * id: number;
145
- *
146
- * @ForeignKey(Dog)
147
- * dogId: number;
148
- *
149
- * @OneToOne("dogId")
150
- * dog: Dog | undefined;
151
- *
152
- * @DataSource
153
- * static readonly default: IncludeTree<Person> = {
154
- * dog: {}, // join Dog table when querying Person with `default` data source
155
- * };
156
- * }
157
- *
158
- * // When queried via the ORM or client API:
159
- * const orm = Orm.fromD1(env.db);
160
- * const people = await orm.list(Person, Person.default);
161
- *
162
- * // => Person { id: 1, dogId: 2, dog: { id: 2, name: "Fido" } }[]
163
- * ```
164
- */
165
- export declare const DataSource: PropertyDecorator;
166
- /**
167
- * Declares a one-to-many relationship between models.
168
- *
169
- * The argument is the foreign key property name on the
170
- * related model.
171
- *
172
- * Example:
173
- * ```ts
174
- * @OneToMany("personId")
175
- * dogs: Dog[];
176
- * ```
177
- */
178
- export declare const OneToMany: (_foreignKeyColumn: string) => PropertyDecorator;
179
- /**
180
- * Declares a one-to-one relationship between models.
181
- *
182
- * The argument is the foreign key property name that links
183
- * the two tables.
184
- *
185
- * Example:
186
- * ```ts
187
- * @OneToOne("dogId")
188
- * dog: Dog | undefined;
189
- * ```
190
- */
191
- export declare const OneToOne: (_foreignKeyColumn: string) => PropertyDecorator;
192
- /**
193
- * Declares a many-to-many relationship between models.
194
- *
195
- * The argument is a unique identifier for the generated
196
- * junction table used to connect the two entities.
197
- *
198
- * Example:
199
- * ```ts
200
- * @ManyToMany("StudentsCourses")
201
- * courses: Course[];
202
- * ```
203
- */
204
- export declare const ManyToMany: (_uniqueId: string) => PropertyDecorator;
205
- /**
206
- * Declares a foreign key relationship between models.
207
- * Directly translates to a SQLite foreign key.
208
- *
209
- * The argument must reference either a model class or the
210
- * name of a model class as a string. The property type must
211
- * match the target model’s primary key type.
212
- *
213
- * Example:
214
- * ```ts
215
- * @ForeignKey(Dog)
216
- * dogId: number;
217
- * ```
218
- */
176
+ export declare function OneToMany<T>(_selector: (model: T) => T[keyof T]): PropertyDecorator;
177
+ export declare function OneToOne<T>(_selector: (model: T) => T[keyof T]): PropertyDecorator;
219
178
  export declare const ForeignKey: <T>(_Model: T | string) => PropertyDecorator;
220
179
  /**
221
180
  * Marks a method parameter for dependency injection.
@@ -235,35 +194,6 @@ export declare const ForeignKey: <T>(_Model: T | string) => PropertyDecorator;
235
194
  * ```
236
195
  */
237
196
  export declare const Inject: ParameterDecorator;
238
- /**
239
- * Enables automatic CRUD method generation for a model.
240
- *
241
- * The argument is a list of CRUD operation kinds
242
- * (e.g. `"SAVE"`, `"GET"`, `"LIST"`) to generate for the model.
243
- *
244
- * Cloesce will emit corresponding backend methods and frontend
245
- * client bindings automatically, removing the need to manually
246
- * define common API operations.
247
- *
248
- * CRUD Operations:
249
- * - **"SAVE"** — Performs an *upsert* (insert, update, or both) for a model instance.
250
- * - **"GET"** — Retrieves a single record by its primary key, optionally using a `DataSource`.
251
- * - **"LIST"** — Retrieves all records for the model, using the specified `DataSource`.
252
- *
253
- * The generated methods are static, exposed through both the backend
254
- * and the frontend client API.
255
- *
256
- * Example:
257
- * ```ts
258
- * @CRUD(["SAVE", "GET", "LIST"])
259
- * @D1
260
- * export class CrudHaver {
261
- * @PrimaryKey id: number;
262
- * name: string;
263
- * }
264
- * ```
265
- */
266
- export declare const CRUD: (_kinds: CrudKind[]) => ClassDecorator;
267
197
  type Primitive = string | number | boolean | bigint | symbol | null | undefined;
268
198
  /**
269
199
  * A recursive type describing which related models to include
@@ -344,180 +274,4 @@ export type DataSourceOf<T extends object> = (KeysOfType<T, IncludeTree<T>> | "n
344
274
  export type Integer = number & {
345
275
  __brand?: "Integer";
346
276
  };
347
- /**
348
- * Exposes the ORM primitives Cloesce uses to interact with D1 databases.
349
- */
350
- export declare class Orm {
351
- private db;
352
- private constructor();
353
- /**
354
- * Creates an instance of an `Orm`
355
- * @param db The database to use for ORM calls.
356
- */
357
- static fromD1(db: D1Database): Orm;
358
- /**
359
- * Maps SQL records to an instantiated Model. The records must be flat
360
- * (e.g., of the form "id, name, address") or derive from a Cloesce data source view
361
- * (e.g., of the form "Horse.id, Horse.name, Horse.address")
362
- *
363
- * Assumes the data is formatted correctly, throwing an error otherwise.
364
- *
365
- * @param ctor The model constructor
366
- * @param records D1 Result records
367
- * @param includeTree Include tree to define the relationships to join.
368
- */
369
- static mapSql<T extends object>(ctor: new () => T, records: Record<string, any>[], includeTree?: IncludeTree<T> | null): T[];
370
- /**
371
- * Executes an "upsert" query, adding or augmenting a model in the database.
372
- *
373
- * If a model's primary key is not defined in `newModel`, the query is assumed to be an insert.
374
- *
375
- * If a model's primary key _is_ defined, but some attributes are missing, the query is assumed to be an update.
376
- *
377
- * Finally, if the primary key is defined, but all attributes are included, a SQLite upsert will be performed.
378
- *
379
- * In any other case, an error string will be returned.
380
- *
381
- * ### Inserting a new Model
382
- * ```ts
383
- * const model = {name: "julio", lastname: "pumpkin"};
384
- * const idRes = await orm.upsert(Person, model, null);
385
- * ```
386
- *
387
- * ### Updating an existing model
388
- * ```ts
389
- * const model = {id: 1, name: "timothy"};
390
- * const idRes = await orm.upsert(Person, model, null);
391
- * // (in db)=> {id: 1, name: "timothy", lastname: "pumpkin"}
392
- * ```
393
- *
394
- * ### Upserting a model
395
- * ```ts
396
- * // (assume a Person already exists)
397
- * const model = {
398
- * id: 1,
399
- * lastname: "burger", // updates last name
400
- * dog: {
401
- * name: "fido" // insert dog relationship
402
- * }
403
- * };
404
- * const idRes = await orm.upsert(Person, model, null);
405
- * // (in db)=> Person: {id: 1, dogId: 1 ...} ; Dog: {id: 1, name: "fido"}
406
- * ```
407
- *
408
- * @param ctor A model constructor.
409
- * @param newModel The new or augmented model.
410
- * @param includeTree An include tree describing which foreign keys to join.
411
- * @returns An error string, or the primary key of the inserted model.
412
- */
413
- upsert<T extends object>(ctor: new () => T, newModel: DeepPartial<T>, includeTree?: IncludeTree<T> | null): Promise<Either<string, any>>;
414
- /**
415
- * Returns a select query, creating a CTE view for the model using the provided include tree.
416
- *
417
- * @param ctor The model constructor.
418
- * @param includeTree An include tree describing which related models to join.
419
- * @param from An optional custom `FROM` clause to use instead of the base table.
420
- * @param tagCte An optional CTE name to tag the query with. Defaults to "Model.view".
421
- *
422
- * ### Example:
423
- * ```ts
424
- * // Using a data source
425
- * const query = Orm.listQuery(Person, "default");
426
- *
427
- * // Using a custom from statement
428
- * const query = Orm.listQuery(Person, null, "SELECT * FROM Person WHERE age > 18");
429
- * ```
430
- *
431
- * ### Example SQL output:
432
- * ```sql
433
- * WITH Person_view AS (
434
- * SELECT
435
- * "Person"."id" AS "id",
436
- * ...
437
- * FROM "Person"
438
- * LEFT JOIN ...
439
- * )
440
- * SELECT * FROM Person_view
441
- * ```
442
- */
443
- static listQuery<T extends object>(ctor: new () => T, opts: {
444
- includeTree?: IncludeTree<T> | null;
445
- from?: string;
446
- tagCte?: string;
447
- }): string;
448
- /**
449
- * Returns a select query for a single model by primary key, creating a CTE view using the provided include tree.
450
- *
451
- * @param ctor The model constructor.
452
- * @param includeTree An include tree describing which related models to join.
453
- *
454
- * ### Example:
455
- * ```ts
456
- * // Using a data source
457
- * const query = Orm.getQuery(Person, "default");
458
- * ```
459
- *
460
- * ### Example SQL output:
461
- *
462
- * ```sql
463
- * WITH Person_view AS (
464
- * SELECT
465
- * "Person"."id" AS "id",
466
- * ...
467
- * FROM "Person"
468
- * LEFT JOIN ...
469
- * )
470
- * SELECT * FROM Person_view WHERE [Person].[id] = ?
471
- * ```
472
- */
473
- static getQuery<T extends object>(ctor: new () => T, includeTree?: IncludeTree<T> | null): string;
474
- /**
475
- * Retrieves all instances of a model from the database.
476
- * @param ctor The model constructor.
477
- * @param includeTree An include tree describing which related models to join.
478
- * @param from An optional custom `FROM` clause to use instead of the base table.
479
- * @returns Either an error string, or an array of model instances.
480
- *
481
- * ### Example:
482
- * ```ts
483
- * const orm = Orm.fromD1(env.db);
484
- * const horses = await orm.list(Horse, Horse.default);
485
- * ```
486
- *
487
- * ### Example with custom from:
488
- * ```ts
489
- * const orm = Orm.fromD1(env.db);
490
- * const adultHorses = await orm.list(Horse, Horse.default, "SELECT * FROM Horse ORDER BY age DESC LIMIT 10");
491
- * ```
492
- *
493
- * =>
494
- *
495
- * ```sql
496
- * SELECT
497
- * "Horse"."id" AS "id",
498
- * ...
499
- * FROM (SELECT * FROM Horse ORDER BY age DESC LIMIT 10)
500
- * LEFT JOIN ...
501
- * ```
502
- *
503
- */
504
- list<T extends object>(ctor: new () => T, opts: {
505
- includeTree?: IncludeTree<T> | null;
506
- from?: string;
507
- }): Promise<Either<string, T[]>>;
508
- /**
509
- * Retrieves a single model by primary key.
510
- * @param ctor The model constructor.
511
- * @param id The primary key value.
512
- * @param includeTree An include tree describing which related models to join.
513
- * @returns Either an error string, or the model instance (null if not found).
514
- *
515
- * ### Example:
516
- * ```ts
517
- * const orm = Orm.fromD1(env.db);
518
- * const horse = await orm.get(Horse, 1, Horse.default);
519
- * ```
520
- */
521
- get<T extends object>(ctor: new () => T, id: any, includeTree?: IncludeTree<T> | null): Promise<Either<string, T | null>>;
522
- }
523
277
  //# sourceMappingURL=backend.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"backend.d.ts","sourceRoot":"","sources":["../../src/ui/backend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iDAAiD,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,EAAW,MAAM,aAAa,CAAC;AAGvE,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC;;GAEG;AACH,OAAO,EACL,UAAU,EACV,mBAAmB,IAAI,kBAAkB,GAC1C,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,YAAY,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAE1C;;;;;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