cloesce 0.0.3 → 0.0.4-unstable.0

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.
Files changed (44) hide show
  1. package/dist/README.md +487 -0
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +221 -254
  4. package/dist/common.d.ts +69 -1
  5. package/dist/common.d.ts.map +1 -1
  6. package/dist/common.js +72 -11
  7. package/dist/{extract.d.ts → extractor/extract.d.ts} +5 -2
  8. package/dist/extractor/extract.d.ts.map +1 -0
  9. package/dist/{extract.js → extractor/extract.js} +242 -43
  10. package/dist/generator.wasm +0 -0
  11. package/dist/orm.wasm +0 -0
  12. package/dist/router/crud.d.ts +22 -0
  13. package/dist/router/crud.d.ts.map +1 -0
  14. package/dist/router/crud.js +65 -0
  15. package/dist/router/router.d.ts +77 -0
  16. package/dist/router/router.d.ts.map +1 -0
  17. package/dist/router/router.js +358 -0
  18. package/dist/router/wasm.d.ts +37 -0
  19. package/dist/router/wasm.d.ts.map +1 -0
  20. package/dist/router/wasm.js +98 -0
  21. package/dist/ui/backend.d.ts +124 -0
  22. package/dist/ui/backend.d.ts.map +1 -0
  23. package/dist/ui/backend.js +201 -0
  24. package/dist/ui/client.d.ts +5 -0
  25. package/dist/ui/client.d.ts.map +1 -0
  26. package/dist/ui/client.js +7 -0
  27. package/package.json +70 -58
  28. package/LICENSE +0 -201
  29. package/README.md +0 -23
  30. package/dist/cli.wasm +0 -0
  31. package/dist/cloesce.d.ts +0 -108
  32. package/dist/cloesce.d.ts.map +0 -1
  33. package/dist/cloesce.js +0 -453
  34. package/dist/decorators.d.ts +0 -13
  35. package/dist/decorators.d.ts.map +0 -1
  36. package/dist/decorators.js +0 -13
  37. package/dist/dog.cloesce.js +0 -111
  38. package/dist/extract.d.ts.map +0 -1
  39. package/dist/index.d.ts +0 -24
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/index.js +0 -24
  42. package/dist/types.d.ts +0 -4
  43. package/dist/types.d.ts.map +0 -1
  44. package/dist/types.js +0 -1
