appflare 0.2.41 → 0.2.43

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 (145) hide show
  1. package/Documentation.md +898 -758
  2. package/cli/commands/index.ts +247 -247
  3. package/cli/generate.ts +360 -360
  4. package/cli/index.ts +120 -120
  5. package/cli/load-config.ts +184 -184
  6. package/cli/schema-compiler.ts +1363 -1361
  7. package/cli/templates/auth/README.md +156 -156
  8. package/cli/templates/auth/config.ts +61 -61
  9. package/cli/templates/auth/route-config.ts +1 -1
  10. package/cli/templates/auth/route-handler.ts +1 -1
  11. package/cli/templates/auth/route-request-utils.ts +5 -5
  12. package/cli/templates/auth/route.config.ts +18 -18
  13. package/cli/templates/auth/route.handler.ts +18 -18
  14. package/cli/templates/auth/route.request-utils.ts +55 -55
  15. package/cli/templates/auth/route.ts +14 -14
  16. package/cli/templates/core/README.md +266 -266
  17. package/cli/templates/core/app-creation.ts +19 -19
  18. package/cli/templates/core/client/appflare.ts +112 -112
  19. package/cli/templates/core/client/handlers/index.ts +763 -755
  20. package/cli/templates/core/client/handlers.ts +1 -1
  21. package/cli/templates/core/client/index.ts +7 -7
  22. package/cli/templates/core/client/storage.ts +195 -195
  23. package/cli/templates/core/client/types.ts +187 -186
  24. package/cli/templates/core/client-modules/appflare.ts +1 -1
  25. package/cli/templates/core/client-modules/handlers.ts +1 -1
  26. package/cli/templates/core/client-modules/index.ts +1 -1
  27. package/cli/templates/core/client-modules/storage.ts +1 -1
  28. package/cli/templates/core/client-modules/types.ts +1 -1
  29. package/cli/templates/core/client.artifacts.ts +39 -39
  30. package/cli/templates/core/client.ts +4 -4
  31. package/cli/templates/core/drizzle.ts +15 -15
  32. package/cli/templates/core/export.ts +14 -14
  33. package/cli/templates/core/handlers.route.ts +24 -24
  34. package/cli/templates/core/handlers.ts +1 -1
  35. package/cli/templates/core/imports.ts +9 -9
  36. package/cli/templates/core/server.ts +38 -38
  37. package/cli/templates/core/types.ts +6 -6
  38. package/cli/templates/core/wrangler.ts +109 -109
  39. package/cli/templates/dashboard/builders/functions/index.ts +17 -17
  40. package/cli/templates/dashboard/builders/functions/render-page/header.ts +20 -20
  41. package/cli/templates/dashboard/builders/functions/render-page/index.ts +33 -33
  42. package/cli/templates/dashboard/builders/functions/render-page/request-panel.ts +171 -171
  43. package/cli/templates/dashboard/builders/functions/render-page/result-panel.ts +85 -85
  44. package/cli/templates/dashboard/builders/functions/render-page/scripts.ts +554 -554
  45. package/cli/templates/dashboard/builders/functions/tree-builder.ts +47 -47
  46. package/cli/templates/dashboard/builders/navigation.ts +155 -155
  47. package/cli/templates/dashboard/builders/storage/index.ts +13 -13
  48. package/cli/templates/dashboard/builders/storage/routes/create-directory-route.ts +29 -29
  49. package/cli/templates/dashboard/builders/storage/routes/delete-route.ts +18 -18
  50. package/cli/templates/dashboard/builders/storage/routes/download-route.ts +23 -23
  51. package/cli/templates/dashboard/builders/storage/routes/index.ts +22 -22
  52. package/cli/templates/dashboard/builders/storage/routes/list-route.ts +25 -25
  53. package/cli/templates/dashboard/builders/storage/routes/preview-route.ts +21 -21
  54. package/cli/templates/dashboard/builders/storage/routes/upload-route.ts +21 -21
  55. package/cli/templates/dashboard/builders/storage/runtime/helpers.ts +72 -72
  56. package/cli/templates/dashboard/builders/storage/runtime/storage-page.ts +130 -130
  57. package/cli/templates/dashboard/builders/table-routes/common/drawer-panel.ts +27 -27
  58. package/cli/templates/dashboard/builders/table-routes/common/pagination.ts +30 -30
  59. package/cli/templates/dashboard/builders/table-routes/common/search-bar.ts +23 -23
  60. package/cli/templates/dashboard/builders/table-routes/fragments.ts +217 -217
  61. package/cli/templates/dashboard/builders/table-routes/helpers.ts +45 -45
  62. package/cli/templates/dashboard/builders/table-routes/index.ts +8 -8
  63. package/cli/templates/dashboard/builders/table-routes/table/actions-cell.ts +71 -71
  64. package/cli/templates/dashboard/builders/table-routes/table/get-route.ts +291 -291
  65. package/cli/templates/dashboard/builders/table-routes/table/index.ts +80 -80
  66. package/cli/templates/dashboard/builders/table-routes/table/post-routes.ts +163 -163
  67. package/cli/templates/dashboard/builders/table-routes/table-route.ts +7 -7
  68. package/cli/templates/dashboard/builders/table-routes/users/get-route.ts +69 -69
  69. package/cli/templates/dashboard/builders/table-routes/users/html/modals.ts +57 -57
  70. package/cli/templates/dashboard/builders/table-routes/users/html/page.ts +27 -27
  71. package/cli/templates/dashboard/builders/table-routes/users/html/table.ts +128 -128
  72. package/cli/templates/dashboard/builders/table-routes/users/index.ts +32 -32
  73. package/cli/templates/dashboard/builders/table-routes/users/post-routes.ts +150 -150
  74. package/cli/templates/dashboard/builders/table-routes/users/redirect.ts +14 -14
  75. package/cli/templates/dashboard/builders/table-routes/users-route.ts +10 -10
  76. package/cli/templates/dashboard/components/dashboard-home.ts +23 -23
  77. package/cli/templates/dashboard/components/layout.ts +420 -420
  78. package/cli/templates/dashboard/components/login-page.ts +65 -65
  79. package/cli/templates/dashboard/index.ts +61 -61
  80. package/cli/templates/dashboard/types.ts +9 -9
  81. package/cli/templates/handlers/README.md +353 -353
  82. package/cli/templates/handlers/auth.ts +37 -37
  83. package/cli/templates/handlers/execution.ts +42 -42
  84. package/cli/templates/handlers/generators/context/context-creation.ts +101 -101
  85. package/cli/templates/handlers/generators/context/error-helpers.ts +11 -11
  86. package/cli/templates/handlers/generators/context/scheduler.ts +24 -24
  87. package/cli/templates/handlers/generators/context/storage-api.ts +82 -82
  88. package/cli/templates/handlers/generators/context/storage-helpers.ts +59 -59
  89. package/cli/templates/handlers/generators/context/types.ts +40 -40
  90. package/cli/templates/handlers/generators/context.ts +43 -43
  91. package/cli/templates/handlers/generators/execution.ts +15 -15
  92. package/cli/templates/handlers/generators/handlers.ts +14 -14
  93. package/cli/templates/handlers/generators/registration/modules/cron.ts +26 -26
  94. package/cli/templates/handlers/generators/registration/modules/realtime/auth.ts +75 -75
  95. package/cli/templates/handlers/generators/registration/modules/realtime/durable-object.ts +144 -144
  96. package/cli/templates/handlers/generators/registration/modules/realtime/index.ts +14 -14
  97. package/cli/templates/handlers/generators/registration/modules/realtime/publisher.ts +102 -102
  98. package/cli/templates/handlers/generators/registration/modules/realtime/routes.ts +164 -164
  99. package/cli/templates/handlers/generators/registration/modules/realtime/types.ts +30 -30
  100. package/cli/templates/handlers/generators/registration/modules/realtime/utils.ts +510 -510
  101. package/cli/templates/handlers/generators/registration/modules/scheduler.ts +56 -56
  102. package/cli/templates/handlers/generators/registration/modules/storage.ts +199 -199
  103. package/cli/templates/handlers/generators/registration/sections.ts +210 -210
  104. package/cli/templates/handlers/generators/types/context.ts +121 -121
  105. package/cli/templates/handlers/generators/types/core.ts +106 -106
  106. package/cli/templates/handlers/generators/types/operations.ts +135 -135
  107. package/cli/templates/handlers/generators/types/query-definitions/filter-and-where-types.ts +291 -271
  108. package/cli/templates/handlers/generators/types/query-definitions/query-api-types.ts +135 -135
  109. package/cli/templates/handlers/generators/types/query-definitions/query-helper-functions.ts +1382 -1382
  110. package/cli/templates/handlers/generators/types/query-definitions/schema-and-table-types.ts +278 -278
  111. package/cli/templates/handlers/generators/types/query-definitions.ts +13 -13
  112. package/cli/templates/handlers/generators/types/query-runtime/handled-error.ts +13 -13
  113. package/cli/templates/handlers/generators/types/query-runtime/runtime-aggregate-and-footer.ts +174 -174
  114. package/cli/templates/handlers/generators/types/query-runtime/runtime-read.ts +157 -157
  115. package/cli/templates/handlers/generators/types/query-runtime/runtime-setup.ts +45 -45
  116. package/cli/templates/handlers/generators/types/query-runtime/runtime-write.ts +958 -697
  117. package/cli/templates/handlers/generators/types/query-runtime.ts +15 -15
  118. package/cli/templates/handlers/index.ts +47 -47
  119. package/cli/templates/handlers/operations.ts +116 -116
  120. package/cli/templates/handlers/registration.ts +91 -91
  121. package/cli/templates/handlers/types.ts +17 -17
  122. package/cli/templates/handlers/utils.ts +48 -48
  123. package/cli/types.ts +110 -110
  124. package/cli/utils/handler-discovery.ts +466 -466
  125. package/cli/utils/json-utils.ts +24 -24
  126. package/cli/utils/path-utils.ts +19 -19
  127. package/cli/utils/schema-discovery.ts +399 -399
  128. package/dist/cli/index.js +320 -31
  129. package/dist/cli/index.mjs +320 -31
  130. package/dist/index.js +1 -1
  131. package/dist/index.mjs +1 -1
  132. package/dist/react/index.d.mts +2 -0
  133. package/dist/react/index.d.ts +2 -0
  134. package/dist/react/index.js +1 -1
  135. package/dist/react/index.mjs +1 -1
  136. package/index.ts +18 -18
  137. package/package.json +58 -58
  138. package/react/index.ts +5 -5
  139. package/react/use-infinite-query.ts +255 -252
  140. package/react/use-mutation.ts +89 -89
  141. package/react/use-query.ts +210 -207
  142. package/schema.ts +641 -641
  143. package/test-better-auth-hash.ts +2 -2
  144. package/tsconfig.json +6 -6
  145. package/tsup.config.ts +82 -82