package/dist/README.md ADDED
@@ -0,0 +1,487 @@
1
+ # cloesce (unstable, `v0.0.4`)
2
+
3
+ Cloesce is a full stack compiler for the Cloudflare developer platform, allowing class definitions in high level languages to serve as a metadata basis to create a database schema, backend REST API, frontend API client, and Cloudflare infrastructure (as of v0.0.4, D1 + Workers).
4
+
5
+ Cloesce is working towards an alpha MVP (v0.1.0), with the general milestones being [here](https://cloesce.pages.dev/schreiber/v0.1.0_milestones/).
6
+
7
+ Internal documentation going over design decisions and general thoughts for each milestone can be found [here](https://cloesce.pages.dev/).
8
+
9
+ # Documentation `v0.0.4`
10
+
11
+ ## Getting Started
12
+
13
+ `v0.0.4` supports only Typescript-to-Typescript projects. An example project is shown [here](https://github.com/bens-schreiber/cloesce/tree/main/examples).
14
+
15
+ 1. NPM
16
+
17
+ - Create an NPM project and install cloesce
18
+
19
+ ```sh
20
+ npm i cloesce@0.0.4-unstable.0
21
+ ```
22
+
23
+ 2. TypeScript
24
+
25
+ - Create a `tsconfig.json` with the following values:
26
+
27
+ ```json
28
+ {
29
+ "compilerOptions": {
30
+ // ...
31
+ "resolveJsonModule": true,
32
+ "strict": true,
33
+ "strictPropertyInitialization": false,
34
+ "experimentalDecorators": true,
35
+ "emitDecoratorMetadata": true
36
+ },
37
+ "include": ["<your_src_dir>/**/*.ts", ".generated/*.ts"]
38
+ }
39
+ ```
40
+
41
+ 3. Cloesce Config
42
+
43
+ - Create a `cloesce.config.json` with the following keys:
44
+
45
+ ```json
46
+ {
47
+ "source": "./src",
48
+ "workersUrl": "http://localhost:5000/api",
49
+ "clientUrl": "http://localhost:5173/api"
50
+ }
51
+ ```
52
+
53
+ 4. Vite
54
+
55
+ To prevent CORS issues, a Vite proxy can be used for the frontend:
56
+
57
+ ```ts
58
+ import { defineConfig } from "vite";
59
+
60
+ export default defineConfig({
61
+ server: {
62
+ port: 5173,
63
+ proxy: {
64
+ "/api": {
65
+ target: "http://localhost:5000",
66
+ changeOrigin: true,
67
+ },
68
+ },
69
+ },
70
+ });
71
+ ```
72
+
73
+ 5. Wrangler Config
74
+
75
+ - `v0.0.4` will generate the required areas of your wrangler config. A full config looks like this:
76
+
77
+ ```toml
78
+ compatibility_date = "2025-10-02"
79
+ main = ".generated/workers.ts"
80
+ name = "example"
81
+
82
+ [[d1_databases]]
83
+ binding = "db"
84
+ database_id = "..."
85
+ database_name = "example"
86
+ ```
87
+
88
+ ## A Simple Model
89
+
90
+ A model is a type which represents:
91
+
92
+ - a database table,
93
+ - database views
94
+ - REST API
95
+ - Client API
96
+ - Cloudflare infrastructure (D1 + Workers)
97
+
98
+ Suprisingly, it's pretty compact. A basic model looks like this:
99
+
100
+ ```ts
101
+ // horse.cloesce.ts
102
+ import { D1, GET, POST, PrimaryKey } from "cloesce/backend";
103
+
104
+ @D1
105
+ export class Horse {
106
+ @PrimaryKey
107
+ id: number;
108
+
109
+ name: string | null;
110
+
111
+ @POST
112
+ neigh(): string {
113
+ return `i am ${this.name}, this is my horse noise`;
114
+ }
115
+ }
116
+ ```
117
+
118
+ - `@D1` denotes that this is a SQL Table
119
+ - `@PrimaryKey` sets the SQL primary key. All models require a primary key.
120
+ - `@POST` reveals the method as an API endpoint with the `POST` HTTP Verb.
121
+ - All Cloesce models need to be under a `.cloesce.ts` file.
122
+
123
+ To compile this model into a working full stack application, Cloesce must undergo both **compilation** and **migrations**. Compilation is the process of extracting the metadata language that powers Cloesce, ensuring it is a valid program, and then producing code to orchestrate the program across different domains (database, backend, frontend, cloud). Migrations utilize the history of validated metadata to create SQL code, translating the evolution of your models.
124
+
125
+ To compile, run `npx cloesce compile`.
126
+
127
+ To create a migration, run `npx cloesce migrate <name>`.
128
+
129
+ After running the above commands, you will have a full project capable of being ran with:
130
+
131
+ ```sh
132
+ # Apply the generated migrations
133
+ npx wrangler d1 migrations apply <db-name>
134
+
135
+ # Run the backend
136
+ npx wrangler dev
137
+ ```
138
+
139
+ Note the output in the `.generated/` dir. These values should not be committed to git, as they depend on the file system of the machine running it.
140
+
141
+ - `client.ts` is an importable API with all of your backend types and endpoints
142
+ - `workers.ts` is the workers entrypoint.
143
+ - `cidl.json` is the working metadata for the project
144
+
145
+ Note the output in `migrations`, ex after running `npx cloesce migrate Initial`
146
+
147
+ - `<date>_Initial.json` contains all model information necessary from SQL
148
+ - `<date>_Initial.sql` contains the acual SQL migrations. In this early version of Cloesce, it's important to check migrations every time.
149
+
150
+ ## Features
151
+
152
+ ### Wrangler Environment
153
+
154
+ In order to interact with your database, you will need to define a WranglerEnv
155
+
156
+ ```ts
157
+ // horse.cloesce.ts
158
+
159
+ import { WranglerEnv } from "cloesce/backend";
160
+
161
+ @WranglerEnv
162
+ export class Env {
163
+ db: D1Database; // only one DB is supported for now-- make sure it matches the name in `wrangler.toml`
164
+
165
+ // you can also define values in the toml under [[vars]]
166
+ motd: string;
167
+ }
168
+ ```
169
+
170
+ The wrangler environment is dependency injected into your method calls:
171
+
172
+ ```ts
173
+ @D1
174
+ export class Horse {
175
+ @PrimaryKey
176
+ id: number;
177
+
178
+ @POST
179
+ async neigh(@Inject env: WranglerEnv): Promise<string> {
180
+ await env.db.prepare(...);
181
+
182
+ return `i am ${this.name}, this is my horse noise`;
183
+ }
184
+ }
185
+ ```
186
+
187
+ ### Foreign Keys, One to One, Data Sources
188
+
189
+ Complex model relationships are permitted via the `@ForeignKey`, `@OneToOne / @OneToMany @ManyToMany` and `@DataSource` decorators.
190
+ Foreign keys are scalar attributes which must reference some other model's primary key:
191
+
192
+ ```ts
193
+ @D1
194
+ export class Dog {
195
+ @PrimaryKey
196
+ id: number;
197
+ }
198
+
199
+ @D1
200
+ export class Person {
201
+ @PrimaryKey
202
+ id: number;
203
+
204
+ @ForeignKey(Dog)
205
+ dogId: number;
206
+ }
207
+ ```
208
+
209
+ This representation is true to the underlying SQL table: `Person` has a column `dogId` which is a foreign key to `Dog`. Cloesce allows you to actually join these tables together in your model representation:
210
+
211
+ ```ts
212
+ @D1
213
+ export class Dog {
214
+ @PrimaryKey
215
+ id: number;
216
+ }
217
+
218
+ @D1
219
+ export class Person {
220
+ @PrimaryKey
221
+ id: number;
222
+
223
+ @ForeignKey(Dog)
224
+ dogId: number;
225
+
226
+ @OneToOne("dogId") // references Person.dogId
227
+ dog: Dog | undefined; // This value is a "navigation property", which may or may not exist at runtime
228
+ }
229
+ ```
230
+
231
+ In `v0.0.4`, there are no defaults, only very explicit decisons. Because of that, navigation properties won't exist at runtime unless you tell them to. Cloesce does this via a `DataSource`, which describes the foreign key dependencies you wish to include. All scalar properties are included by default and cannot be excluded.
232
+
233
+ ```ts
234
+ @D1
235
+ export class Dog {
236
+ @PrimaryKey
237
+ id: number;
238
+ }
239
+
240
+ @D1
241
+ export class Person {
242
+ @PrimaryKey
243
+ id: number;
244
+
245
+ @ForeignKey(Dog)
246
+ dogId: number;
247
+
248
+ @OneToOne("dogId")
249
+ dog: Dog | undefined;
250
+
251
+ @DataSource
252
+ static readonly default: IncludeTree<Person> = {
253
+ dog: {}, // says: on model population, join Persons's Dog
254
+ };
255
+ }
256
+ ```
257
+
258
+ Data sources are just SQL views and can be invoked in your queries. They are aliased in such a way that its similiar to object properties. The frontend chooses which datasource to use in it's API client. `null` is a valid option, meaning no joins will occur.
259
+
260
+ ```ts
261
+ @D1
262
+ export class Person {
263
+ @PrimaryKey
264
+ id: number;
265
+
266
+ @ForeignKey(Dog)
267
+ dogId: number;
268
+
269
+ @OneToOne("dogId")
270
+ dog: Dog | undefined;
271
+
272
+ @DataSource
273
+ static readonly default: IncludeTree<Person> = {
274
+ dog: {},
275
+ };
276
+
277
+ @GET
278
+ static async get(id: number, @Inject env: WranglerEnv): Promise<Person> {
279
+ let records = await env.db
280
+ .prepare("SELECT * FROM [Person.default] WHERE [Person.id] = ?") // Person.default is the SQL view generated from the IncludeTree
281
+ .bind(id)
282
+ .run();
283
+
284
+ let persons = Orm.fromSql(Person, records.results, Person.default);
285
+ return persons.value[0];
286
+ }
287
+ }
288
+ ```
289
+
290
+ Note that the `get` code can be simplified using CRUD methods or ORM primitives.
291
+
292
+ ### One to Many
293
+
294
+ Cloesce supports models with `1:M` relationships:
295
+
296
+ ```ts
297
+ @D1
298
+ export class Person {
299
+ @PrimaryKey
300
+ id: number;
301
+
302
+ @OneToMany("personId") // directly references the FK on Dog
303
+ dogs: Dog[];
304
+
305
+ @DataSource
306
+ static readonly default: IncludeTree<Person> = {
307
+ dogs: {
308
+ person: {
309
+ dogs: {
310
+ // essentially means: "When you get a person, get their dogs, and get all of those dog's Person, ..."
311
+ // we could go on as long as we want
312
+ },
313
+ },
314
+ },
315
+ };
316
+ }
317
+
318
+ @D1
319
+ export class Dog {
320
+ @PrimaryKey
321
+ id: number;
322
+
323
+ @ForeignKey(Person)
324
+ personId: number;
325
+
326
+ // optional navigation property, not needed.
327
+ @OneToOne("personId")
328
+ person: Person | undefined;
329
+ }
330
+ ```
331
+
332
+ ### Many to Many
333
+
334
+ ```ts
335
+ @D1
336
+ export class Student {
337
+ @PrimaryKey
338
+ id: number;
339
+
340
+ @ManyToMany("StudentsCourses") // unique ID for the generated junction table
341
+ courses: Course[];
342
+ }
343
+
344
+ @D1
345
+ export class Course {
346
+ @PrimaryKey
347
+ id: number;
348
+
349
+ @ManyToMany("StudentsCourses") // same unique id => same jct table.
350
+ students: Student[];
351
+ }
352
+ ```
353
+
354
+ ### ORM Methods
355
+
356
+ Cloesce provides a suite of ORM methods for getting, listing, updating and inserting models.
357
+
358
+ #### Upsert
359
+
360
+ ```ts
361
+ @D1
362
+ class Horse {
363
+ // ...
364
+
365
+ @POST
366
+ static async post(@Inject { db }: Env, horse: Horse): Promise<Horse> {
367
+ const orm = Orm.fromD1(db);
368
+ await orm.upsert(Horse, horse, null);
369
+ return (await orm.get(Horse, horse.id, null)).value;
370
+ }
371
+ }
372
+ ```
373
+
374
+ #### List, Get
375
+
376
+ ```ts
377
+ @D1
378
+ class Horse {
379
+ // ...
380
+ @GET
381
+ static async get(@Inject { db }: Env, id: number): Promise<Horse> {
382
+ const orm = Orm.fromD1(db);
383
+ return (await orm.get(Horse, id, "default")).value;
384
+ }
385
+
386
+ @GET
387
+ static async list(@Inject { db }: Env): Promise<Horse[]> {
388
+ const orm = Orm.fromD1(db);
389
+ return (await orm.list(Horse, "default")).value;
390
+ }
391
+ }
392
+ ```
393
+
394
+ ### CRUD Methods
395
+
396
+ Generic GET, POST, PATCH (and in a future version, DEL) boilerplate methods do not need to be copied around. Cloesce supports CRUD generation, a syntactic sugar that adds the methods to the compiler output.
397
+
398
+ ```ts
399
+ @CRUD(["POST", "GET", "LIST"])
400
+ @D1
401
+ export class CrudHaver {
402
+ @PrimaryKey
403
+ id: number;
404
+ name: string;
405
+ }
406
+ ```
407
+
408
+ which will generate client API methods like:
409
+
410
+ ```ts
411
+ static async get(
412
+ id: number,
413
+ dataSource: "none" = "none",
414
+ ): Promise<HttpResult<CrudHaver>>
415
+ ```
416
+
417
+ ### Plain Old Objects
418
+
419
+ Simple non-model objects can be returned and serialized from a model method:
420
+
421
+ ```ts
422
+ @PlainOldObject
423
+ export class CatStuff {
424
+ catFacts: string[],
425
+ catNames: string[],
426
+ }
427
+
428
+ @D1
429
+ export class Cat {
430
+ @PrimaryKey
431
+ id: number;
432
+
433
+ @GET
434
+ query(): CatStuff {
435
+ return {
436
+ catFacts: ["cats r cool"],
437
+ catNames: ["reginald"]
438
+ }
439
+ }
440
+ }
441
+ ```
442
+
443
+ ### HttpResult
444
+
445
+ Methods can return any kind of status code via the `HttpResult` wrapper:
446
+
447
+ ```ts
448
+ @D1
449
+ class Foo {
450
+ ...
451
+
452
+ @GET
453
+ async foo(): Promise<HttpResult<number>> {
454
+ return { ok: false, status: 500, message: "divided by 0"};
455
+ }
456
+ }
457
+ ```
458
+
459
+ # Testing the Compiler
460
+
461
+ ## Unit Tests
462
+
463
+ - `src/frontend/ts` run `npm test`
464
+ - `src/generator` run `cargo test`
465
+
466
+ ## Integration Tests
467
+
468
+ - Regression tests: `cargo run --bin test regression`
469
+ - Pass fail extractor tests: `cargo run --bin test run-fail`
470
+
471
+ Optionally, pass `--check` if new snapshots should not be created.
472
+
473
+ To update integration snapshots, run:
474
+
475
+ - `cargo run --bin update`
476
+
477
+ To delete any generated snapshots run:
478
+
479
+ - `cargo run --bin update -- -d`
480
+
481
+ ## E2E
482
+
483
+ - `tests/e2e` run `npm test`
484
+
485
+ ## Code Formatting
486
+
487
+ - `cargo fmt`, `cargo clippy`, `npm run format:fix`
package/dist/cli.d.ts CHANGED
@@ -1,2 +1,3 @@
1
+ #!/usr/bin/env node
1
2
  export {};
2
3
  //# sourceMappingURL=cli.d.ts.map