@@ -1,1361 +1,1363 @@
1
- import { mkdir } from "node:fs/promises";
2
- import { dirname, resolve } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import type {
5
- ColumnDefinition,
6
- ColumnType,
7
- JsonShape,
8
- ManyRelationDefinition,
9
- ManyToManyRelationDefinition,
10
- OneRelationDefinition,
11
- SchemaDefinition,
12
- TableDefinition,
13
- } from "../schema";
14
- import { isSchemaDefinition } from "../schema";
15
- import type { LoadedAppflareConfig } from "./types";
16
-
17
- export type CompiledSchemaArtifacts = {
18
- schemaPath: string;
19
- typesPath: string;
20
- zodPath: string;
21
- tableNames: string[];
22
- };
23
-
24
- function toSnakeCase(value: string): string {
25
- return value
26
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
27
- .replace(/[\s-]+/g, "_")
28
- .toLowerCase();
29
- }
30
-
31
- function toPascalCase(value: string): string {
32
- return value
33
- .replace(/[_-]+/g, " ")
34
- .replace(/\s+(.)/g, (_match, char: string) => char.toUpperCase())
35
- .replace(/\s/g, "")
36
- .replace(/^(.)/, (_match, char: string) => char.toUpperCase());
37
- }
38
-
39
- function singularize(value: string): string {
40
- if (value.endsWith("ies")) {
41
- return `${value.slice(0, -3)}y`;
42
- }
43
- if (value.endsWith("ses")) {
44
- return value.slice(0, -2);
45
- }
46
- if (value.endsWith("s") && value.length > 1) {
47
- return value.slice(0, -1);
48
- }
49
- return value;
50
- }
51
-
52
- function quote(value: string): string {
53
- return JSON.stringify(value);
54
- }
55
-
56
- function toSqlLiteral(value: unknown): string {
57
- if (typeof value === "string") {
58
- return quote(value);
59
- }
60
- if (typeof value === "number" || typeof value === "boolean") {
61
- return String(value);
62
- }
63
- if (value === null) {
64
- return "null";
65
- }
66
- if (value instanceof Date) {
67
- return quote(value.toISOString());
68
- }
69
- throw new Error(
70
- `Unsupported SQL default value '${String(value)}'. Use string, number, boolean, null, or Date.`,
71
- );
72
- }
73
-
74
- function cloneSchemaDefinition(definition: SchemaDefinition): SchemaDefinition {
75
- return {
76
- kind: "schema",
77
- tables: Object.fromEntries(
78
- Object.entries(definition.tables).map(([tableName, table]) => {
79
- return [
80
- tableName,
81
- {
82
- kind: "table",
83
- sqlName: table.sqlName,
84
- columns: Object.fromEntries(
85
- Object.entries(table.columns).map(([columnName, column]) => {
86
- return [columnName, { ...column }];
87
- }),
88
- ),
89
- relations: Object.fromEntries(
90
- Object.entries(table.relations).map(
91
- ([relationName, relation]) => {
92
- return [relationName, { ...relation }];
93
- },
94
- ),
95
- ),
96
- } satisfies TableDefinition,
97
- ];
98
- }),
99
- ),
100
- enums: Object.fromEntries(
101
- Object.entries(definition.enums ?? {}).map(([name, enumDef]) => {
102
- return [name, { ...enumDef }];
103
- }),
104
- ),
105
- };
106
- }
107
-
108
- function getLocalReferenceType(
109
- definition: SchemaDefinition,
110
- targetTable: string,
111
- referenceField: string,
112
- ): ColumnType | undefined {
113
- const table = definition.tables[targetTable];
114
- if (!table) {
115
- return undefined;
116
- }
117
- const targetColumn = table.columns[referenceField];
118
- return targetColumn?.type;
119
- }
120
-
121
- function ensureInferredReferenceColumn(
122
- tableName: string,
123
- table: TableDefinition,
124
- columnName: string,
125
- referenceTable: string,
126
- referenceField: string,
127
- options: {
128
- fkType?: ColumnType;
129
- sqlName?: string;
130
- notNull?: boolean;
131
- onDelete?: OneRelationDefinition["onDelete"];
132
- onUpdate?: OneRelationDefinition["onUpdate"];
133
- },
134
- inferredType: ColumnType,
135
- ): void {
136
- const existing = table.columns[columnName];
137
- if (existing) {
138
- if (
139
- existing.references &&
140
- (existing.references.table !== referenceTable ||
141
- existing.references.column !== referenceField)
142
- ) {
143
- throw new Error(
144
- `Inferred relation '${tableName}.${columnName}' conflicts with explicit references(${existing.references.table}.${existing.references.column}).`,
145
- );
146
- }
147
-
148
- table.columns[columnName] = {
149
- ...existing,
150
- notNull:
151
- existing.notNull ??
152
- (existing.nullable === true ? false : options.notNull),
153
- nullable:
154
- existing.nullable ?? (options.notNull === false ? true : undefined),
155
- references: {
156
- table: referenceTable,
157
- column: referenceField,
158
- onDelete: existing.references?.onDelete ?? options.onDelete,
159
- onUpdate: existing.references?.onUpdate ?? options.onUpdate,
160
- },
161
- };
162
- return;
163
- }
164
-
165
- table.columns[columnName] = {
166
- kind: "column",
167
- type: options.fkType ?? inferredType,
168
- sqlName: options.sqlName,
169
- notNull: options.notNull ?? true,
170
- nullable: options.notNull === false ? true : undefined,
171
- references: {
172
- table: referenceTable,
173
- column: referenceField,
174
- onDelete: options.onDelete,
175
- onUpdate: options.onUpdate,
176
- },
177
- };
178
- }
179
-
180
- function resolveNotNullFromNullableFlags(
181
- fieldPath: string,
182
- flags: { notNull?: boolean; nullable?: boolean },
183
- defaultNotNull: boolean,
184
- ): boolean {
185
- if (flags.notNull === true && flags.nullable === true) {
186
- throw new Error(
187
- `Invalid nullable configuration on '${fieldPath}': cannot set both notNull and nullable to true.`,
188
- );
189
- }
190
-
191
- if (flags.notNull === true) {
192
- return true;
193
- }
194
-
195
- if (flags.nullable === true) {
196
- return false;
197
- }
198
-
199
- if (flags.notNull === false) {
200
- return false;
201
- }
202
-
203
- return defaultNotNull;
204
- }
205
-
206
- type ManyToManyPair = {
207
- leftTable: string;
208
- leftReferenceField: string;
209
- rightTable: string;
210
- rightReferenceField: string;
211
- junctionTable: string;
212
- leftField: string;
213
- rightField: string;
214
- leftSqlName?: string;
215
- rightSqlName?: string;
216
- onDelete?: OneRelationDefinition["onDelete"];
217
- onUpdate?: OneRelationDefinition["onUpdate"];
218
- };
219
-
220
- function endpointKey(tableName: string, referenceField: string): string {
221
- return `${tableName}:${referenceField}`;
222
- }
223
-
224
- function normalizeManyToManyPairKey(
225
- sourceTable: string,
226
- sourceReferenceField: string,
227
- targetTable: string,
228
- targetReferenceField: string,
229
- ): {
230
- key: string;
231
- leftTable: string;
232
- leftReferenceField: string;
233
- rightTable: string;
234
- rightReferenceField: string;
235
- sourceIsLeft: boolean;
236
- } {
237
- const source = endpointKey(sourceTable, sourceReferenceField);
238
- const target = endpointKey(targetTable, targetReferenceField);
239
- const sourceIsLeft = source <= target;
240
-
241
- if (sourceIsLeft) {
242
- return {
243
- key: `${source}|${target}`,
244
- leftTable: sourceTable,
245
- leftReferenceField: sourceReferenceField,
246
- rightTable: targetTable,
247
- rightReferenceField: targetReferenceField,
248
- sourceIsLeft: true,
249
- };
250
- }
251
-
252
- return {
253
- key: `${target}|${source}`,
254
- leftTable: targetTable,
255
- leftReferenceField: targetReferenceField,
256
- rightTable: sourceTable,
257
- rightReferenceField: sourceReferenceField,
258
- sourceIsLeft: false,
259
- };
260
- }
261
-
262
- function defaultManyToManyJunctionTable(
263
- leftTable: string,
264
- rightTable: string,
265
- ): string {
266
- return `${leftTable}${toPascalCase(rightTable)}Links`;
267
- }
268
-
269
- function defaultManyToManyFieldName(
270
- ownerTable: string,
271
- otherTable: string,
272
- suffix: "source" | "target",
273
- ): string {
274
- const ownerSingular = singularize(ownerTable);
275
- const otherSingular = singularize(otherTable);
276
-
277
- if (ownerSingular === otherSingular) {
278
- return `${suffix}${toPascalCase(ownerSingular)}Id`;
279
- }
280
-
281
- return `${ownerSingular}Id`;
282
- }
283
-
284
- function mergeManyToManyPairConfig(
285
- existing: ManyToManyPair,
286
- incoming: ManyToManyPair,
287
- pairKey: string,
288
- ): ManyToManyPair {
289
- if (existing.junctionTable !== incoming.junctionTable) {
290
- throw new Error(
291
- `manyToMany pair '${pairKey}' has conflicting junctionTable values ('${existing.junctionTable}' vs '${incoming.junctionTable}').`,
292
- );
293
- }
294
-
295
- if (existing.leftField !== incoming.leftField) {
296
- throw new Error(
297
- `manyToMany pair '${pairKey}' has conflicting left field values ('${existing.leftField}' vs '${incoming.leftField}').`,
298
- );
299
- }
300
-
301
- if (existing.rightField !== incoming.rightField) {
302
- throw new Error(
303
- `manyToMany pair '${pairKey}' has conflicting right field values ('${existing.rightField}' vs '${incoming.rightField}').`,
304
- );
305
- }
306
-
307
- if (existing.leftSqlName !== incoming.leftSqlName) {
308
- throw new Error(
309
- `manyToMany pair '${pairKey}' has conflicting left sql name values ('${existing.leftSqlName}' vs '${incoming.leftSqlName}').`,
310
- );
311
- }
312
-
313
- if (existing.rightSqlName !== incoming.rightSqlName) {
314
- throw new Error(
315
- `manyToMany pair '${pairKey}' has conflicting right sql name values ('${existing.rightSqlName}' vs '${incoming.rightSqlName}').`,
316
- );
317
- }
318
-
319
- if (existing.onDelete !== incoming.onDelete) {
320
- throw new Error(
321
- `manyToMany pair '${pairKey}' has conflicting onDelete values ('${existing.onDelete}' vs '${incoming.onDelete}').`,
322
- );
323
- }
324
-
325
- if (existing.onUpdate !== incoming.onUpdate) {
326
- throw new Error(
327
- `manyToMany pair '${pairKey}' has conflicting onUpdate values ('${existing.onUpdate}' vs '${incoming.onUpdate}').`,
328
- );
329
- }
330
-
331
- return existing;
332
- }
333
-
334
- function normalizeManyToManyRelations(definition: SchemaDefinition): void {
335
- const pairMap = new Map<string, ManyToManyPair>();
336
-
337
- for (const [sourceTableName, sourceTable] of Object.entries(
338
- definition.tables,
339
- )) {
340
- for (const relation of Object.values(sourceTable.relations)) {
341
- if (relation.relation !== "manyToMany") {
342
- continue;
343
- }
344
-
345
- const sourceReferenceField = relation.referenceField ?? "id";
346
- const targetReferenceField = relation.targetReferenceField ?? "id";
347
-
348
- const normalizedPair = normalizeManyToManyPairKey(
349
- sourceTableName,
350
- sourceReferenceField,
351
- relation.targetTable,
352
- targetReferenceField,
353
- );
354
-
355
- const defaultLeftField = defaultManyToManyFieldName(
356
- normalizedPair.leftTable,
357
- normalizedPair.rightTable,
358
- "source",
359
- );
360
- const defaultRightField = defaultManyToManyFieldName(
361
- normalizedPair.rightTable,
362
- normalizedPair.leftTable,
363
- "target",
364
- );
365
-
366
- const pair: ManyToManyPair = {
367
- leftTable: normalizedPair.leftTable,
368
- leftReferenceField: normalizedPair.leftReferenceField,
369
- rightTable: normalizedPair.rightTable,
370
- rightReferenceField: normalizedPair.rightReferenceField,
371
- junctionTable:
372
- relation.junctionTable ??
373
- defaultManyToManyJunctionTable(
374
- normalizedPair.leftTable,
375
- normalizedPair.rightTable,
376
- ),
377
- leftField: normalizedPair.sourceIsLeft
378
- ? (relation.sourceField ?? defaultLeftField)
379
- : (relation.targetField ?? defaultLeftField),
380
- rightField: normalizedPair.sourceIsLeft
381
- ? (relation.targetField ?? defaultRightField)
382
- : (relation.sourceField ?? defaultRightField),
383
- leftSqlName: normalizedPair.sourceIsLeft
384
- ? relation.sourceSqlName
385
- : relation.targetSqlName,
386
- rightSqlName: normalizedPair.sourceIsLeft
387
- ? relation.targetSqlName
388
- : relation.sourceSqlName,
389
- onDelete: relation.onDelete,
390
- onUpdate: relation.onUpdate,
391
- };
392
-
393
- if (pair.leftField === pair.rightField) {
394
- throw new Error(
395
- `manyToMany pair '${normalizedPair.key}' resolves to duplicate junction fields '${pair.leftField}'. Set sourceField/targetField explicitly.`,
396
- );
397
- }
398
-
399
- const existing = pairMap.get(normalizedPair.key);
400
- if (existing) {
401
- mergeManyToManyPairConfig(existing, pair, normalizedPair.key);
402
- } else {
403
- pairMap.set(normalizedPair.key, pair);
404
- }
405
-
406
- relation.referenceField = sourceReferenceField;
407
- relation.targetReferenceField = targetReferenceField;
408
- relation.junctionTable = pair.junctionTable;
409
- relation.sourceField = normalizedPair.sourceIsLeft
410
- ? pair.leftField
411
- : pair.rightField;
412
- relation.targetField = normalizedPair.sourceIsLeft
413
- ? pair.rightField
414
- : pair.leftField;
415
- relation.sourceSqlName = normalizedPair.sourceIsLeft
416
- ? pair.leftSqlName
417
- : pair.rightSqlName;
418
- relation.targetSqlName = normalizedPair.sourceIsLeft
419
- ? pair.rightSqlName
420
- : pair.leftSqlName;
421
- }
422
- }
423
-
424
- for (const pair of pairMap.values()) {
425
- if (pair.junctionTable in definition.tables) {
426
- throw new Error(
427
- `manyToMany auto junction table '${pair.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`,
428
- );
429
- }
430
-
431
- const leftType =
432
- getLocalReferenceType(
433
- definition,
434
- pair.leftTable,
435
- pair.leftReferenceField,
436
- ) ?? "string";
437
- const rightType =
438
- getLocalReferenceType(
439
- definition,
440
- pair.rightTable,
441
- pair.rightReferenceField,
442
- ) ?? "string";
443
-
444
- definition.tables[pair.junctionTable] = {
445
- kind: "table",
446
- columns: {
447
- [pair.leftField]: {
448
- kind: "column",
449
- type: leftType,
450
- sqlName: pair.leftSqlName,
451
- notNull: true,
452
- nullable: false,
453
- references: {
454
- table: pair.leftTable,
455
- column: pair.leftReferenceField,
456
- onDelete: pair.onDelete,
457
- onUpdate: pair.onUpdate,
458
- },
459
- index: true,
460
- },
461
- [pair.rightField]: {
462
- kind: "column",
463
- type: rightType,
464
- sqlName: pair.rightSqlName,
465
- notNull: true,
466
- nullable: false,
467
- references: {
468
- table: pair.rightTable,
469
- column: pair.rightReferenceField,
470
- onDelete: pair.onDelete,
471
- onUpdate: pair.onUpdate,
472
- },
473
- index: true,
474
- },
475
- },
476
- relations: {
477
- [pair.leftTable]: {
478
- kind: "relation",
479
- relation: "one",
480
- targetTable: pair.leftTable,
481
- field: pair.leftField,
482
- referenceField: pair.leftReferenceField,
483
- },
484
- [pair.rightTable]: {
485
- kind: "relation",
486
- relation: "one",
487
- targetTable: pair.rightTable,
488
- field: pair.rightField,
489
- referenceField: pair.rightReferenceField,
490
- },
491
- },
492
- };
493
- }
494
- }
495
-
496
- function validateNullableFlags(definition: SchemaDefinition): void {
497
- for (const [tableName, table] of Object.entries(definition.tables)) {
498
- for (const [columnName, column] of Object.entries(table.columns)) {
499
- if (column.notNull === true && column.nullable === true) {
500
- throw new Error(
501
- `Invalid nullable configuration on '${tableName}.${columnName}': cannot set both notNull and nullable to true.`,
502
- );
503
- }
504
- }
505
-
506
- for (const [relationName, relation] of Object.entries(table.relations)) {
507
- if (
508
- relation.relation !== "manyToMany" &&
509
- relation.notNull === true &&
510
- relation.nullable === true
511
- ) {
512
- throw new Error(
513
- `Invalid nullable configuration on '${tableName}.${relationName}': cannot set both notNull and nullable to true.`,
514
- );
515
- }
516
- }
517
- }
518
- }
519
-
520
- function normalizeSchemaDefinition(
521
- definition: SchemaDefinition,
522
- ): SchemaDefinition {
523
- validateNullableFlags(definition);
524
- const normalized = cloneSchemaDefinition(definition);
525
-
526
- for (const [tableName, table] of Object.entries(normalized.tables)) {
527
- for (const [relationName, relation] of Object.entries(table.relations)) {
528
- if (relation.relation !== "one") {
529
- continue;
530
- }
531
-
532
- const referenceField = relation.referenceField ?? "id";
533
- const inferredField = relation.field ?? `${relationName}Id`;
534
- relation.field = inferredField;
535
-
536
- const inferredType =
537
- getLocalReferenceType(
538
- normalized,
539
- relation.targetTable,
540
- referenceField,
541
- ) ??
542
- relation.fkType ??
543
- "string";
544
-
545
- ensureInferredReferenceColumn(
546
- tableName,
547
- table,
548
- inferredField,
549
- relation.targetTable,
550
- referenceField,
551
- {
552
- fkType: relation.fkType,
553
- sqlName: relation.sqlName,
554
- notNull: resolveNotNullFromNullableFlags(
555
- `${tableName}.${relationName}`,
556
- relation,
557
- true,
558
- ),
559
- onDelete: relation.onDelete,
560
- onUpdate: relation.onUpdate,
561
- },
562
- inferredType,
563
- );
564
- }
565
- }
566
-
567
- for (const [sourceTableName, sourceTable] of Object.entries(
568
- normalized.tables,
569
- )) {
570
- for (const relation of Object.values(sourceTable.relations)) {
571
- if (relation.relation !== "many") {
572
- continue;
573
- }
574
-
575
- const targetTable = normalized.tables[relation.targetTable];
576
- if (!targetTable) {
577
- continue;
578
- }
579
-
580
- const referenceField = relation.referenceField ?? "id";
581
- const inferredField =
582
- relation.field ?? `${singularize(sourceTableName)}Id`;
583
- relation.field = inferredField;
584
- const inferredType =
585
- getLocalReferenceType(normalized, sourceTableName, referenceField) ??
586
- relation.fkType ??
587
- "string";
588
-
589
- ensureInferredReferenceColumn(
590
- relation.targetTable,
591
- targetTable,
592
- inferredField,
593
- sourceTableName,
594
- referenceField,
595
- {
596
- fkType: relation.fkType,
597
- sqlName: relation.sqlName,
598
- notNull: resolveNotNullFromNullableFlags(
599
- `${sourceTableName}.${relation.targetTable}`,
600
- relation,
601
- true,
602
- ),
603
- onDelete: relation.onDelete,
604
- onUpdate: relation.onUpdate,
605
- },
606
- inferredType,
607
- );
608
- }
609
- }
610
-
611
- normalizeManyToManyRelations(normalized);
612
-
613
- return normalized;
614
- }
615
-
616
- function isOptionalInsertColumn(column: ColumnDefinition): boolean {
617
- return (
618
- column.primaryKey === true ||
619
- column.notNull !== true ||
620
- column.autoIncrement === true ||
621
- column.sqlDefault !== undefined ||
622
- column.runtimeDefaultFn !== undefined
623
- );
624
- }
625
-
626
- function isNullableSelectColumn(column: ColumnDefinition): boolean {
627
- return column.notNull !== true;
628
- }
629
-
630
- function drizzleBaseColumn(
631
- fieldName: string,
632
- column: ColumnDefinition,
633
- strategy: "camelToSnake",
634
- ): string {
635
- const resolvedSqlName = column.sqlName ?? toSnakeCase(fieldName);
636
- const needsExplicitName = resolvedSqlName !== fieldName;
637
-
638
- if (column.type === "int") {
639
- return needsExplicitName ? `t.int(${quote(resolvedSqlName)})` : "t.int()";
640
- }
641
-
642
- if (column.type === "string") {
643
- if (column.length !== undefined) {
644
- if (needsExplicitName) {
645
- return `t.text(${quote(resolvedSqlName)}, { length: ${column.length} })`;
646
- }
647
- return `t.text({ length: ${column.length} })`;
648
- }
649
-
650
- return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
651
- }
652
-
653
- if (column.type === "boolean") {
654
- if (needsExplicitName) {
655
- return `t.int(${quote(resolvedSqlName)}, { mode: "boolean" })`;
656
- }
657
- return 't.int({ mode: "boolean" })';
658
- }
659
-
660
- if (column.type === "date") {
661
- if (needsExplicitName) {
662
- return `t.int(${quote(resolvedSqlName)}, { mode: "timestamp_ms" })`;
663
- }
664
- return 't.int({ mode: "timestamp_ms" })';
665
- }
666
-
667
- if (column.type === "enum" && column.enumValues && column.enumValues.length > 0) {
668
- if (column.isArray) {
669
- return needsExplicitName
670
- ? `t.text(${quote(resolvedSqlName)}).array()`
671
- : "t.text().array()";
672
- }
673
- return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
674
- }
675
-
676
- if (column.type === "json" && column.jsonShape) {
677
- const tsType = jsonShapeToTypeScript(column.jsonShape);
678
- const base = needsExplicitName
679
- ? `t.text(${quote(resolvedSqlName)}, { mode: "json" })`
680
- : `t.text({ mode: "json" })`;
681
- return `${base}.$type<${tsType}>()`;
682
- }
683
-
684
- if (strategy === "camelToSnake") {
685
- return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
686
- }
687
-
688
- return "t.text()";
689
- }
690
-
691
- function resolveOneRelationReference(
692
- tableName: string,
693
- table: TableDefinition,
694
- relation: OneRelationDefinition,
695
- ): { sourceField: string; targetField: string } {
696
- const sourceField = relation.field;
697
- const targetField = relation.referenceField ?? "id";
698
-
699
- if (!sourceField) {
700
- throw new Error(
701
- `Relation on '${tableName}' targeting '${relation.targetTable}' is missing a local field.`,
702
- );
703
- }
704
-
705
- if (!(sourceField in table.columns)) {
706
- throw new Error(
707
- `Relation '${tableName}.${sourceField}' references missing local field '${sourceField}'.`,
708
- );
709
- }
710
-
711
- return {
712
- sourceField,
713
- targetField,
714
- };
715
- }
716
-
717
- function buildExternalTableImportLines(externals: Set<string>): string {
718
- if (externals.size === 0) {
719
- return "";
720
- }
721
- return `import { ${Array.from(externals).sort().join(", ")} } from \"./auth.schema\";\n`;
722
- }
723
-
724
- function getRelationImports(table: TableDefinition): string[] {
725
- return Object.values(table.relations)
726
- .filter((relation) => relation.relation === "one")
727
- .map((relation) => relation.targetTable);
728
- }
729
-
730
- function resolveColumnReference(
731
- fieldName: string,
732
- column: ColumnDefinition,
733
- table: TableDefinition,
734
- ): { tableName: string; fieldName: string } | undefined {
735
- if (column.references) {
736
- return {
737
- tableName: column.references.table,
738
- fieldName: column.references.column,
739
- };
740
- }
741
-
742
- const matchingOne = Object.values(table.relations).find((relation) => {
743
- return relation.relation === "one" && relation.field === fieldName;
744
- }) as OneRelationDefinition | undefined;
745
-
746
- if (!matchingOne) {
747
- return undefined;
748
- }
749
-
750
- return {
751
- tableName: matchingOne.targetTable,
752
- fieldName: matchingOne.referenceField ?? "id",
753
- };
754
- }
755
-
756
- function emitJsonColumnsMetadata(definition: SchemaDefinition): string {
757
- const tableEntries: string[] = [];
758
-
759
- for (const [tableName, table] of Object.entries(definition.tables)) {
760
- const columnEntries: string[] = [];
761
-
762
- for (const [fieldName, column] of Object.entries(table.columns)) {
763
- if (column.type !== "json" || !column.jsonShape) continue;
764
-
765
- const shapeStr = jsonShapeToRuntimeLiteral(column.jsonShape);
766
- columnEntries.push(
767
- `${quote(fieldName)}: { shape: ${shapeStr} },`,
768
- );
769
- }
770
-
771
- if (columnEntries.length === 0) continue;
772
-
773
- tableEntries.push(
774
- `${quote(tableName)}: {
775
- ${columnEntries.map((entry) => `\t\t${entry}`).join("\n")}
776
- },`,
777
- );
778
- }
779
-
780
- if (tableEntries.length === 0) {
781
- return "export const __appflareJsonColumns = {} as const;\n";
782
- }
783
-
784
- return `export const __appflareJsonColumns = {
785
- ${tableEntries.map((entry) => `\t${entry}`).join("\n")}
786
- } as const;
787
- `;
788
- }
789
-
790
- function jsonShapeToRuntimeLiteral(shape: JsonShape): string {
791
- if (shape.kind === "array") {
792
- return `{ kind: "array", element: ${jsonShapeToRuntimeLiteral(shape.element)} }`;
793
- }
794
- if (shape.kind === "object") {
795
- const fields = Object.entries(shape.shape)
796
- .map(([key, fieldShape]) => `${quote(key)}: ${jsonShapeToRuntimeLiteral(fieldShape)}`)
797
- .join(", ");
798
- return `{ kind: "object", shape: { ${fields} } }`;
799
- }
800
- return `{ kind: ${quote(shape.kind)} }`;
801
- }
802
-
803
- function emitManyToManyRuntimeMetadata(definition: SchemaDefinition): string {
804
- const tableEntries: string[] = [];
805
-
806
- for (const [tableName, table] of Object.entries(definition.tables)) {
807
- const relationEntries: string[] = [];
808
-
809
- for (const [relationName, relation] of Object.entries(table.relations)) {
810
- if (relation.relation !== "manyToMany") {
811
- continue;
812
- }
813
-
814
- if (!relation.junctionTable) {
815
- continue;
816
- }
817
-
818
- relationEntries.push(
819
- `${quote(relationName)}: {
820
- targetTable: ${quote(relation.targetTable)},
821
- junctionTable: ${quote(relation.junctionTable)},
822
- sourceField: ${quote(relation.sourceField ?? "")},
823
- targetField: ${quote(relation.targetField ?? "")},
824
- },`,
825
- );
826
- }
827
-
828
- if (relationEntries.length === 0) {
829
- continue;
830
- }
831
-
832
- tableEntries.push(
833
- `${quote(tableName)}: {
834
- ${relationEntries.map((entry) => `\t${entry}`).join("\n")}
835
- },`,
836
- );
837
- }
838
-
839
- if (tableEntries.length === 0) {
840
- return "export const __appflareManyToMany = {} as const;\n";
841
- }
842
-
843
- return `export const __appflareManyToMany = {
844
- ${tableEntries.map((entry) => `\t${entry}`).join("\n")}
845
- } as const;
846
- `;
847
- }
848
-
849
- function emitRuntimeRelationMetadata(definition: SchemaDefinition): string {
850
- const tableEntries: string[] = [];
851
-
852
- for (const [tableName, table] of Object.entries(definition.tables)) {
853
- const relationEntries: string[] = [];
854
-
855
- for (const [relationName, relation] of Object.entries(table.relations)) {
856
- if (relation.relation === "one") {
857
- relationEntries.push(
858
- `${quote(relationName)}: {
859
- kind: "one",
860
- targetTable: ${quote(relation.targetTable)},
861
- sourceField: ${quote(relation.field ?? "")},
862
- referenceField: ${quote(relation.referenceField ?? "id")},
863
- },`,
864
- );
865
- continue;
866
- }
867
-
868
- if (relation.relation === "many") {
869
- relationEntries.push(
870
- `${quote(relationName)}: {
871
- kind: "many",
872
- targetTable: ${quote(relation.targetTable)},
873
- sourceField: ${quote(relation.field ?? "")},
874
- referenceField: ${quote(relation.referenceField ?? "id")},
875
- },`,
876
- );
877
- continue;
878
- }
879
-
880
- relationEntries.push(
881
- `${quote(relationName)}: {
882
- kind: "manyToMany",
883
- targetTable: ${quote(relation.targetTable)},
884
- junctionTable: ${quote(relation.junctionTable ?? "")},
885
- sourceField: ${quote(relation.sourceField ?? "")},
886
- targetField: ${quote(relation.targetField ?? "")},
887
- referenceField: ${quote(relation.referenceField ?? "id")},
888
- targetReferenceField: ${quote(relation.targetReferenceField ?? "id")},
889
- },`,
890
- );
891
- }
892
-
893
- if (relationEntries.length === 0) {
894
- continue;
895
- }
896
-
897
- tableEntries.push(
898
- `${quote(tableName)}: {
899
- ${relationEntries.map((entry) => `\t${entry}`).join("\n")}
900
- },`,
901
- );
902
- }
903
-
904
- if (tableEntries.length === 0) {
905
- return "export const __appflareRelations = {} as const;\n";
906
- }
907
-
908
- return `export const __appflareRelations = {
909
- ${tableEntries.map((entry) => `\t${entry}`).join("\n")}
910
- } as const;
911
- `;
912
- }
913
-
914
- function emitDrizzleSchema(
915
- definition: SchemaDefinition,
916
- strategy: "camelToSnake",
917
- ): string {
918
- const localTables = new Set(Object.keys(definition.tables));
919
- const externalTables = new Set<string>();
920
-
921
- for (const table of Object.values(definition.tables)) {
922
- for (const relationTarget of getRelationImports(table)) {
923
- if (!localTables.has(relationTarget)) {
924
- externalTables.add(relationTarget);
925
- }
926
- }
927
- for (const column of Object.values(table.columns)) {
928
- if (column.references && !localTables.has(column.references.table)) {
929
- externalTables.add(column.references.table);
930
- }
931
- }
932
- }
933
-
934
- const enumColumns = new Map<string, ColumnDefinition>();
935
- for (const table of Object.values(definition.tables)) {
936
- for (const [fieldName, column] of Object.entries(table.columns)) {
937
- if (
938
- column.type === "enum" &&
939
- column.enumValues &&
940
- column.enumValues.length > 0
941
- ) {
942
- const key = column.enumRef ?? `${fieldName}`;
943
- if (!enumColumns.has(key)) {
944
- enumColumns.set(key, column);
945
- }
946
- }
947
- }
948
- }
949
-
950
- const enumTypeLines: string[] = [];
951
- const enumCustomTypeLines: string[] = [];
952
- for (const [key, column] of enumColumns.entries()) {
953
- const typeName = toPascalCase(key);
954
- const valuesStr = column.enumValues!.map((v) => `"${v}"`).join(" | ");
955
- enumTypeLines.push(`export type ${typeName} = ${valuesStr};`);
956
- enumCustomTypeLines.push(
957
- `export const ${typeName}Column = t.customType<{ data: ${typeName}; dataNotNull: ${typeName} }>({ dataType: () => "text" });`,
958
- );
959
- }
960
-
961
- const tableBlocks: string[] = [];
962
- const relationBlocks: string[] = [];
963
-
964
- for (const [tableName, table] of Object.entries(definition.tables)) {
965
- const sqlTableName = table.sqlName ?? toSnakeCase(tableName);
966
- const columnLines: string[] = [];
967
- const indexes: string[] = [];
968
-
969
- for (const [fieldName, column] of Object.entries(table.columns)) {
970
- let expr: string;
971
- if (
972
- column.type === "enum" &&
973
- column.enumValues &&
974
- column.enumValues.length > 0
975
- ) {
976
- const enumKey = column.enumRef ?? fieldName;
977
- const typeName = toPascalCase(enumKey);
978
- const resolvedSqlName = column.sqlName ?? toSnakeCase(fieldName);
979
- const needsExplicitName = resolvedSqlName !== fieldName;
980
- expr = needsExplicitName
981
- ? `${typeName}Column(${quote(resolvedSqlName)})`
982
- : `${typeName}Column()`;
983
- if (column.isArray) {
984
- expr += ".array()";
985
- }
986
- } else {
987
- expr = drizzleBaseColumn(fieldName, column, strategy);
988
- }
989
-
990
- if (column.uuidPrimaryKey) {
991
- expr += ".$defaultFn(() => crypto.randomUUID())";
992
- }
993
-
994
- if (column.primaryKey) {
995
- expr += column.autoIncrement
996
- ? ".primaryKey({ autoIncrement: true })"
997
- : ".primaryKey()";
998
- }
999
- if (column.notNull) {
1000
- expr += ".notNull()";
1001
- }
1002
- if (column.sqlDefault !== undefined) {
1003
- expr += `.default(${toSqlLiteral(column.sqlDefault)})`;
1004
- }
1005
-
1006
- const reference = resolveColumnReference(fieldName, column, table);
1007
- if (reference) {
1008
- if (column.references?.onDelete || column.references?.onUpdate) {
1009
- const actions: string[] = [];
1010
- if (column.references.onDelete) {
1011
- actions.push(`onDelete: ${quote(column.references.onDelete)}`);
1012
- }
1013
- if (column.references.onUpdate) {
1014
- actions.push(`onUpdate: ${quote(column.references.onUpdate)}`);
1015
- }
1016
- expr += `.references(() => ${reference.tableName}.${reference.fieldName}, { ${actions.join(", ")} })`;
1017
- } else {
1018
- expr += `.references(() => ${reference.tableName}.${reference.fieldName})`;
1019
- }
1020
- }
1021
-
1022
- if (column.unique) {
1023
- const uniqueName =
1024
- typeof column.unique === "object" && column.unique.name
1025
- ? column.unique.name
1026
- : `${sqlTableName}_${toSnakeCase(fieldName)}_unique_idx`;
1027
- indexes.push(
1028
- `\t\tt.uniqueIndex(${quote(uniqueName)}).on(table.${fieldName})`,
1029
- );
1030
- }
1031
-
1032
- if (column.index) {
1033
- const indexName =
1034
- typeof column.index === "object" && column.index.name
1035
- ? column.index.name
1036
- : `${sqlTableName}_${toSnakeCase(fieldName)}_idx`;
1037
- indexes.push(`\t\tt.index(${quote(indexName)}).on(table.${fieldName})`);
1038
- }
1039
-
1040
- columnLines.push(`\t\t${fieldName}: ${expr},`);
1041
- }
1042
-
1043
- if (indexes.length > 0) {
1044
- tableBlocks.push(
1045
- `export const ${tableName} = table(\n\t${quote(sqlTableName)},\n\t{\n${columnLines.join("\n")}\n\t},\n\t(table) => [\n${indexes.join(",\n")}\n\t],\n);`,
1046
- );
1047
- } else {
1048
- tableBlocks.push(
1049
- `export const ${tableName} = table(${quote(sqlTableName)}, {\n${columnLines.join("\n")}\n\t});`,
1050
- );
1051
- }
1052
-
1053
- const oneRelations = Object.entries(table.relations).filter(
1054
- ([, relation]) => {
1055
- return relation.relation === "one";
1056
- },
1057
- ) as Array<[string, OneRelationDefinition]>;
1058
- const manyRelations = Object.entries(table.relations).filter(
1059
- ([, relation]) => {
1060
- return relation.relation === "many";
1061
- },
1062
- ) as Array<[string, ManyRelationDefinition]>;
1063
- const manyToManyRelations = Object.entries(table.relations).filter(
1064
- ([, relation]) => {
1065
- return relation.relation === "manyToMany";
1066
- },
1067
- ) as Array<[string, ManyToManyRelationDefinition]>;
1068
-
1069
- if (
1070
- oneRelations.length === 0 &&
1071
- manyRelations.length === 0 &&
1072
- manyToManyRelations.length === 0
1073
- ) {
1074
- continue;
1075
- }
1076
-
1077
- const relationLines: string[] = [];
1078
- for (const [relationName, relation] of oneRelations) {
1079
- const resolved = resolveOneRelationReference(tableName, table, relation);
1080
- relationLines.push(
1081
- `\t${relationName}: one(${relation.targetTable}, {\n\t\tfields: [${tableName}.${resolved.sourceField}],\n\t\treferences: [${relation.targetTable}.${resolved.targetField}],\n\t}),`,
1082
- );
1083
- }
1084
- for (const [relationName, relation] of manyRelations) {
1085
- relationLines.push(`\t${relationName}: many(${relation.targetTable}),`);
1086
- }
1087
- for (const [relationName, relation] of manyToManyRelations) {
1088
- if (!relation.junctionTable) {
1089
- throw new Error(
1090
- `manyToMany relation '${tableName}.${relationName}' is missing junctionTable after normalization.`,
1091
- );
1092
- }
1093
- relationLines.push(`\t${relationName}: many(${relation.junctionTable}),`);
1094
- }
1095
-
1096
- relationBlocks.push(
1097
- `export const ${tableName}Relations = relations(${tableName}, ({ one, many }) => ({\n${relationLines.join("\n")}\n}));`,
1098
- );
1099
- }
1100
-
1101
- return `import * as t from "drizzle-orm/sqlite-core";
1102
- import { sqliteTable as table } from "drizzle-orm/sqlite-core";
1103
- import { relations } from "drizzle-orm";
1104
- ${buildExternalTableImportLines(externalTables)}
1105
- ${enumTypeLines.join("\n")}
1106
- ${enumCustomTypeLines.join("\n")}
1107
-
1108
- ${tableBlocks.join("\n\n")}
1109
-
1110
- ${relationBlocks.join("\n\n")}
1111
-
1112
- ${emitJsonColumnsMetadata(definition)}
1113
-
1114
- ${emitManyToManyRuntimeMetadata(definition)}
1115
-
1116
- ${emitRuntimeRelationMetadata(definition)}
1117
- `;
1118
- }
1119
-
1120
- function jsonShapeToZod(shape: JsonShape): string {
1121
- if (shape.kind === "array") {
1122
- return `z.array(${jsonShapeToZod(shape.element)})`;
1123
- }
1124
- if (shape.kind === "object") {
1125
- const fields = Object.entries(shape.shape)
1126
- .map(([key, fieldShape]) => `${quote(key)}: ${jsonShapeToZod(fieldShape)}`)
1127
- .join(", ");
1128
- return `z.object({ ${fields} })`;
1129
- }
1130
- if (shape.kind === "string") return "z.string()";
1131
- if (shape.kind === "number") return "z.number()";
1132
- if (shape.kind === "boolean") return "z.boolean()";
1133
- if (shape.kind === "date") return "z.date()";
1134
- return "z.unknown()";
1135
- }
1136
-
1137
- function zodSchemaExpression(
1138
- column: ColumnDefinition,
1139
- optional: boolean,
1140
- nullable: boolean,
1141
- ): string {
1142
- let expr = "z.unknown()";
1143
- if (column.type === "int") {
1144
- expr = "z.number().int()";
1145
- } else if (column.type === "string") {
1146
- expr = "z.string()";
1147
- if (column.length !== undefined) {
1148
- expr += `.max(${column.length})`;
1149
- }
1150
- } else if (column.type === "boolean") {
1151
- expr = "z.boolean()";
1152
- } else if (column.type === "date") {
1153
- expr = "z.date()";
1154
- } else if (column.type === "enum" && column.enumValues && column.enumValues.length > 0) {
1155
- const valuesStr = column.enumValues.map((v) => `"${v}"`).join(", ");
1156
- const enumZod = `z.enum([${valuesStr}])`;
1157
- expr = column.isArray ? `z.array(${enumZod})` : enumZod;
1158
- } else if (column.type === "json" && column.jsonShape) {
1159
- expr = jsonShapeToZod(column.jsonShape);
1160
- }
1161
-
1162
- if (optional) {
1163
- expr += ".optional()";
1164
- }
1165
-
1166
- if (nullable) {
1167
- expr += ".nullable()";
1168
- }
1169
-
1170
- return expr;
1171
- }
1172
-
1173
- function emitZodSchemas(definition: SchemaDefinition): string {
1174
- const blocks: string[] = [];
1175
-
1176
- for (const [tableName, table] of Object.entries(definition.tables)) {
1177
- const pascal = toPascalCase(tableName);
1178
- const insertLines: string[] = [];
1179
- const selectLines: string[] = [];
1180
-
1181
- for (const [fieldName, column] of Object.entries(table.columns)) {
1182
- insertLines.push(
1183
- `\t${fieldName}: ${zodSchemaExpression(column, isOptionalInsertColumn(column), isNullableSelectColumn(column))},`,
1184
- );
1185
- selectLines.push(
1186
- `\t${fieldName}: ${zodSchemaExpression(column, isNullableSelectColumn(column), isNullableSelectColumn(column))},`,
1187
- );
1188
- }
1189
-
1190
- blocks.push(`export const ${tableName}InsertSchema = z.object({\n${insertLines.join("\n")}\n});
1191
- export const ${tableName}SelectSchema = z.object({\n${selectLines.join("\n")}\n});
1192
-
1193
- export type ${pascal}Insert = z.infer<typeof ${tableName}InsertSchema>;
1194
- export type ${pascal}Select = z.infer<typeof ${tableName}SelectSchema>;
1195
- `);
1196
- }
1197
-
1198
- return `import { z } from "zod";
1199
-
1200
- ${blocks.join("\n")}`;
1201
- }
1202
-
1203
- function jsonShapeToTypeScript(shape: JsonShape): string {
1204
- if (shape.kind === "array") {
1205
- return `Array<${jsonShapeToTypeScript(shape.element)}>`;
1206
- }
1207
- if (shape.kind === "object") {
1208
- const fields = Object.entries(shape.shape)
1209
- .map(([key, fieldShape]) => `${key}: ${jsonShapeToTypeScript(fieldShape)}`)
1210
- .join("; ");
1211
- return `{ ${fields} }`;
1212
- }
1213
- if (shape.kind === "string") return "string";
1214
- if (shape.kind === "number") return "number";
1215
- if (shape.kind === "boolean") return "boolean";
1216
- if (shape.kind === "date") return "Date";
1217
- return "unknown";
1218
- }
1219
-
1220
- function toTypeScriptType(column: ColumnDefinition): string {
1221
- if (column.type === "int") {
1222
- return "number";
1223
- }
1224
- if (column.type === "string") {
1225
- return "string";
1226
- }
1227
- if (column.type === "boolean") {
1228
- return "boolean";
1229
- }
1230
- if (column.type === "date") {
1231
- return "Date";
1232
- }
1233
- if (column.type === "enum" && column.enumValues && column.enumValues.length > 0) {
1234
- const union = column.enumValues.map((v) => `"${v}"`).join(" | ");
1235
- if (column.isArray) {
1236
- return `Array<${union}>`;
1237
- }
1238
- return union;
1239
- }
1240
- if (column.type === "json" && column.jsonShape) {
1241
- return jsonShapeToTypeScript(column.jsonShape);
1242
- }
1243
- return "unknown";
1244
- }
1245
-
1246
- function emitTypes(definition: SchemaDefinition): string {
1247
- const enumTypeLines: string[] = [];
1248
- for (const [name, enumDef] of Object.entries(definition.enums ?? {})) {
1249
- const typeName = toPascalCase(name);
1250
- const valuesStr = enumDef.values.map((v) => `"${v}"`).join(" | ");
1251
- enumTypeLines.push(`export type ${typeName} = ${valuesStr};`);
1252
- }
1253
-
1254
- const lines: string[] = [];
1255
-
1256
- for (const [tableName, table] of Object.entries(definition.tables)) {
1257
- const pascal = toPascalCase(tableName);
1258
- const selectFields: string[] = [];
1259
- const insertFields: string[] = [];
1260
-
1261
- for (const [fieldName, column] of Object.entries(table.columns)) {
1262
- const tsType = toTypeScriptType(column);
1263
- const nullableSuffix = isNullableSelectColumn(column) ? " | null" : "";
1264
- selectFields.push(
1265
- `\t${fieldName}${isNullableSelectColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
1266
- );
1267
- insertFields.push(
1268
- `\t${fieldName}${isOptionalInsertColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
1269
- );
1270
- }
1271
-
1272
- lines.push(`export type ${pascal} = {\n${selectFields.join("\n")}\n};
1273
-
1274
- export type New${pascal} = {\n${insertFields.join("\n")}\n};`);
1275
- }
1276
-
1277
- return `${enumTypeLines.join("\n")}
1278
- ${lines.join("\n\n")}
1279
- `;
1280
- }
1281
-
1282
- function findSchemaExport(
1283
- moduleExports: Record<string, unknown>,
1284
- exportName?: string,
1285
- ): SchemaDefinition {
1286
- if (exportName) {
1287
- const explicit = moduleExports[exportName];
1288
- if (!isSchemaDefinition(explicit)) {
1289
- throw new Error(
1290
- `schemaDsl.exportName '${exportName}' does not point to a schema() export.`,
1291
- );
1292
- }
1293
- return explicit;
1294
- }
1295
-
1296
- for (const candidate of Object.values(moduleExports)) {
1297
- if (isSchemaDefinition(candidate)) {
1298
- return candidate;
1299
- }
1300
- }
1301
-
1302
- throw new Error(
1303
- "No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.",
1304
- );
1305
- }
1306
-
1307
- export async function compileSchemaDsl(
1308
- loadedConfig: LoadedAppflareConfig,
1309
- ): Promise<CompiledSchemaArtifacts | undefined> {
1310
- const schemaDsl = loadedConfig.config.schemaDsl;
1311
- if (!schemaDsl) {
1312
- return undefined;
1313
- }
1314
-
1315
- const namingStrategy = schemaDsl.namingStrategy ?? "camelToSnake";
1316
- const entryPath = resolve(loadedConfig.configDir, schemaDsl.entry);
1317
- const outSchemaPath = resolve(
1318
- loadedConfig.configDir,
1319
- schemaDsl.outFile ?? resolve(loadedConfig.outDirAbs, "schema.compiled.ts"),
1320
- );
1321
- const outTypesPath = resolve(
1322
- loadedConfig.configDir,
1323
- schemaDsl.typesOutFile ??
1324
- resolve(loadedConfig.outDirAbs, "schema.types.ts"),
1325
- );
1326
- const outZodPath = resolve(
1327
- loadedConfig.configDir,
1328
- schemaDsl.zodOutFile ?? resolve(loadedConfig.outDirAbs, "schema.zod.ts"),
1329
- );
1330
-
1331
- const moduleUrl = `${pathToFileURL(entryPath).href}?t=${Date.now()}`;
1332
- const schemaModule = (await import(moduleUrl)) as Record<string, unknown>;
1333
- const schemaDefinition = findSchemaExport(schemaModule, schemaDsl.exportName);
1334
- const normalizedSchema = normalizeSchemaDefinition(schemaDefinition);
1335
-
1336
- await Promise.all([
1337
- mkdir(dirname(outSchemaPath), { recursive: true }),
1338
- mkdir(dirname(outTypesPath), { recursive: true }),
1339
- mkdir(dirname(outZodPath), { recursive: true }),
1340
- ]);
1341
-
1342
- const drizzleSchemaSource = emitDrizzleSchema(
1343
- normalizedSchema,
1344
- namingStrategy,
1345
- );
1346
- const typesSource = emitTypes(normalizedSchema);
1347
- const zodSource = emitZodSchemas(normalizedSchema);
1348
-
1349
- await Promise.all([
1350
- Bun.write(outSchemaPath, drizzleSchemaSource),
1351
- Bun.write(outTypesPath, typesSource),
1352
- Bun.write(outZodPath, zodSource),
1353
- ]);
1354
-
1355
- return {
1356
- schemaPath: outSchemaPath,
1357
- typesPath: outTypesPath,
1358
- zodPath: outZodPath,
1359
- tableNames: Object.keys(normalizedSchema.tables),
1360
- };
1361
- }
1
+ import { mkdir } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import type {
5
+ ColumnDefinition,
6
+ ColumnType,
7
+ JsonShape,
8
+ ManyRelationDefinition,
9
+ ManyToManyRelationDefinition,
10
+ OneRelationDefinition,
11
+ SchemaDefinition,
12
+ TableDefinition,
13
+ } from "../schema";
14
+ import { isSchemaDefinition } from "../schema";
15
+ import type { LoadedAppflareConfig } from "./types";
16
+
17
+ export type CompiledSchemaArtifacts = {
18
+ schemaPath: string;
19
+ typesPath: string;
20
+ zodPath: string;
21
+ tableNames: string[];
22
+ };
23
+
24
+ function toSnakeCase(value: string): string {
25
+ return value
26
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
27
+ .replace(/[\s-]+/g, "_")
28
+ .toLowerCase();
29
+ }
30
+
31
+ function toPascalCase(value: string): string {
32
+ return value
33
+ .replace(/[_-]+/g, " ")
34
+ .replace(/\s+(.)/g, (_match, char: string) => char.toUpperCase())
35
+ .replace(/\s/g, "")
36
+ .replace(/^(.)/, (_match, char: string) => char.toUpperCase());
37
+ }
38
+
39
+ function singularize(value: string): string {
40
+ if (value.endsWith("ies")) {
41
+ return `${value.slice(0, -3)}y`;
42
+ }
43
+ if (value.endsWith("ses")) {
44
+ return value.slice(0, -2);
45
+ }
46
+ if (value.endsWith("s") && value.length > 1) {
47
+ return value.slice(0, -1);
48
+ }
49
+ return value;
50
+ }
51
+
52
+ function quote(value: string): string {
53
+ return JSON.stringify(value);
54
+ }
55
+
56
+ function toSqlLiteral(value: unknown): string {
57
+ if (typeof value === "string") {
58
+ return quote(value);
59
+ }
60
+ if (typeof value === "number" || typeof value === "boolean") {
61
+ return String(value);
62
+ }
63
+ if (value === null) {
64
+ return "null";
65
+ }
66
+ if (value instanceof Date) {
67
+ return quote(value.toISOString());
68
+ }
69
+ throw new Error(
70
+ `Unsupported SQL default value '${String(value)}'. Use string, number, boolean, null, or Date.`,
71
+ );
72
+ }
73
+
74
+ function cloneSchemaDefinition(definition: SchemaDefinition): SchemaDefinition {
75
+ return {
76
+ kind: "schema",
77
+ tables: Object.fromEntries(
78
+ Object.entries(definition.tables).map(([tableName, table]) => {
79
+ return [
80
+ tableName,
81
+ {
82
+ kind: "table",
83
+ sqlName: table.sqlName,
84
+ columns: Object.fromEntries(
85
+ Object.entries(table.columns).map(([columnName, column]) => {
86
+ return [columnName, { ...column }];
87
+ }),
88
+ ),
89
+ relations: Object.fromEntries(
90
+ Object.entries(table.relations).map(
91
+ ([relationName, relation]) => {
92
+ return [relationName, { ...relation }];
93
+ },
94
+ ),
95
+ ),
96
+ } satisfies TableDefinition,
97
+ ];
98
+ }),
99
+ ),
100
+ enums: Object.fromEntries(
101
+ Object.entries(definition.enums ?? {}).map(([name, enumDef]) => {
102
+ return [name, { ...enumDef }];
103
+ }),
104
+ ),
105
+ };
106
+ }
107
+
108
+ function getLocalReferenceType(
109
+ definition: SchemaDefinition,
110
+ targetTable: string,
111
+ referenceField: string,
112
+ ): ColumnType | undefined {
113
+ const table = definition.tables[targetTable];
114
+ if (!table) {
115
+ return undefined;
116
+ }
117
+ const targetColumn = table.columns[referenceField];
118
+ return targetColumn?.type;
119
+ }
120
+
121
+ function ensureInferredReferenceColumn(
122
+ tableName: string,
123
+ table: TableDefinition,
124
+ columnName: string,
125
+ referenceTable: string,
126
+ referenceField: string,
127
+ options: {
128
+ fkType?: ColumnType;
129
+ sqlName?: string;
130
+ notNull?: boolean;
131
+ onDelete?: OneRelationDefinition["onDelete"];
132
+ onUpdate?: OneRelationDefinition["onUpdate"];
133
+ },
134
+ inferredType: ColumnType,
135
+ ): void {
136
+ const existing = table.columns[columnName];
137
+ if (existing) {
138
+ if (
139
+ existing.references &&
140
+ (existing.references.table !== referenceTable ||
141
+ existing.references.column !== referenceField)
142
+ ) {
143
+ throw new Error(
144
+ `Inferred relation '${tableName}.${columnName}' conflicts with explicit references(${existing.references.table}.${existing.references.column}).`,
145
+ );
146
+ }
147
+
148
+ table.columns[columnName] = {
149
+ ...existing,
150
+ notNull:
151
+ existing.notNull ??
152
+ (existing.nullable === true ? false : options.notNull),
153
+ nullable:
154
+ existing.nullable ?? (options.notNull === false ? true : undefined),
155
+ references: {
156
+ table: referenceTable,
157
+ column: referenceField,
158
+ onDelete: existing.references?.onDelete ?? options.onDelete,
159
+ onUpdate: existing.references?.onUpdate ?? options.onUpdate,
160
+ },
161
+ };
162
+ return;
163
+ }
164
+
165
+ table.columns[columnName] = {
166
+ kind: "column",
167
+ type: options.fkType ?? inferredType,
168
+ sqlName: options.sqlName,
169
+ notNull: options.notNull ?? true,
170
+ nullable: options.notNull === false ? true : undefined,
171
+ references: {
172
+ table: referenceTable,
173
+ column: referenceField,
174
+ onDelete: options.onDelete,
175
+ onUpdate: options.onUpdate,
176
+ },
177
+ };
178
+ }
179
+
180
+ function resolveNotNullFromNullableFlags(
181
+ fieldPath: string,
182
+ flags: { notNull?: boolean; nullable?: boolean },
183
+ defaultNotNull: boolean,
184
+ ): boolean {
185
+ if (flags.notNull === true && flags.nullable === true) {
186
+ throw new Error(
187
+ `Invalid nullable configuration on '${fieldPath}': cannot set both notNull and nullable to true.`,
188
+ );
189
+ }
190
+
191
+ if (flags.notNull === true) {
192
+ return true;
193
+ }
194
+
195
+ if (flags.nullable === true) {
196
+ return false;
197
+ }
198
+
199
+ if (flags.notNull === false) {
200
+ return false;
201
+ }
202
+
203
+ return defaultNotNull;
204
+ }
205
+
206
+ type ManyToManyPair = {
207
+ leftTable: string;
208
+ leftReferenceField: string;
209
+ rightTable: string;
210
+ rightReferenceField: string;
211
+ junctionTable: string;
212
+ leftField: string;
213
+ rightField: string;
214
+ leftSqlName?: string;
215
+ rightSqlName?: string;
216
+ onDelete?: OneRelationDefinition["onDelete"];
217
+ onUpdate?: OneRelationDefinition["onUpdate"];
218
+ };
219
+
220
+ function endpointKey(tableName: string, referenceField: string): string {
221
+ return `${tableName}:${referenceField}`;
222
+ }
223
+
224
+ function normalizeManyToManyPairKey(
225
+ sourceTable: string,
226
+ sourceReferenceField: string,
227
+ targetTable: string,
228
+ targetReferenceField: string,
229
+ ): {
230
+ key: string;
231
+ leftTable: string;
232
+ leftReferenceField: string;
233
+ rightTable: string;
234
+ rightReferenceField: string;
235
+ sourceIsLeft: boolean;
236
+ } {
237
+ const source = endpointKey(sourceTable, sourceReferenceField);
238
+ const target = endpointKey(targetTable, targetReferenceField);
239
+ const sourceIsLeft = source <= target;
240
+
241
+ if (sourceIsLeft) {
242
+ return {
243
+ key: `${source}|${target}`,
244
+ leftTable: sourceTable,
245
+ leftReferenceField: sourceReferenceField,
246
+ rightTable: targetTable,
247
+ rightReferenceField: targetReferenceField,
248
+ sourceIsLeft: true,
249
+ };
250
+ }
251
+
252
+ return {
253
+ key: `${target}|${source}`,
254
+ leftTable: targetTable,
255
+ leftReferenceField: targetReferenceField,
256
+ rightTable: sourceTable,
257
+ rightReferenceField: sourceReferenceField,
258
+ sourceIsLeft: false,
259
+ };
260
+ }
261
+
262
+ function defaultManyToManyJunctionTable(
263
+ leftTable: string,
264
+ rightTable: string,
265
+ ): string {
266
+ return `${leftTable}${toPascalCase(rightTable)}Links`;
267
+ }
268
+
269
+ function defaultManyToManyFieldName(
270
+ ownerTable: string,
271
+ otherTable: string,
272
+ suffix: "source" | "target",
273
+ ): string {
274
+ const ownerSingular = singularize(ownerTable);
275
+ const otherSingular = singularize(otherTable);
276
+
277
+ if (ownerSingular === otherSingular) {
278
+ return `${suffix}${toPascalCase(ownerSingular)}Id`;
279
+ }
280
+
281
+ return `${ownerSingular}Id`;
282
+ }
283
+
284
+ function mergeManyToManyPairConfig(
285
+ existing: ManyToManyPair,
286
+ incoming: ManyToManyPair,
287
+ pairKey: string,
288
+ ): ManyToManyPair {
289
+ if (existing.junctionTable !== incoming.junctionTable) {
290
+ throw new Error(
291
+ `manyToMany pair '${pairKey}' has conflicting junctionTable values ('${existing.junctionTable}' vs '${incoming.junctionTable}').`,
292
+ );
293
+ }
294
+
295
+ if (existing.leftField !== incoming.leftField) {
296
+ throw new Error(
297
+ `manyToMany pair '${pairKey}' has conflicting left field values ('${existing.leftField}' vs '${incoming.leftField}').`,
298
+ );
299
+ }
300
+
301
+ if (existing.rightField !== incoming.rightField) {
302
+ throw new Error(
303
+ `manyToMany pair '${pairKey}' has conflicting right field values ('${existing.rightField}' vs '${incoming.rightField}').`,
304
+ );
305
+ }
306
+
307
+ if (existing.leftSqlName !== incoming.leftSqlName) {
308
+ throw new Error(
309
+ `manyToMany pair '${pairKey}' has conflicting left sql name values ('${existing.leftSqlName}' vs '${incoming.leftSqlName}').`,
310
+ );
311
+ }
312
+
313
+ if (existing.rightSqlName !== incoming.rightSqlName) {
314
+ throw new Error(
315
+ `manyToMany pair '${pairKey}' has conflicting right sql name values ('${existing.rightSqlName}' vs '${incoming.rightSqlName}').`,
316
+ );
317
+ }
318
+
319
+ if (existing.onDelete !== incoming.onDelete) {
320
+ throw new Error(
321
+ `manyToMany pair '${pairKey}' has conflicting onDelete values ('${existing.onDelete}' vs '${incoming.onDelete}').`,
322
+ );
323
+ }
324
+
325
+ if (existing.onUpdate !== incoming.onUpdate) {
326
+ throw new Error(
327
+ `manyToMany pair '${pairKey}' has conflicting onUpdate values ('${existing.onUpdate}' vs '${incoming.onUpdate}').`,
328
+ );
329
+ }
330
+
331
+ return existing;
332
+ }
333
+
334
+ function normalizeManyToManyRelations(definition: SchemaDefinition): void {
335
+ const pairMap = new Map<string, ManyToManyPair>();
336
+
337
+ for (const [sourceTableName, sourceTable] of Object.entries(
338
+ definition.tables,
339
+ )) {
340
+ for (const relation of Object.values(sourceTable.relations)) {
341
+ if (relation.relation !== "manyToMany") {
342
+ continue;
343
+ }
344
+
345
+ const sourceReferenceField = relation.referenceField ?? "id";
346
+ const targetReferenceField = relation.targetReferenceField ?? "id";
347
+
348
+ const normalizedPair = normalizeManyToManyPairKey(
349
+ sourceTableName,
350
+ sourceReferenceField,
351
+ relation.targetTable,
352
+ targetReferenceField,
353
+ );
354
+
355
+ const defaultLeftField = defaultManyToManyFieldName(
356
+ normalizedPair.leftTable,
357
+ normalizedPair.rightTable,
358
+ "source",
359
+ );
360
+ const defaultRightField = defaultManyToManyFieldName(
361
+ normalizedPair.rightTable,
362
+ normalizedPair.leftTable,
363
+ "target",
364
+ );
365
+
366
+ const pair: ManyToManyPair = {
367
+ leftTable: normalizedPair.leftTable,
368
+ leftReferenceField: normalizedPair.leftReferenceField,
369
+ rightTable: normalizedPair.rightTable,
370
+ rightReferenceField: normalizedPair.rightReferenceField,
371
+ junctionTable:
372
+ relation.junctionTable ??
373
+ defaultManyToManyJunctionTable(
374
+ normalizedPair.leftTable,
375
+ normalizedPair.rightTable,
376
+ ),
377
+ leftField: normalizedPair.sourceIsLeft
378
+ ? (relation.sourceField ?? defaultLeftField)
379
+ : (relation.targetField ?? defaultLeftField),
380
+ rightField: normalizedPair.sourceIsLeft
381
+ ? (relation.targetField ?? defaultRightField)
382
+ : (relation.sourceField ?? defaultRightField),
383
+ leftSqlName: normalizedPair.sourceIsLeft
384
+ ? relation.sourceSqlName
385
+ : relation.targetSqlName,
386
+ rightSqlName: normalizedPair.sourceIsLeft
387
+ ? relation.targetSqlName
388
+ : relation.sourceSqlName,
389
+ onDelete: relation.onDelete,
390
+ onUpdate: relation.onUpdate,
391
+ };
392
+
393
+ if (pair.leftField === pair.rightField) {
394
+ throw new Error(
395
+ `manyToMany pair '${normalizedPair.key}' resolves to duplicate junction fields '${pair.leftField}'. Set sourceField/targetField explicitly.`,
396
+ );
397
+ }
398
+
399
+ const existing = pairMap.get(normalizedPair.key);
400
+ if (existing) {
401
+ mergeManyToManyPairConfig(existing, pair, normalizedPair.key);
402
+ } else {
403
+ pairMap.set(normalizedPair.key, pair);
404
+ }
405
+
406
+ relation.referenceField = sourceReferenceField;
407
+ relation.targetReferenceField = targetReferenceField;
408
+ relation.junctionTable = pair.junctionTable;
409
+ relation.sourceField = normalizedPair.sourceIsLeft
410
+ ? pair.leftField
411
+ : pair.rightField;
412
+ relation.targetField = normalizedPair.sourceIsLeft
413
+ ? pair.rightField
414
+ : pair.leftField;
415
+ relation.sourceSqlName = normalizedPair.sourceIsLeft
416
+ ? pair.leftSqlName
417
+ : pair.rightSqlName;
418
+ relation.targetSqlName = normalizedPair.sourceIsLeft
419
+ ? pair.rightSqlName
420
+ : pair.leftSqlName;
421
+ }
422
+ }
423
+
424
+ for (const pair of pairMap.values()) {
425
+ if (pair.junctionTable in definition.tables) {
426
+ throw new Error(
427
+ `manyToMany auto junction table '${pair.junctionTable}' conflicts with an existing table. Set a different junctionTable name.`,
428
+ );
429
+ }
430
+
431
+ const leftType =
432
+ getLocalReferenceType(
433
+ definition,
434
+ pair.leftTable,
435
+ pair.leftReferenceField,
436
+ ) ?? "string";
437
+ const rightType =
438
+ getLocalReferenceType(
439
+ definition,
440
+ pair.rightTable,
441
+ pair.rightReferenceField,
442
+ ) ?? "string";
443
+
444
+ definition.tables[pair.junctionTable] = {
445
+ kind: "table",
446
+ columns: {
447
+ [pair.leftField]: {
448
+ kind: "column",
449
+ type: leftType,
450
+ sqlName: pair.leftSqlName,
451
+ notNull: true,
452
+ nullable: false,
453
+ references: {
454
+ table: pair.leftTable,
455
+ column: pair.leftReferenceField,
456
+ onDelete: pair.onDelete,
457
+ onUpdate: pair.onUpdate,
458
+ },
459
+ index: true,
460
+ },
461
+ [pair.rightField]: {
462
+ kind: "column",
463
+ type: rightType,
464
+ sqlName: pair.rightSqlName,
465
+ notNull: true,
466
+ nullable: false,
467
+ references: {
468
+ table: pair.rightTable,
469
+ column: pair.rightReferenceField,
470
+ onDelete: pair.onDelete,
471
+ onUpdate: pair.onUpdate,
472
+ },
473
+ index: true,
474
+ },
475
+ },
476
+ relations: {
477
+ [pair.leftTable]: {
478
+ kind: "relation",
479
+ relation: "one",
480
+ targetTable: pair.leftTable,
481
+ field: pair.leftField,
482
+ referenceField: pair.leftReferenceField,
483
+ },
484
+ [pair.rightTable]: {
485
+ kind: "relation",
486
+ relation: "one",
487
+ targetTable: pair.rightTable,
488
+ field: pair.rightField,
489
+ referenceField: pair.rightReferenceField,
490
+ },
491
+ },
492
+ };
493
+ }
494
+ }
495
+
496
+ function validateNullableFlags(definition: SchemaDefinition): void {
497
+ for (const [tableName, table] of Object.entries(definition.tables)) {
498
+ for (const [columnName, column] of Object.entries(table.columns)) {
499
+ if (column.notNull === true && column.nullable === true) {
500
+ throw new Error(
501
+ `Invalid nullable configuration on '${tableName}.${columnName}': cannot set both notNull and nullable to true.`,
502
+ );
503
+ }
504
+ }
505
+
506
+ for (const [relationName, relation] of Object.entries(table.relations)) {
507
+ if (
508
+ relation.relation !== "manyToMany" &&
509
+ relation.notNull === true &&
510
+ relation.nullable === true
511
+ ) {
512
+ throw new Error(
513
+ `Invalid nullable configuration on '${tableName}.${relationName}': cannot set both notNull and nullable to true.`,
514
+ );
515
+ }
516
+ }
517
+ }
518
+ }
519
+
520
+ function normalizeSchemaDefinition(
521
+ definition: SchemaDefinition,
522
+ ): SchemaDefinition {
523
+ validateNullableFlags(definition);
524
+ const normalized = cloneSchemaDefinition(definition);
525
+
526
+ for (const [tableName, table] of Object.entries(normalized.tables)) {
527
+ for (const [relationName, relation] of Object.entries(table.relations)) {
528
+ if (relation.relation !== "one") {
529
+ continue;
530
+ }
531
+
532
+ const referenceField = relation.referenceField ?? "id";
533
+ const inferredField = relation.field ?? `${relationName}Id`;
534
+ relation.field = inferredField;
535
+
536
+ const inferredType =
537
+ getLocalReferenceType(
538
+ normalized,
539
+ relation.targetTable,
540
+ referenceField,
541
+ ) ??
542
+ relation.fkType ??
543
+ "string";
544
+
545
+ ensureInferredReferenceColumn(
546
+ tableName,
547
+ table,
548
+ inferredField,
549
+ relation.targetTable,
550
+ referenceField,
551
+ {
552
+ fkType: relation.fkType,
553
+ sqlName: relation.sqlName,
554
+ notNull: resolveNotNullFromNullableFlags(
555
+ `${tableName}.${relationName}`,
556
+ relation,
557
+ true,
558
+ ),
559
+ onDelete: relation.onDelete,
560
+ onUpdate: relation.onUpdate,
561
+ },
562
+ inferredType,
563
+ );
564
+ }
565
+ }
566
+
567
+ for (const [sourceTableName, sourceTable] of Object.entries(
568
+ normalized.tables,
569
+ )) {
570
+ for (const relation of Object.values(sourceTable.relations)) {
571
+ if (relation.relation !== "many") {
572
+ continue;
573
+ }
574
+
575
+ const targetTable = normalized.tables[relation.targetTable];
576
+ if (!targetTable) {
577
+ continue;
578
+ }
579
+
580
+ const referenceField = relation.referenceField ?? "id";
581
+ const inferredField =
582
+ relation.field ?? `${singularize(sourceTableName)}Id`;
583
+ relation.field = inferredField;
584
+ const inferredType =
585
+ getLocalReferenceType(normalized, sourceTableName, referenceField) ??
586
+ relation.fkType ??
587
+ "string";
588
+
589
+ ensureInferredReferenceColumn(
590
+ relation.targetTable,
591
+ targetTable,
592
+ inferredField,
593
+ sourceTableName,
594
+ referenceField,
595
+ {
596
+ fkType: relation.fkType,
597
+ sqlName: relation.sqlName,
598
+ notNull: resolveNotNullFromNullableFlags(
599
+ `${sourceTableName}.${relation.targetTable}`,
600
+ relation,
601
+ true,
602
+ ),
603
+ onDelete: relation.onDelete,
604
+ onUpdate: relation.onUpdate,
605
+ },
606
+ inferredType,
607
+ );
608
+ }
609
+ }
610
+
611
+ normalizeManyToManyRelations(normalized);
612
+
613
+ return normalized;
614
+ }
615
+
616
+ function isOptionalInsertColumn(column: ColumnDefinition): boolean {
617
+ return (
618
+ column.primaryKey === true ||
619
+ column.notNull !== true ||
620
+ column.autoIncrement === true ||
621
+ column.sqlDefault !== undefined ||
622
+ column.runtimeDefaultFn !== undefined
623
+ );
624
+ }
625
+
626
+ function isNullableSelectColumn(column: ColumnDefinition): boolean {
627
+ return column.notNull !== true;
628
+ }
629
+
630
+ function drizzleBaseColumn(
631
+ fieldName: string,
632
+ column: ColumnDefinition,
633
+ strategy: "camelToSnake",
634
+ ): string {
635
+ const resolvedSqlName = column.sqlName ?? toSnakeCase(fieldName);
636
+ const needsExplicitName = resolvedSqlName !== fieldName;
637
+
638
+ if (column.type === "int") {
639
+ return needsExplicitName ? `t.int(${quote(resolvedSqlName)})` : "t.int()";
640
+ }
641
+
642
+ if (column.type === "string") {
643
+ if (column.length !== undefined) {
644
+ if (needsExplicitName) {
645
+ return `t.text(${quote(resolvedSqlName)}, { length: ${column.length} })`;
646
+ }
647
+ return `t.text({ length: ${column.length} })`;
648
+ }
649
+
650
+ return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
651
+ }
652
+
653
+ if (column.type === "boolean") {
654
+ if (needsExplicitName) {
655
+ return `t.int(${quote(resolvedSqlName)}, { mode: "boolean" })`;
656
+ }
657
+ return 't.int({ mode: "boolean" })';
658
+ }
659
+
660
+ if (column.type === "date") {
661
+ if (needsExplicitName) {
662
+ return `t.int(${quote(resolvedSqlName)}, { mode: "timestamp_ms" })`;
663
+ }
664
+ return 't.int({ mode: "timestamp_ms" })';
665
+ }
666
+
667
+ if (column.type === "enum" && column.enumValues && column.enumValues.length > 0) {
668
+ if (column.isArray) {
669
+ return needsExplicitName
670
+ ? `t.text(${quote(resolvedSqlName)}).array()`
671
+ : "t.text().array()";
672
+ }
673
+ return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
674
+ }
675
+
676
+ if (column.type === "json" && column.jsonShape) {
677
+ const tsType = jsonShapeToTypeScript(column.jsonShape);
678
+ const base = needsExplicitName
679
+ ? `t.text(${quote(resolvedSqlName)}, { mode: "json" })`
680
+ : `t.text({ mode: "json" })`;
681
+ return `${base}.$type<${tsType}>()`;
682
+ }
683
+
684
+ if (strategy === "camelToSnake") {
685
+ return needsExplicitName ? `t.text(${quote(resolvedSqlName)})` : "t.text()";
686
+ }
687
+
688
+ return "t.text()";
689
+ }
690
+
691
+ function resolveOneRelationReference(
692
+ tableName: string,
693
+ table: TableDefinition,
694
+ relation: OneRelationDefinition,
695
+ ): { sourceField: string; targetField: string } {
696
+ const sourceField = relation.field;
697
+ const targetField = relation.referenceField ?? "id";
698
+
699
+ if (!sourceField) {
700
+ throw new Error(
701
+ `Relation on '${tableName}' targeting '${relation.targetTable}' is missing a local field.`,
702
+ );
703
+ }
704
+
705
+ if (!(sourceField in table.columns)) {
706
+ throw new Error(
707
+ `Relation '${tableName}.${sourceField}' references missing local field '${sourceField}'.`,
708
+ );
709
+ }
710
+
711
+ return {
712
+ sourceField,
713
+ targetField,
714
+ };
715
+ }
716
+
717
+ function buildExternalTableImportLines(externals: Set<string>): string {
718
+ if (externals.size === 0) {
719
+ return "";
720
+ }
721
+ return `import { ${Array.from(externals).sort().join(", ")} } from \"./auth.schema\";\n`;
722
+ }
723
+
724
+ function getRelationImports(table: TableDefinition): string[] {
725
+ return Object.values(table.relations)
726
+ .filter((relation) => relation.relation === "one")
727
+ .map((relation) => relation.targetTable);
728
+ }
729
+
730
+ function resolveColumnReference(
731
+ fieldName: string,
732
+ column: ColumnDefinition,
733
+ table: TableDefinition,
734
+ ): { tableName: string; fieldName: string } | undefined {
735
+ if (column.references) {
736
+ return {
737
+ tableName: column.references.table,
738
+ fieldName: column.references.column,
739
+ };
740
+ }
741
+
742
+ const matchingOne = Object.values(table.relations).find((relation) => {
743
+ return relation.relation === "one" && relation.field === fieldName;
744
+ }) as OneRelationDefinition | undefined;
745
+
746
+ if (!matchingOne) {
747
+ return undefined;
748
+ }
749
+
750
+ return {
751
+ tableName: matchingOne.targetTable,
752
+ fieldName: matchingOne.referenceField ?? "id",
753
+ };
754
+ }
755
+
756
+ function emitJsonColumnsMetadata(definition: SchemaDefinition): string {
757
+ const tableEntries: string[] = [];
758
+
759
+ for (const [tableName, table] of Object.entries(definition.tables)) {
760
+ const columnEntries: string[] = [];
761
+
762
+ for (const [fieldName, column] of Object.entries(table.columns)) {
763
+ if (column.type !== "json" || !column.jsonShape) continue;
764
+
765
+ const shapeStr = jsonShapeToRuntimeLiteral(column.jsonShape);
766
+ columnEntries.push(
767
+ `${quote(fieldName)}: { shape: ${shapeStr} },`,
768
+ );
769
+ }
770
+
771
+ if (columnEntries.length === 0) continue;
772
+
773
+ tableEntries.push(
774
+ `${quote(tableName)}: {
775
+ ${columnEntries.map((entry) => `\t\t${entry}`).join("\n")}
776
+ },`,
777
+ );
778
+ }
779
+
780
+ if (tableEntries.length === 0) {
781
+ return "export const __appflareJsonColumns = {} as const;\n";
782
+ }
783
+
784
+ return `export const __appflareJsonColumns = {
785
+ ${tableEntries.map((entry) => `\t${entry}`).join("\n")}
786
+ } as const;
787
+ `;
788
+ }
789
+
790
+ function jsonShapeToRuntimeLiteral(shape: JsonShape): string {
791
+ if (shape.kind === "array") {
792
+ return `{ kind: "array", element: ${jsonShapeToRuntimeLiteral(shape.element)} }`;
793
+ }
794
+ if (shape.kind === "object") {
795
+ const fields = Object.entries(shape.shape)
796
+ .map(([key, fieldShape]) => `${quote(key)}: ${jsonShapeToRuntimeLiteral(fieldShape)}`)
797
+ .join(", ");
798
+ return `{ kind: "object", shape: { ${fields} } }`;
799
+ }
800
+ return `{ kind: ${quote(shape.kind)} }`;
801
+ }
802
+
803
+ function emitManyToManyRuntimeMetadata(definition: SchemaDefinition): string {
804
+ const tableEntries: string[] = [];
805
+
806
+ for (const [tableName, table] of Object.entries(definition.tables)) {
807
+ const relationEntries: string[] = [];
808
+
809
+ for (const [relationName, relation] of Object.entries(table.relations)) {
810
+ if (relation.relation !== "manyToMany") {
811
+ continue;
812
+ }
813
+
814
+ if (!relation.junctionTable) {
815
+ continue;
816
+ }
817
+
818
+ relationEntries.push(
819
+ `${quote(relationName)}: {
820
+ targetTable: ${quote(relation.targetTable)},
821
+ junctionTable: ${quote(relation.junctionTable)},
822
+ sourceField: ${quote(relation.sourceField ?? "")},
823
+ targetField: ${quote(relation.targetField ?? "")},
824
+ referenceField: ${quote(relation.referenceField ?? "id")},
825
+ targetReferenceField: ${quote(relation.targetReferenceField ?? "id")},
826
+ },`,
827
+ );
828
+ }
829
+
830
+ if (relationEntries.length === 0) {
831
+ continue;
832
+ }
833
+
834
+ tableEntries.push(
835
+ `${quote(tableName)}: {
836
+ ${relationEntries.map((entry) => `\t${entry}`).join("\n")}
837
+ },`,
838
+ );
839
+ }
840
+
841
+ if (tableEntries.length === 0) {
842
+ return "export const __appflareManyToMany = {} as const;\n";
843
+ }
844
+
845
+ return `export const __appflareManyToMany = {
846
+ ${tableEntries.map((entry) => `\t${entry}`).join("\n")}
847
+ } as const;
848
+ `;
849
+ }
850
+
851
+ function emitRuntimeRelationMetadata(definition: SchemaDefinition): string {
852
+ const tableEntries: string[] = [];
853
+
854
+ for (const [tableName, table] of Object.entries(definition.tables)) {
855
+ const relationEntries: string[] = [];
856
+
857
+ for (const [relationName, relation] of Object.entries(table.relations)) {
858
+ if (relation.relation === "one") {
859
+ relationEntries.push(
860
+ `${quote(relationName)}: {
861
+ kind: "one",
862
+ targetTable: ${quote(relation.targetTable)},
863
+ sourceField: ${quote(relation.field ?? "")},
864
+ referenceField: ${quote(relation.referenceField ?? "id")},
865
+ },`,
866
+ );
867
+ continue;
868
+ }
869
+
870
+ if (relation.relation === "many") {
871
+ relationEntries.push(
872
+ `${quote(relationName)}: {
873
+ kind: "many",
874
+ targetTable: ${quote(relation.targetTable)},
875
+ sourceField: ${quote(relation.field ?? "")},
876
+ referenceField: ${quote(relation.referenceField ?? "id")},
877
+ },`,
878
+ );
879
+ continue;
880
+ }
881
+
882
+ relationEntries.push(
883
+ `${quote(relationName)}: {
884
+ kind: "manyToMany",
885
+ targetTable: ${quote(relation.targetTable)},
886
+ junctionTable: ${quote(relation.junctionTable ?? "")},
887
+ sourceField: ${quote(relation.sourceField ?? "")},
888
+ targetField: ${quote(relation.targetField ?? "")},
889
+ referenceField: ${quote(relation.referenceField ?? "id")},
890
+ targetReferenceField: ${quote(relation.targetReferenceField ?? "id")},
891
+ },`,
892
+ );
893
+ }
894
+
895
+ if (relationEntries.length === 0) {
896
+ continue;
897
+ }
898
+
899
+ tableEntries.push(
900
+ `${quote(tableName)}: {
901
+ ${relationEntries.map((entry) => `\t${entry}`).join("\n")}
902
+ },`,
903
+ );
904
+ }
905
+
906
+ if (tableEntries.length === 0) {
907
+ return "export const __appflareRelations = {} as const;\n";
908
+ }
909
+
910
+ return `export const __appflareRelations = {
911
+ ${tableEntries.map((entry) => `\t${entry}`).join("\n")}
912
+ } as const;
913
+ `;
914
+ }
915
+
916
+ function emitDrizzleSchema(
917
+ definition: SchemaDefinition,
918
+ strategy: "camelToSnake",
919
+ ): string {
920
+ const localTables = new Set(Object.keys(definition.tables));
921
+ const externalTables = new Set<string>();
922
+
923
+ for (const table of Object.values(definition.tables)) {
924
+ for (const relationTarget of getRelationImports(table)) {
925
+ if (!localTables.has(relationTarget)) {
926
+ externalTables.add(relationTarget);
927
+ }
928
+ }
929
+ for (const column of Object.values(table.columns)) {
930
+ if (column.references && !localTables.has(column.references.table)) {
931
+ externalTables.add(column.references.table);
932
+ }
933
+ }
934
+ }
935
+
936
+ const enumColumns = new Map<string, ColumnDefinition>();
937
+ for (const table of Object.values(definition.tables)) {
938
+ for (const [fieldName, column] of Object.entries(table.columns)) {
939
+ if (
940
+ column.type === "enum" &&
941
+ column.enumValues &&
942
+ column.enumValues.length > 0
943
+ ) {
944
+ const key = column.enumRef ?? `${fieldName}`;
945
+ if (!enumColumns.has(key)) {
946
+ enumColumns.set(key, column);
947
+ }
948
+ }
949
+ }
950
+ }
951
+
952
+ const enumTypeLines: string[] = [];
953
+ const enumCustomTypeLines: string[] = [];
954
+ for (const [key, column] of enumColumns.entries()) {
955
+ const typeName = toPascalCase(key);
956
+ const valuesStr = column.enumValues!.map((v) => `"${v}"`).join(" | ");
957
+ enumTypeLines.push(`export type ${typeName} = ${valuesStr};`);
958
+ enumCustomTypeLines.push(
959
+ `export const ${typeName}Column = t.customType<{ data: ${typeName}; dataNotNull: ${typeName} }>({ dataType: () => "text" });`,
960
+ );
961
+ }
962
+
963
+ const tableBlocks: string[] = [];
964
+ const relationBlocks: string[] = [];
965
+
966
+ for (const [tableName, table] of Object.entries(definition.tables)) {
967
+ const sqlTableName = table.sqlName ?? toSnakeCase(tableName);
968
+ const columnLines: string[] = [];
969
+ const indexes: string[] = [];
970
+
971
+ for (const [fieldName, column] of Object.entries(table.columns)) {
972
+ let expr: string;
973
+ if (
974
+ column.type === "enum" &&
975
+ column.enumValues &&
976
+ column.enumValues.length > 0
977
+ ) {
978
+ const enumKey = column.enumRef ?? fieldName;
979
+ const typeName = toPascalCase(enumKey);
980
+ const resolvedSqlName = column.sqlName ?? toSnakeCase(fieldName);
981
+ const needsExplicitName = resolvedSqlName !== fieldName;
982
+ expr = needsExplicitName
983
+ ? `${typeName}Column(${quote(resolvedSqlName)})`
984
+ : `${typeName}Column()`;
985
+ if (column.isArray) {
986
+ expr += ".array()";
987
+ }
988
+ } else {
989
+ expr = drizzleBaseColumn(fieldName, column, strategy);
990
+ }
991
+
992
+ if (column.uuidPrimaryKey) {
993
+ expr += ".$defaultFn(() => crypto.randomUUID())";
994
+ }
995
+
996
+ if (column.primaryKey) {
997
+ expr += column.autoIncrement
998
+ ? ".primaryKey({ autoIncrement: true })"
999
+ : ".primaryKey()";
1000
+ }
1001
+ if (column.notNull) {
1002
+ expr += ".notNull()";
1003
+ }
1004
+ if (column.sqlDefault !== undefined) {
1005
+ expr += `.default(${toSqlLiteral(column.sqlDefault)})`;
1006
+ }
1007
+
1008
+ const reference = resolveColumnReference(fieldName, column, table);
1009
+ if (reference) {
1010
+ if (column.references?.onDelete || column.references?.onUpdate) {
1011
+ const actions: string[] = [];
1012
+ if (column.references.onDelete) {
1013
+ actions.push(`onDelete: ${quote(column.references.onDelete)}`);
1014
+ }
1015
+ if (column.references.onUpdate) {
1016
+ actions.push(`onUpdate: ${quote(column.references.onUpdate)}`);
1017
+ }
1018
+ expr += `.references(() => ${reference.tableName}.${reference.fieldName}, { ${actions.join(", ")} })`;
1019
+ } else {
1020
+ expr += `.references(() => ${reference.tableName}.${reference.fieldName})`;
1021
+ }
1022
+ }
1023
+
1024
+ if (column.unique) {
1025
+ const uniqueName =
1026
+ typeof column.unique === "object" && column.unique.name
1027
+ ? column.unique.name
1028
+ : `${sqlTableName}_${toSnakeCase(fieldName)}_unique_idx`;
1029
+ indexes.push(
1030
+ `\t\tt.uniqueIndex(${quote(uniqueName)}).on(table.${fieldName})`,
1031
+ );
1032
+ }
1033
+
1034
+ if (column.index) {
1035
+ const indexName =
1036
+ typeof column.index === "object" && column.index.name
1037
+ ? column.index.name
1038
+ : `${sqlTableName}_${toSnakeCase(fieldName)}_idx`;
1039
+ indexes.push(`\t\tt.index(${quote(indexName)}).on(table.${fieldName})`);
1040
+ }
1041
+
1042
+ columnLines.push(`\t\t${fieldName}: ${expr},`);
1043
+ }
1044
+
1045
+ if (indexes.length > 0) {
1046
+ tableBlocks.push(
1047
+ `export const ${tableName} = table(\n\t${quote(sqlTableName)},\n\t{\n${columnLines.join("\n")}\n\t},\n\t(table) => [\n${indexes.join(",\n")}\n\t],\n);`,
1048
+ );
1049
+ } else {
1050
+ tableBlocks.push(
1051
+ `export const ${tableName} = table(${quote(sqlTableName)}, {\n${columnLines.join("\n")}\n\t});`,
1052
+ );
1053
+ }
1054
+
1055
+ const oneRelations = Object.entries(table.relations).filter(
1056
+ ([, relation]) => {
1057
+ return relation.relation === "one";
1058
+ },
1059
+ ) as Array<[string, OneRelationDefinition]>;
1060
+ const manyRelations = Object.entries(table.relations).filter(
1061
+ ([, relation]) => {
1062
+ return relation.relation === "many";
1063
+ },
1064
+ ) as Array<[string, ManyRelationDefinition]>;
1065
+ const manyToManyRelations = Object.entries(table.relations).filter(
1066
+ ([, relation]) => {
1067
+ return relation.relation === "manyToMany";
1068
+ },
1069
+ ) as Array<[string, ManyToManyRelationDefinition]>;
1070
+
1071
+ if (
1072
+ oneRelations.length === 0 &&
1073
+ manyRelations.length === 0 &&
1074
+ manyToManyRelations.length === 0
1075
+ ) {
1076
+ continue;
1077
+ }
1078
+
1079
+ const relationLines: string[] = [];
1080
+ for (const [relationName, relation] of oneRelations) {
1081
+ const resolved = resolveOneRelationReference(tableName, table, relation);
1082
+ relationLines.push(
1083
+ `\t${relationName}: one(${relation.targetTable}, {\n\t\tfields: [${tableName}.${resolved.sourceField}],\n\t\treferences: [${relation.targetTable}.${resolved.targetField}],\n\t}),`,
1084
+ );
1085
+ }
1086
+ for (const [relationName, relation] of manyRelations) {
1087
+ relationLines.push(`\t${relationName}: many(${relation.targetTable}),`);
1088
+ }
1089
+ for (const [relationName, relation] of manyToManyRelations) {
1090
+ if (!relation.junctionTable) {
1091
+ throw new Error(
1092
+ `manyToMany relation '${tableName}.${relationName}' is missing junctionTable after normalization.`,
1093
+ );
1094
+ }
1095
+ relationLines.push(`\t${relationName}: many(${relation.junctionTable}),`);
1096
+ }
1097
+
1098
+ relationBlocks.push(
1099
+ `export const ${tableName}Relations = relations(${tableName}, ({ one, many }) => ({\n${relationLines.join("\n")}\n}));`,
1100
+ );
1101
+ }
1102
+
1103
+ return `import * as t from "drizzle-orm/sqlite-core";
1104
+ import { sqliteTable as table } from "drizzle-orm/sqlite-core";
1105
+ import { relations } from "drizzle-orm";
1106
+ ${buildExternalTableImportLines(externalTables)}
1107
+ ${enumTypeLines.join("\n")}
1108
+ ${enumCustomTypeLines.join("\n")}
1109
+
1110
+ ${tableBlocks.join("\n\n")}
1111
+
1112
+ ${relationBlocks.join("\n\n")}
1113
+
1114
+ ${emitJsonColumnsMetadata(definition)}
1115
+
1116
+ ${emitManyToManyRuntimeMetadata(definition)}
1117
+
1118
+ ${emitRuntimeRelationMetadata(definition)}
1119
+ `;
1120
+ }
1121
+
1122
+ function jsonShapeToZod(shape: JsonShape): string {
1123
+ if (shape.kind === "array") {
1124
+ return `z.array(${jsonShapeToZod(shape.element)})`;
1125
+ }
1126
+ if (shape.kind === "object") {
1127
+ const fields = Object.entries(shape.shape)
1128
+ .map(([key, fieldShape]) => `${quote(key)}: ${jsonShapeToZod(fieldShape)}`)
1129
+ .join(", ");
1130
+ return `z.object({ ${fields} })`;
1131
+ }
1132
+ if (shape.kind === "string") return "z.string()";
1133
+ if (shape.kind === "number") return "z.number()";
1134
+ if (shape.kind === "boolean") return "z.boolean()";
1135
+ if (shape.kind === "date") return "z.date()";
1136
+ return "z.unknown()";
1137
+ }
1138
+
1139
+ function zodSchemaExpression(
1140
+ column: ColumnDefinition,
1141
+ optional: boolean,
1142
+ nullable: boolean,
1143
+ ): string {
1144
+ let expr = "z.unknown()";
1145
+ if (column.type === "int") {
1146
+ expr = "z.number().int()";
1147
+ } else if (column.type === "string") {
1148
+ expr = "z.string()";
1149
+ if (column.length !== undefined) {
1150
+ expr += `.max(${column.length})`;
1151
+ }
1152
+ } else if (column.type === "boolean") {
1153
+ expr = "z.boolean()";
1154
+ } else if (column.type === "date") {
1155
+ expr = "z.date()";
1156
+ } else if (column.type === "enum" && column.enumValues && column.enumValues.length > 0) {
1157
+ const valuesStr = column.enumValues.map((v) => `"${v}"`).join(", ");
1158
+ const enumZod = `z.enum([${valuesStr}])`;
1159
+ expr = column.isArray ? `z.array(${enumZod})` : enumZod;
1160
+ } else if (column.type === "json" && column.jsonShape) {
1161
+ expr = jsonShapeToZod(column.jsonShape);
1162
+ }
1163
+
1164
+ if (optional) {
1165
+ expr += ".optional()";
1166
+ }
1167
+
1168
+ if (nullable) {
1169
+ expr += ".nullable()";
1170
+ }
1171
+
1172
+ return expr;
1173
+ }
1174
+
1175
+ function emitZodSchemas(definition: SchemaDefinition): string {
1176
+ const blocks: string[] = [];
1177
+
1178
+ for (const [tableName, table] of Object.entries(definition.tables)) {
1179
+ const pascal = toPascalCase(tableName);
1180
+ const insertLines: string[] = [];
1181
+ const selectLines: string[] = [];
1182
+
1183
+ for (const [fieldName, column] of Object.entries(table.columns)) {
1184
+ insertLines.push(
1185
+ `\t${fieldName}: ${zodSchemaExpression(column, isOptionalInsertColumn(column), isNullableSelectColumn(column))},`,
1186
+ );
1187
+ selectLines.push(
1188
+ `\t${fieldName}: ${zodSchemaExpression(column, isNullableSelectColumn(column), isNullableSelectColumn(column))},`,
1189
+ );
1190
+ }
1191
+
1192
+ blocks.push(`export const ${tableName}InsertSchema = z.object({\n${insertLines.join("\n")}\n});
1193
+ export const ${tableName}SelectSchema = z.object({\n${selectLines.join("\n")}\n});
1194
+
1195
+ export type ${pascal}Insert = z.infer<typeof ${tableName}InsertSchema>;
1196
+ export type ${pascal}Select = z.infer<typeof ${tableName}SelectSchema>;
1197
+ `);
1198
+ }
1199
+
1200
+ return `import { z } from "zod";
1201
+
1202
+ ${blocks.join("\n")}`;
1203
+ }
1204
+
1205
+ function jsonShapeToTypeScript(shape: JsonShape): string {
1206
+ if (shape.kind === "array") {
1207
+ return `Array<${jsonShapeToTypeScript(shape.element)}>`;
1208
+ }
1209
+ if (shape.kind === "object") {
1210
+ const fields = Object.entries(shape.shape)
1211
+ .map(([key, fieldShape]) => `${key}: ${jsonShapeToTypeScript(fieldShape)}`)
1212
+ .join("; ");
1213
+ return `{ ${fields} }`;
1214
+ }
1215
+ if (shape.kind === "string") return "string";
1216
+ if (shape.kind === "number") return "number";
1217
+ if (shape.kind === "boolean") return "boolean";
1218
+ if (shape.kind === "date") return "Date";
1219
+ return "unknown";
1220
+ }
1221
+
1222
+ function toTypeScriptType(column: ColumnDefinition): string {
1223
+ if (column.type === "int") {
1224
+ return "number";
1225
+ }
1226
+ if (column.type === "string") {
1227
+ return "string";
1228
+ }
1229
+ if (column.type === "boolean") {
1230
+ return "boolean";
1231
+ }
1232
+ if (column.type === "date") {
1233
+ return "Date";
1234
+ }
1235
+ if (column.type === "enum" && column.enumValues && column.enumValues.length > 0) {
1236
+ const union = column.enumValues.map((v) => `"${v}"`).join(" | ");
1237
+ if (column.isArray) {
1238
+ return `Array<${union}>`;
1239
+ }
1240
+ return union;
1241
+ }
1242
+ if (column.type === "json" && column.jsonShape) {
1243
+ return jsonShapeToTypeScript(column.jsonShape);
1244
+ }
1245
+ return "unknown";
1246
+ }
1247
+
1248
+ function emitTypes(definition: SchemaDefinition): string {
1249
+ const enumTypeLines: string[] = [];
1250
+ for (const [name, enumDef] of Object.entries(definition.enums ?? {})) {
1251
+ const typeName = toPascalCase(name);
1252
+ const valuesStr = enumDef.values.map((v) => `"${v}"`).join(" | ");
1253
+ enumTypeLines.push(`export type ${typeName} = ${valuesStr};`);
1254
+ }
1255
+
1256
+ const lines: string[] = [];
1257
+
1258
+ for (const [tableName, table] of Object.entries(definition.tables)) {
1259
+ const pascal = toPascalCase(tableName);
1260
+ const selectFields: string[] = [];
1261
+ const insertFields: string[] = [];
1262
+
1263
+ for (const [fieldName, column] of Object.entries(table.columns)) {
1264
+ const tsType = toTypeScriptType(column);
1265
+ const nullableSuffix = isNullableSelectColumn(column) ? " | null" : "";
1266
+ selectFields.push(
1267
+ `\t${fieldName}${isNullableSelectColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
1268
+ );
1269
+ insertFields.push(
1270
+ `\t${fieldName}${isOptionalInsertColumn(column) ? "?" : ""}: ${tsType}${nullableSuffix};`,
1271
+ );
1272
+ }
1273
+
1274
+ lines.push(`export type ${pascal} = {\n${selectFields.join("\n")}\n};
1275
+
1276
+ export type New${pascal} = {\n${insertFields.join("\n")}\n};`);
1277
+ }
1278
+
1279
+ return `${enumTypeLines.join("\n")}
1280
+ ${lines.join("\n\n")}
1281
+ `;
1282
+ }
1283
+
1284
+ function findSchemaExport(
1285
+ moduleExports: Record<string, unknown>,
1286
+ exportName?: string,
1287
+ ): SchemaDefinition {
1288
+ if (exportName) {
1289
+ const explicit = moduleExports[exportName];
1290
+ if (!isSchemaDefinition(explicit)) {
1291
+ throw new Error(
1292
+ `schemaDsl.exportName '${exportName}' does not point to a schema() export.`,
1293
+ );
1294
+ }
1295
+ return explicit;
1296
+ }
1297
+
1298
+ for (const candidate of Object.values(moduleExports)) {
1299
+ if (isSchemaDefinition(candidate)) {
1300
+ return candidate;
1301
+ }
1302
+ }
1303
+
1304
+ throw new Error(
1305
+ "No schema() export found in schemaDsl entry module. Set schemaDsl.exportName to the correct export.",
1306
+ );
1307
+ }
1308
+
1309
+ export async function compileSchemaDsl(
1310
+ loadedConfig: LoadedAppflareConfig,
1311
+ ): Promise<CompiledSchemaArtifacts | undefined> {
1312
+ const schemaDsl = loadedConfig.config.schemaDsl;
1313
+ if (!schemaDsl) {
1314
+ return undefined;
1315
+ }
1316
+
1317
+ const namingStrategy = schemaDsl.namingStrategy ?? "camelToSnake";
1318
+ const entryPath = resolve(loadedConfig.configDir, schemaDsl.entry);
1319
+ const outSchemaPath = resolve(
1320
+ loadedConfig.configDir,
1321
+ schemaDsl.outFile ?? resolve(loadedConfig.outDirAbs, "schema.compiled.ts"),
1322
+ );
1323
+ const outTypesPath = resolve(
1324
+ loadedConfig.configDir,
1325
+ schemaDsl.typesOutFile ??
1326
+ resolve(loadedConfig.outDirAbs, "schema.types.ts"),
1327
+ );
1328
+ const outZodPath = resolve(
1329
+ loadedConfig.configDir,
1330
+ schemaDsl.zodOutFile ?? resolve(loadedConfig.outDirAbs, "schema.zod.ts"),
1331
+ );
1332
+
1333
+ const moduleUrl = `${pathToFileURL(entryPath).href}?t=${Date.now()}`;
1334
+ const schemaModule = (await import(moduleUrl)) as Record<string, unknown>;
1335
+ const schemaDefinition = findSchemaExport(schemaModule, schemaDsl.exportName);
1336
+ const normalizedSchema = normalizeSchemaDefinition(schemaDefinition);
1337
+
1338
+ await Promise.all([
1339
+ mkdir(dirname(outSchemaPath), { recursive: true }),
1340
+ mkdir(dirname(outTypesPath), { recursive: true }),
1341
+ mkdir(dirname(outZodPath), { recursive: true }),
1342
+ ]);
1343
+
1344
+ const drizzleSchemaSource = emitDrizzleSchema(
1345
+ normalizedSchema,
1346
+ namingStrategy,
1347
+ );
1348
+ const typesSource = emitTypes(normalizedSchema);
1349
+ const zodSource = emitZodSchemas(normalizedSchema);
1350
+
1351
+ await Promise.all([
1352
+ Bun.write(outSchemaPath, drizzleSchemaSource),
1353
+ Bun.write(outTypesPath, typesSource),
1354
+ Bun.write(outZodPath, zodSource),
1355
+ ]);
1356
+
1357
+ return {
1358
+ schemaPath: outSchemaPath,
1359
+ typesPath: outTypesPath,
1360
+ zodPath: outZodPath,
1361
+ tableNames: Object.keys(normalizedSchema.tables),
1362
+ };
1363
+ }