@danielhritcu/zenstack-custom 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2668 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/codegen/config.ts
5
+ function defineConfig(tables, config) {
6
+ const derived2 = config.derived ?? {};
7
+ const orm = {
8
+ ...tables
9
+ };
10
+ for (const [name, desc] of Object.entries(derived2)) {
11
+ if (name in tables) {
12
+ throw new Error(`Derived model "${name}" collides with existing table name.`);
13
+ }
14
+ orm[name] = desc;
15
+ }
16
+ const models = config.models(orm);
17
+ return {
18
+ tables,
19
+ schema: config.schema,
20
+ default: config.default,
21
+ derived: derived2,
22
+ models
23
+ };
24
+ }
25
+ __name(defineConfig, "defineConfig");
26
+
27
+ // src/codegen/dsl/extend.ts
28
+ import { getTableConfig } from "drizzle-orm/pg-core";
29
+ function inferNarrow(where) {
30
+ const narrow = {};
31
+ let hasNarrow = false;
32
+ for (const [field, condition] of Object.entries(where)) {
33
+ if (condition && typeof condition === "object" && !Array.isArray(condition)) {
34
+ const cond = condition;
35
+ if ("in" in cond && Array.isArray(cond["in"])) {
36
+ narrow[field] = cond["in"];
37
+ hasNarrow = true;
38
+ }
39
+ }
40
+ }
41
+ return hasNarrow ? narrow : null;
42
+ }
43
+ __name(inferNarrow, "inferNarrow");
44
+ function derived(base, opts) {
45
+ const cfg = getTableConfig(base);
46
+ const descriptor = {
47
+ __brand: "derived",
48
+ base,
49
+ where: opts.where,
50
+ narrow: opts.narrow ?? inferNarrow(opts.where),
51
+ baseName: cfg.name
52
+ };
53
+ return new Proxy(descriptor, {
54
+ get(target, prop, receiver) {
55
+ if (prop in target) return Reflect.get(target, prop, receiver);
56
+ return Reflect.get(base, prop);
57
+ },
58
+ has(target, prop) {
59
+ return prop in target || prop in base;
60
+ }
61
+ });
62
+ }
63
+ __name(derived, "derived");
64
+ function extend(tables, derivedModels) {
65
+ for (const key of Object.keys(derivedModels)) {
66
+ if (key in tables) {
67
+ throw new Error(`Derived model "${key}" collides with existing table name. Choose a different name.`);
68
+ }
69
+ }
70
+ const extended = {
71
+ tables: {
72
+ ...tables
73
+ },
74
+ derived: {
75
+ ...derivedModels
76
+ }
77
+ };
78
+ const schemaProps = Object.assign({}, tables, derivedModels, {
79
+ __extended: extended
80
+ });
81
+ const defineModelsFn = /* @__PURE__ */ __name((globalConfig, models) => ({
82
+ schema: extended,
83
+ global: globalConfig,
84
+ models
85
+ }), "defineModelsFn");
86
+ return Object.assign(defineModelsFn, schemaProps);
87
+ }
88
+ __name(extend, "extend");
89
+
90
+ // src/codegen/dsl/relations.ts
91
+ function one(target, opts) {
92
+ return {
93
+ kind: "one",
94
+ target,
95
+ fields: opts.fields,
96
+ references: opts.references,
97
+ ...opts.where ? {
98
+ where: opts.where
99
+ } : {},
100
+ ...opts.relationName ? {
101
+ relationName: opts.relationName
102
+ } : {}
103
+ };
104
+ }
105
+ __name(one, "one");
106
+ function many(target, opts) {
107
+ return {
108
+ kind: "many",
109
+ target,
110
+ ...opts?.where ? {
111
+ where: opts.where
112
+ } : {},
113
+ ...opts?.single ? {
114
+ single: true
115
+ } : {}
116
+ };
117
+ }
118
+ __name(many, "many");
119
+ function through(path) {
120
+ return {
121
+ kind: "through",
122
+ path
123
+ };
124
+ }
125
+ __name(through, "through");
126
+
127
+ // src/codegen/dsl/model.ts
128
+ function model(table, opts) {
129
+ const helpers = {
130
+ one,
131
+ many,
132
+ through
133
+ };
134
+ return {
135
+ table,
136
+ relations: opts.relations?.(helpers),
137
+ computed: opts.computed,
138
+ search: opts.search,
139
+ defaultWhere: opts.defaultWhere,
140
+ derived: opts.derived,
141
+ validate: opts.validate
142
+ };
143
+ }
144
+ __name(model, "model");
145
+ function defineModels(extendedSchema, globalConfig, models) {
146
+ return {
147
+ schema: extendedSchema.__extended,
148
+ global: globalConfig,
149
+ models
150
+ };
151
+ }
152
+ __name(defineModels, "defineModels");
153
+
154
+ // src/codegen/dsl/adapter.ts
155
+ import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
156
+ var COMPUTED_TYPE_MAP = {
157
+ json: {
158
+ type: "Json",
159
+ tsType: "JsonValue"
160
+ },
161
+ string: {
162
+ type: "String",
163
+ tsType: "string"
164
+ },
165
+ text: {
166
+ type: "String",
167
+ tsType: "string"
168
+ },
169
+ int: {
170
+ type: "Int",
171
+ tsType: "number"
172
+ },
173
+ float: {
174
+ type: "Float",
175
+ tsType: "number"
176
+ },
177
+ bool: {
178
+ type: "Boolean",
179
+ tsType: "boolean"
180
+ },
181
+ boolean: {
182
+ type: "Boolean",
183
+ tsType: "boolean"
184
+ },
185
+ dateTime: {
186
+ type: "DateTime",
187
+ tsType: "Date"
188
+ }
189
+ };
190
+ function resolveColumn(tables, column) {
191
+ for (const table of Object.values(tables)) {
192
+ for (const key of Object.keys(table)) {
193
+ if (table[key] === column) return {
194
+ table,
195
+ jsKey: key
196
+ };
197
+ }
198
+ }
199
+ const sqlName = column.name;
200
+ for (const table of Object.values(tables)) {
201
+ for (const key of Object.keys(table)) {
202
+ const col = table[key];
203
+ if (col && typeof col === "object" && "name" in col && col.name === sqlName) {
204
+ return {
205
+ table,
206
+ jsKey: key
207
+ };
208
+ }
209
+ }
210
+ }
211
+ return void 0;
212
+ }
213
+ __name(resolveColumn, "resolveColumn");
214
+ function findExportNameForTable(tables, target) {
215
+ for (const [exportName, table] of Object.entries(tables)) {
216
+ if (table === target) return exportName;
217
+ }
218
+ const targetSqlName = getTableConfig2(target).name;
219
+ for (const [exportName, table] of Object.entries(tables)) {
220
+ if (getTableConfig2(table).name === targetSqlName) return exportName;
221
+ }
222
+ throw new Error(`Could not find export name for table "${targetSqlName}"`);
223
+ }
224
+ __name(findExportNameForTable, "findExportNameForTable");
225
+ function sqlNameToExportName(tables, sqlName) {
226
+ for (const [exportName, table] of Object.entries(tables)) {
227
+ if (getTableConfig2(table).name === sqlName) return exportName;
228
+ }
229
+ throw new Error(`No table export found with SQL name "${sqlName}"`);
230
+ }
231
+ __name(sqlNameToExportName, "sqlNameToExportName");
232
+ function findDerivedNameForDescriptor(derived2, descriptor) {
233
+ for (const [name, desc] of Object.entries(derived2)) {
234
+ if (desc === descriptor) return name;
235
+ }
236
+ throw new Error(`Could not find derived model name for descriptor with base "${descriptor.baseName}"`);
237
+ }
238
+ __name(findDerivedNameForDescriptor, "findDerivedNameForDescriptor");
239
+ function convertSearchFields(tables, fields) {
240
+ const result = {};
241
+ for (const field of fields) {
242
+ if ("name" in field && typeof field.name === "string") {
243
+ const resolved = resolveColumn(tables, field);
244
+ if (!resolved) throw new Error(`Could not resolve column "${field.name}"`);
245
+ result[resolved.jsKey] = true;
246
+ } else {
247
+ for (const [relation, nested] of Object.entries(field)) {
248
+ result[relation] = convertSearchFields(tables, nested);
249
+ }
250
+ }
251
+ }
252
+ return result;
253
+ }
254
+ __name(convertSearchFields, "convertSearchFields");
255
+ function convertSearchProfile(tables, _modelTable, profile) {
256
+ return {
257
+ fields: convertSearchFields(tables, profile.fields)
258
+ };
259
+ }
260
+ __name(convertSearchProfile, "convertSearchProfile");
261
+ function adaptToLegacyConfig(output) {
262
+ const { schema, models } = output;
263
+ const computedFields = {};
264
+ const computedCallbacks = {};
265
+ const derivedModels = {};
266
+ const filteredRelations = {};
267
+ const searchDefaults = {};
268
+ const throughRelations = {};
269
+ const relationTargets = {};
270
+ const modelScopes = {};
271
+ const derivedFields = {};
272
+ const validationSchemas = {};
273
+ const fkRelations = {};
274
+ for (const [derivedName, desc] of Object.entries(schema.derived)) {
275
+ const baseExportName = sqlNameToExportName(schema.tables, desc.baseName);
276
+ if (!derivedModels[baseExportName]) {
277
+ derivedModels[baseExportName] = {};
278
+ }
279
+ derivedModels[baseExportName][derivedName] = {
280
+ where: desc.where,
281
+ ...desc.narrow ? {
282
+ narrow: desc.narrow
283
+ } : {}
284
+ };
285
+ }
286
+ for (const [modelName, config] of Object.entries(models)) {
287
+ if (config.computed && typeof config.computed !== "function") {
288
+ const resolvedComputed = {};
289
+ const callbacks = {};
290
+ for (const [fieldName, decl] of Object.entries(config.computed)) {
291
+ if (typeof decl === "function") {
292
+ resolvedComputed[fieldName] = COMPUTED_TYPE_MAP["json"];
293
+ callbacks[fieldName] = decl;
294
+ } else {
295
+ const declObj = decl;
296
+ const typeKey = declObj.type?.toLowerCase() ?? "json";
297
+ resolvedComputed[fieldName] = COMPUTED_TYPE_MAP[typeKey] ?? COMPUTED_TYPE_MAP["json"];
298
+ }
299
+ }
300
+ computedFields[modelName] = resolvedComputed;
301
+ if (Object.keys(callbacks).length > 0) {
302
+ computedCallbacks[modelName] = callbacks;
303
+ }
304
+ }
305
+ if (config.relations) {
306
+ for (const [relName, rel] of Object.entries(config.relations)) {
307
+ if (rel.kind === "one") {
308
+ const oneRel = rel;
309
+ const targetTable = "__brand" in oneRel.target ? oneRel.target.base : oneRel.target;
310
+ const targetExportName = findExportNameForTable(schema.tables, targetTable);
311
+ const resolvedFields = oneRel.fields.map((col) => {
312
+ const resolved = resolveColumn(schema.tables, col);
313
+ return resolved?.jsKey ?? col.name;
314
+ });
315
+ const resolvedRefs = oneRel.references.map((col) => {
316
+ const resolved = resolveColumn(schema.tables, col);
317
+ return resolved?.jsKey ?? col.name;
318
+ });
319
+ if (oneRel.where) {
320
+ if (!fkRelations[modelName]) {
321
+ fkRelations[modelName] = {};
322
+ }
323
+ fkRelations[modelName][relName] = {
324
+ targetExportName,
325
+ fields: resolvedFields,
326
+ references: resolvedRefs,
327
+ relationName: oneRel.relationName ?? null
328
+ };
329
+ if (!filteredRelations[modelName]) {
330
+ filteredRelations[modelName] = {};
331
+ }
332
+ filteredRelations[modelName][relName] = {
333
+ relation: {
334
+ [relName]: true
335
+ },
336
+ where: oneRel.where,
337
+ single: true
338
+ };
339
+ } else {
340
+ if (!fkRelations[modelName]) {
341
+ fkRelations[modelName] = {};
342
+ }
343
+ fkRelations[modelName][relName] = {
344
+ targetExportName,
345
+ fields: resolvedFields,
346
+ references: resolvedRefs,
347
+ relationName: oneRel.relationName ?? null
348
+ };
349
+ }
350
+ if ("__brand" in oneRel.target && oneRel.target.__brand === "derived") {
351
+ const descriptor = oneRel.target;
352
+ const derivedName = findDerivedNameForDescriptor(schema.derived, descriptor);
353
+ const baseExportName = sqlNameToExportName(schema.tables, descriptor.baseName);
354
+ if (!derivedModels[baseExportName]) {
355
+ derivedModels[baseExportName] = {};
356
+ }
357
+ const derivedEntry = derivedModels[baseExportName][derivedName];
358
+ if (derivedEntry) {
359
+ if (!derivedEntry.relations) {
360
+ derivedEntry.relations = {};
361
+ }
362
+ if (!derivedEntry.relations[modelName]) {
363
+ derivedEntry.relations[modelName] = {};
364
+ }
365
+ derivedEntry.relations[modelName][relName] = true;
366
+ }
367
+ if (!relationTargets[modelName]) {
368
+ relationTargets[modelName] = {};
369
+ }
370
+ relationTargets[modelName][relName] = derivedName;
371
+ }
372
+ } else if (rel.kind === "many") {
373
+ const manyRel = rel;
374
+ const targetExportName = findExportNameForTable(schema.tables, manyRel.target);
375
+ if (!filteredRelations[modelName]) {
376
+ filteredRelations[modelName] = {};
377
+ }
378
+ filteredRelations[modelName][relName] = {
379
+ relation: {
380
+ [targetExportName]: true
381
+ },
382
+ ...manyRel.where ? {
383
+ where: manyRel.where
384
+ } : {},
385
+ ...manyRel.single ? {
386
+ single: true
387
+ } : {}
388
+ };
389
+ } else if (rel.kind === "through") {
390
+ const throughRel = rel;
391
+ if (!throughRelations[modelName]) {
392
+ throughRelations[modelName] = {};
393
+ }
394
+ throughRelations[modelName][relName] = {
395
+ path: throughRel.path
396
+ };
397
+ }
398
+ }
399
+ }
400
+ if (config.defaultWhere) {
401
+ modelScopes[modelName] = config.defaultWhere;
402
+ } else if (output.global.defaultWhere) {
403
+ modelScopes[modelName] = output.global.defaultWhere;
404
+ }
405
+ if (config.derived) {
406
+ derivedFields[modelName] = config.derived;
407
+ }
408
+ if (config.validate) {
409
+ validationSchemas[modelName] = config.validate;
410
+ }
411
+ if (config.search) {
412
+ const modelSearchDefaults = {};
413
+ for (const [profileName, profile] of Object.entries(config.search)) {
414
+ modelSearchDefaults[profileName] = convertSearchProfile(schema.tables, config.table, profile);
415
+ }
416
+ searchDefaults[modelName] = modelSearchDefaults;
417
+ }
418
+ }
419
+ return {
420
+ computedFields,
421
+ computedCallbacks,
422
+ derivedModels,
423
+ filteredRelations,
424
+ searchDefaults,
425
+ throughRelations,
426
+ relationTargets,
427
+ modelScopes,
428
+ derivedFields,
429
+ validationSchemas,
430
+ fkRelations
431
+ };
432
+ }
433
+ __name(adaptToLegacyConfig, "adaptToLegacyConfig");
434
+
435
+ // src/codegen/utils.ts
436
+ import * as fs from "fs";
437
+ var APP_SLUG_SQL = "app_slug";
438
+ var APP_SLUG_JS = "appSlug";
439
+ var GENERATED_FILE_BANNER = [
440
+ "//////////////////////////////////////////////////////////////////////////////////////////////",
441
+ "// DO NOT MODIFY THIS FILE //",
442
+ "// Generated by scripts/zen from Drizzle schema. //",
443
+ "//////////////////////////////////////////////////////////////////////////////////////////////",
444
+ "",
445
+ "/* eslint-disable */"
446
+ ];
447
+ function emitGeneratedFileBanner() {
448
+ return [
449
+ ...GENERATED_FILE_BANNER
450
+ ];
451
+ }
452
+ __name(emitGeneratedFileBanner, "emitGeneratedFileBanner");
453
+ function capitalize(s) {
454
+ return s.charAt(0).toUpperCase() + s.slice(1);
455
+ }
456
+ __name(capitalize, "capitalize");
457
+ function toPascalCase(s) {
458
+ return s.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[_\-\s]+/).filter(Boolean).map(capitalize).join("");
459
+ }
460
+ __name(toPascalCase, "toPascalCase");
461
+ function uncapitalize(s) {
462
+ return s.charAt(0).toLowerCase() + s.slice(1);
463
+ }
464
+ __name(uncapitalize, "uncapitalize");
465
+ function esc(s) {
466
+ return JSON.stringify(s);
467
+ }
468
+ __name(esc, "esc");
469
+ function getDrizzleTableName(table) {
470
+ return table[Symbol.for("drizzle:Name")];
471
+ }
472
+ __name(getDrizzleTableName, "getDrizzleTableName");
473
+ function writeFileIfChanged(filePath, content) {
474
+ if (fs.existsSync(filePath) && fs.readFileSync(filePath, "utf-8") === content) {
475
+ return false;
476
+ }
477
+ fs.writeFileSync(filePath, content, "utf-8");
478
+ return true;
479
+ }
480
+ __name(writeFileIfChanged, "writeFileIfChanged");
481
+
482
+ // src/codegen/columns.ts
483
+ function mapColumn(jsKey, col, enumMap) {
484
+ const sqlName = col.name;
485
+ const colType = col.columnType;
486
+ const notNull = col.notNull;
487
+ const hasDefault = col.hasDefault;
488
+ const isPrimary = col.primary;
489
+ const isUnique = col.isUnique;
490
+ const generated = col.generated;
491
+ const isArray = colType === "PgArray";
492
+ let type = "String";
493
+ const dbAttrs = [];
494
+ let enumPgName = null;
495
+ let isJsonColumn = false;
496
+ let actualColType = colType;
497
+ let actualCol = col;
498
+ if (isArray && col.baseColumn) {
499
+ actualCol = col.baseColumn;
500
+ actualColType = actualCol.columnType;
501
+ }
502
+ switch (actualColType) {
503
+ case "PgUUID":
504
+ type = "String";
505
+ dbAttrs.push("@db.Uuid");
506
+ break;
507
+ case "PgText":
508
+ type = "String";
509
+ break;
510
+ case "PgVarchar": {
511
+ type = "String";
512
+ const len = actualCol.length;
513
+ if (len) dbAttrs.push(`@db.VarChar(${len})`);
514
+ else dbAttrs.push("@db.VarChar");
515
+ break;
516
+ }
517
+ case "PgBoolean":
518
+ type = "Boolean";
519
+ break;
520
+ case "PgInteger":
521
+ type = "Int";
522
+ break;
523
+ case "PgBigInt53":
524
+ type = "BigInt";
525
+ break;
526
+ case "PgSerial":
527
+ type = "Int";
528
+ break;
529
+ case "PgReal":
530
+ type = "Float";
531
+ dbAttrs.push("@db.Real");
532
+ break;
533
+ case "PgDoublePrecision":
534
+ type = "Float";
535
+ dbAttrs.push("@db.DoublePrecision");
536
+ break;
537
+ case "PgTimestamp": {
538
+ type = "DateTime";
539
+ const wtz = actualCol.withTimezone ?? actualCol.config?.withTimezone;
540
+ if (wtz) dbAttrs.push("@db.Timestamptz(6)");
541
+ else dbAttrs.push("@db.Timestamp(6)");
542
+ break;
543
+ }
544
+ case "PgDate":
545
+ case "PgDateString":
546
+ type = "DateTime";
547
+ dbAttrs.push("@db.Date");
548
+ break;
549
+ case "PgJsonb":
550
+ type = "Json";
551
+ isJsonColumn = true;
552
+ dbAttrs.push("@db.JsonB");
553
+ break;
554
+ case "PgJson":
555
+ type = "Json";
556
+ isJsonColumn = true;
557
+ dbAttrs.push("@db.Json");
558
+ break;
559
+ case "PgEnumColumn": {
560
+ if (isArray) {
561
+ type = "String";
562
+ } else {
563
+ const eName = actualCol.enum?.enumName;
564
+ if (eName && enumMap.has(eName)) {
565
+ type = enumMap.get(eName).zenstackName;
566
+ enumPgName = eName;
567
+ } else {
568
+ type = "String";
569
+ }
570
+ }
571
+ break;
572
+ }
573
+ case "PgCustomColumn": {
574
+ const sqlType = actualCol.sqlName || actualCol.config?.dataType;
575
+ if (sqlType === "json") {
576
+ type = "Json";
577
+ isJsonColumn = true;
578
+ dbAttrs.push("@db.Json");
579
+ } else if (sqlType === "jsonb") {
580
+ type = "Json";
581
+ isJsonColumn = true;
582
+ dbAttrs.push("@db.JsonB");
583
+ } else if (sqlType === "numeric") {
584
+ type = "Decimal";
585
+ } else type = "String";
586
+ break;
587
+ }
588
+ case "PgNumeric":
589
+ type = "Decimal";
590
+ break;
591
+ default:
592
+ console.warn(`Unknown Drizzle column type "${actualColType}" for column "${sqlName}" \u2014 falling back to String`);
593
+ type = "String";
594
+ }
595
+ let defaultExpr = null;
596
+ if (hasDefault) {
597
+ if (isPrimary && actualColType === "PgUUID") {
598
+ defaultExpr = 'ExpressionUtils.call("uuid")';
599
+ } else if (actualColType === "PgBigInt53" && col.generatedIdentity) {
600
+ defaultExpr = 'ExpressionUtils.call("autoincrement")';
601
+ } else if (actualColType === "PgSerial") {
602
+ defaultExpr = 'ExpressionUtils.call("autoincrement")';
603
+ } else if (col.defaultFn) {
604
+ if (type === "DateTime") {
605
+ defaultExpr = 'ExpressionUtils.call("now")';
606
+ } else if (type === "String" && isPrimary) {
607
+ defaultExpr = 'ExpressionUtils.call("uuid")';
608
+ } else {
609
+ defaultExpr = null;
610
+ }
611
+ } else if (col.default !== void 0) {
612
+ const d = col.default;
613
+ if (typeof d === "boolean" || typeof d === "number") {
614
+ defaultExpr = `ExpressionUtils.literal(${d})`;
615
+ } else if (typeof d === "string") {
616
+ defaultExpr = `ExpressionUtils.literal(${esc(d)})`;
617
+ } else if (d && typeof d === "object" && "queryChunks" in d) {
618
+ try {
619
+ const chunks = d.queryChunks || [];
620
+ const sqlStr = chunks.map((c) => typeof c === "string" ? c : c.value?.[0] || "").join("").trim();
621
+ if (sqlStr) {
622
+ defaultExpr = `ExpressionUtils.call("dbgenerated", [ExpressionUtils.literal(${esc(sqlStr)})])`;
623
+ }
624
+ } catch (e) {
625
+ console.warn(`Failed to parse SQL default for column "${sqlName}":`, e);
626
+ }
627
+ } else if (Array.isArray(d) && d.length === 0) {
628
+ defaultExpr = "[] as FieldDefault";
629
+ } else if (typeof d === "object" && d !== null && Object.keys(d).length === 0) {
630
+ defaultExpr = `ExpressionUtils.literal("{}")`;
631
+ }
632
+ }
633
+ }
634
+ return {
635
+ name: jsKey,
636
+ sqlName,
637
+ type,
638
+ isJsonColumn,
639
+ optional: !notNull && !hasDefault,
640
+ array: isArray,
641
+ id: isPrimary,
642
+ unique: isUnique,
643
+ hasDefault,
644
+ dbAttrs,
645
+ defaultExpr,
646
+ enumPgName,
647
+ isGenerated: !!generated
648
+ };
649
+ }
650
+ __name(mapColumn, "mapColumn");
651
+
652
+ // src/codegen/discover.ts
653
+ import { getTableConfig as getTableConfig3, getViewConfig } from "drizzle-orm/pg-core";
654
+ import * as fs2 from "fs";
655
+ import * as ts from "typescript";
656
+
657
+ // src/drizzle/define.ts
658
+ import { SQL, sql } from "drizzle-orm";
659
+ import { pgEnum as drizzlePgEnum } from "drizzle-orm/pg-core";
660
+ var ENUM_MAP = Symbol.for("drizzle:EnumMap");
661
+
662
+ // src/codegen/discover.ts
663
+ function discoverEnums(allEnums) {
664
+ const enums = /* @__PURE__ */ new Map();
665
+ for (const [exportName, val] of Object.entries(allEnums)) {
666
+ if (typeof val !== "function" || !("enumName" in val)) continue;
667
+ const e = val;
668
+ const pgName = e.enumName;
669
+ const values = e.enumValues;
670
+ const zenstackName = capitalize(exportName.replace(/Enum$/, ""));
671
+ const mapping = e[ENUM_MAP] ?? null;
672
+ enums.set(pgName, {
673
+ pgName,
674
+ zenstackName,
675
+ values,
676
+ mapping,
677
+ mappedName: pgName
678
+ });
679
+ }
680
+ return enums;
681
+ }
682
+ __name(discoverEnums, "discoverEnums");
683
+ function getColumnsObject(node) {
684
+ if (ts.isObjectLiteralExpression(node)) return node;
685
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
686
+ if (ts.isObjectLiteralExpression(node.body)) return node.body;
687
+ if (ts.isParenthesizedExpression(node.body) && ts.isObjectLiteralExpression(node.body.expression)) {
688
+ return node.body.expression;
689
+ }
690
+ if (ts.isBlock(node.body)) {
691
+ for (const statement of node.body.statements) {
692
+ if (!ts.isReturnStatement(statement) || !statement.expression) continue;
693
+ if (ts.isObjectLiteralExpression(statement.expression)) return statement.expression;
694
+ if (ts.isParenthesizedExpression(statement.expression) && ts.isObjectLiteralExpression(statement.expression.expression)) {
695
+ return statement.expression.expression;
696
+ }
697
+ }
698
+ }
699
+ }
700
+ return null;
701
+ }
702
+ __name(getColumnsObject, "getColumnsObject");
703
+ function getColumnBuilderName(node) {
704
+ if (ts.isCallExpression(node)) return getColumnBuilderName(node.expression);
705
+ if (ts.isPropertyAccessExpression(node)) {
706
+ if (ts.isIdentifier(node.expression) && node.expression.text === "col") {
707
+ return node.name.text;
708
+ }
709
+ return getColumnBuilderName(node.expression);
710
+ }
711
+ return null;
712
+ }
713
+ __name(getColumnBuilderName, "getColumnBuilderName");
714
+ function assertNoTypedColumnOverrides(tablesFilePath) {
715
+ const sourceFile = ts.createSourceFile(tablesFilePath, fs2.readFileSync(tablesFilePath, "utf8"), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
716
+ for (const statement of sourceFile.statements) {
717
+ if (!ts.isVariableStatement(statement)) continue;
718
+ for (const declaration of statement.declarationList.declarations) {
719
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue;
720
+ if (!ts.isCallExpression(declaration.initializer)) continue;
721
+ const columnsArg = declaration.initializer.arguments[1];
722
+ if (!columnsArg) continue;
723
+ const columnsObject = getColumnsObject(columnsArg);
724
+ if (!columnsObject) continue;
725
+ for (const property of columnsObject.properties) {
726
+ if (!ts.isPropertyAssignment(property)) continue;
727
+ const nameNode = property.name;
728
+ const jsKey = ts.isIdentifier(nameNode) || ts.isStringLiteral(nameNode) ? nameNode.text : null;
729
+ if (!jsKey) continue;
730
+ let typedCall = null;
731
+ const visit = /* @__PURE__ */ __name((node) => {
732
+ if (typedCall) return;
733
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "$type") {
734
+ typedCall = node;
735
+ return;
736
+ }
737
+ ts.forEachChild(node, visit);
738
+ }, "visit");
739
+ visit(property.initializer);
740
+ if (!typedCall) continue;
741
+ const resolvedCall = typedCall;
742
+ const builderName = getColumnBuilderName(resolvedCall.expression.expression);
743
+ if (builderName === "json" || builderName === "jsonb" || builderName === "array") continue;
744
+ const fullText = property.initializer.getText();
745
+ if (fullText.includes(".array()")) continue;
746
+ console.warn(`Warning: Column "${declaration.name.text}.${jsKey}" uses $type<...>() on a ${builderName ?? "scalar"} column. Consider using a real enum.`);
747
+ }
748
+ }
749
+ }
750
+ }
751
+ __name(assertNoTypedColumnOverrides, "assertNoTypedColumnOverrides");
752
+ function discoverTables(allTables, computedFieldsConfig = {}, derivedModelsConfig = {}) {
753
+ const tables = [];
754
+ const tablesByModel = /* @__PURE__ */ new Map();
755
+ for (const [exportName, _val] of Object.entries(allTables)) {
756
+ const val = _val;
757
+ if (!val || typeof val !== "object") continue;
758
+ const syms = Object.getOwnPropertySymbols(val);
759
+ if (!syms.some((s) => s.toString().includes("IsDrizzleTable"))) continue;
760
+ const sqlName = getDrizzleTableName(val);
761
+ const modelName = exportName;
762
+ const typeName = capitalize(exportName);
763
+ const sqlToJsKey = /* @__PURE__ */ new Map();
764
+ const jsKeySet = /* @__PURE__ */ new Set();
765
+ for (const key of Object.keys(val)) {
766
+ const col = val[key];
767
+ if (col.name && col.columnType) {
768
+ sqlToJsKey.set(col.name, key);
769
+ jsKeySet.add(key);
770
+ }
771
+ }
772
+ const cfg = getTableConfig3(val);
773
+ const computedFields = Object.entries(computedFieldsConfig[exportName] ?? {}).map(([name, field]) => {
774
+ if (jsKeySet.has(name)) {
775
+ throw new Error(`Computed field "${exportName}.${name}" collides with an existing column.`);
776
+ }
777
+ return {
778
+ name,
779
+ type: field.type,
780
+ tsType: field.tsType
781
+ };
782
+ });
783
+ tables.push({
784
+ exportName,
785
+ sqlName,
786
+ modelName,
787
+ typeName,
788
+ table: val,
789
+ cfg,
790
+ sqlToJsKey,
791
+ jsKeySet,
792
+ computedFields,
793
+ derivedFrom: null,
794
+ defaultWhere: null,
795
+ narrow: null
796
+ });
797
+ tablesByModel.set(modelName, tables[tables.length - 1]);
798
+ }
799
+ for (const modelName of Object.keys(computedFieldsConfig)) {
800
+ if (!tablesByModel.has(modelName)) {
801
+ throw new Error(`Computed fields declared for unknown table export "${modelName}".`);
802
+ }
803
+ }
804
+ for (const [baseModelName, derivedModels] of Object.entries(derivedModelsConfig)) {
805
+ const baseTable = tablesByModel.get(baseModelName);
806
+ if (!baseTable) {
807
+ throw new Error(`Derived models declared for unknown table export "${baseModelName}".`);
808
+ }
809
+ for (const [derivedModelName, declaration] of Object.entries(derivedModels)) {
810
+ if (tablesByModel.has(derivedModelName)) {
811
+ throw new Error(`Derived model "${derivedModelName}" collides with an existing table or derived model.`);
812
+ }
813
+ const derivedTable = {
814
+ ...baseTable,
815
+ exportName: derivedModelName,
816
+ modelName: derivedModelName,
817
+ typeName: capitalize(derivedModelName),
818
+ computedFields: [
819
+ ...baseTable.computedFields
820
+ ],
821
+ derivedFrom: baseModelName,
822
+ defaultWhere: declaration.where,
823
+ narrow: declaration.narrow ?? null
824
+ };
825
+ tables.push(derivedTable);
826
+ tablesByModel.set(derivedModelName, derivedTable);
827
+ }
828
+ }
829
+ return tables;
830
+ }
831
+ __name(discoverTables, "discoverTables");
832
+ function discoverViews(allViews) {
833
+ const views = [];
834
+ for (const [exportName, val] of Object.entries(allViews)) {
835
+ if (!val || typeof val !== "object") continue;
836
+ const syms = Object.getOwnPropertySymbols(val);
837
+ if (!syms.some((s) => s.toString().includes("IsDrizzleView"))) continue;
838
+ const cfg = getViewConfig(val);
839
+ const sqlName = cfg.name;
840
+ const modelName = exportName;
841
+ const typeName = capitalize(exportName);
842
+ const sqlToJsKey = /* @__PURE__ */ new Map();
843
+ const columns = /* @__PURE__ */ new Map();
844
+ for (const [jsKey, col] of Object.entries(cfg.selectedFields)) {
845
+ const colObj = col;
846
+ if (colObj.name && colObj.columnType) {
847
+ sqlToJsKey.set(colObj.name, jsKey);
848
+ columns.set(jsKey, colObj);
849
+ }
850
+ }
851
+ views.push({
852
+ exportName,
853
+ sqlName,
854
+ modelName,
855
+ typeName,
856
+ columns,
857
+ sqlToJsKey
858
+ });
859
+ }
860
+ return views;
861
+ }
862
+ __name(discoverViews, "discoverViews");
863
+ function extractFKs(table) {
864
+ const cfg = getTableConfig3(table);
865
+ return cfg.foreignKeys.map((fk) => {
866
+ const ref = fk.reference();
867
+ return {
868
+ name: fk.getName(),
869
+ localColumns: ref.columns.map((c) => c.name),
870
+ foreignTable: getDrizzleTableName(ref.foreignTable),
871
+ foreignColumns: ref.foreignColumns.map((c) => c.name)
872
+ };
873
+ });
874
+ }
875
+ __name(extractFKs, "extractFKs");
876
+
877
+ // src/codegen/relations.ts
878
+ function makePhysicalRelationSignature(fields, references, array) {
879
+ return [
880
+ array ? "many" : "one",
881
+ fields?.join(",") || "",
882
+ references?.join(",") || ""
883
+ ].join("|");
884
+ }
885
+ __name(makePhysicalRelationSignature, "makePhysicalRelationSignature");
886
+ function makePhysicalFKSignature(sourceTable, targetTable, fk) {
887
+ return makePhysicalRelationSignature(fk.localColumns.map((column) => sourceTable.sqlToJsKey.get(column) || column), fk.foreignColumns.map((column) => targetTable.sqlToJsKey.get(column) || column), false);
888
+ }
889
+ __name(makePhysicalFKSignature, "makePhysicalFKSignature");
890
+ function assertNoRelationFieldCollision(table, sourceRelations, fieldName) {
891
+ if (table.jsKeySet.has(fieldName)) {
892
+ throw new Error(`Relation "${table.exportName}.${fieldName}" collides with an existing field. Rename the FK key in tables.ts or choose a different relation key in relations.ts.`);
893
+ }
894
+ if (sourceRelations.some((relation) => relation.fieldName === fieldName)) {
895
+ throw new Error(`Relation "${table.exportName}.${fieldName}" collides with another relation field. Use a unique key in relations.ts.`);
896
+ }
897
+ }
898
+ __name(assertNoRelationFieldCollision, "assertNoRelationFieldCollision");
899
+ function unfoldThroughPath(path, relationNames = []) {
900
+ const entries = Object.entries(path);
901
+ if (entries.length !== 1) {
902
+ throw new Error("Through relation path must contain exactly one relation per level.");
903
+ }
904
+ const entry = entries[0];
905
+ const [relationName, next] = entry;
906
+ relationNames.push(relationName);
907
+ if (next === true) {
908
+ return relationNames;
909
+ }
910
+ return unfoldThroughPath(next, relationNames);
911
+ }
912
+ __name(unfoldThroughPath, "unfoldThroughPath");
913
+ function unfoldRelationSelector(relation) {
914
+ const entries = Object.entries(relation);
915
+ if (entries.length !== 1) {
916
+ throw new Error("Filtered relation selector must contain exactly one relation.");
917
+ }
918
+ const entry = entries[0];
919
+ const [relationName, enabled] = entry;
920
+ if (enabled !== true) {
921
+ throw new Error("Filtered relation selector values must be true.");
922
+ }
923
+ return relationName;
924
+ }
925
+ __name(unfoldRelationSelector, "unfoldRelationSelector");
926
+ function buildRelations(tables, relationTargets = {}, filteredRelations = {}, throughRelations = {}, fkRelations = {}) {
927
+ const baseTables = tables.filter((table) => !table.derivedFrom);
928
+ const sqlToBaseTable = /* @__PURE__ */ new Map();
929
+ const modelToTable = /* @__PURE__ */ new Map();
930
+ for (const table of tables) {
931
+ modelToTable.set(table.modelName, table);
932
+ if (!table.derivedFrom) {
933
+ sqlToBaseTable.set(table.sqlName, table);
934
+ }
935
+ }
936
+ const fksByTable = /* @__PURE__ */ new Map();
937
+ for (const table of baseTables) {
938
+ fksByTable.set(table.modelName, extractFKs(table.table));
939
+ }
940
+ const modelRelations = /* @__PURE__ */ new Map();
941
+ for (const table of tables) {
942
+ modelRelations.set(table.modelName, []);
943
+ }
944
+ for (const [modelName, relations] of Object.entries(fkRelations)) {
945
+ const sourceTable = modelToTable.get(modelName);
946
+ if (!sourceTable) continue;
947
+ const sourceRelations = modelRelations.get(modelName) || [];
948
+ const colByName = new Map(sourceTable.cfg.columns.map((column) => [
949
+ column.name,
950
+ column
951
+ ]));
952
+ for (const [relName, fkInfo] of Object.entries(relations)) {
953
+ const targetTable = modelToTable.get(fkInfo.targetExportName) ?? sqlToBaseTable.get(fkInfo.targetExportName);
954
+ if (!targetTable) continue;
955
+ const targetModelOverride = relationTargets[modelName]?.[relName];
956
+ const fieldName = relName;
957
+ assertNoRelationFieldCollision(sourceTable, sourceRelations, fieldName);
958
+ let hasDefaultFK = false;
959
+ let isOptional = false;
960
+ const jsToSql = new Map([
961
+ ...sourceTable.sqlToJsKey.entries()
962
+ ].map(([sql2, js]) => [
963
+ js,
964
+ sql2
965
+ ]));
966
+ for (const jsKey of fkInfo.fields) {
967
+ const sqlName = jsToSql.get(jsKey) ?? jsKey;
968
+ const localColumn = colByName.get(sqlName);
969
+ if (localColumn?.hasDefault) hasDefaultFK = true;
970
+ if (!localColumn?.notNull) isOptional = true;
971
+ }
972
+ sourceRelations.push({
973
+ fieldName,
974
+ targetModel: targetModelOverride ?? fkInfo.targetExportName,
975
+ optional: isOptional,
976
+ array: false,
977
+ relationName: fkInfo.relationName,
978
+ fields: fkInfo.fields,
979
+ references: fkInfo.references,
980
+ hasDefault: hasDefaultFK
981
+ });
982
+ }
983
+ modelRelations.set(modelName, sourceRelations);
984
+ }
985
+ for (const table of tables) {
986
+ if (!table.derivedFrom) continue;
987
+ const baseRelations = modelRelations.get(table.derivedFrom) || [];
988
+ modelRelations.set(table.modelName, baseRelations.map((relation) => ({
989
+ ...relation,
990
+ _opposite: void 0
991
+ })));
992
+ }
993
+ for (const table of baseTables) {
994
+ const sourceRelations = modelRelations.get(table.modelName) || [];
995
+ const relationsByTarget = /* @__PURE__ */ new Map();
996
+ for (const relation of sourceRelations) {
997
+ if (relation.kind && relation.kind !== "normal") continue;
998
+ const group = relationsByTarget.get(relation.targetModel) || [];
999
+ group.push(relation);
1000
+ relationsByTarget.set(relation.targetModel, group);
1001
+ }
1002
+ for (const [targetModel, relations] of relationsByTarget) {
1003
+ if (relations.length <= 1) continue;
1004
+ for (const relation of relations) {
1005
+ if (relation.relationName) continue;
1006
+ throw new Error(`Ambiguous relations for "${table.exportName}" -> "${targetModel}". Add explicit relationName values in supabase/schema/relations.ts.`);
1007
+ }
1008
+ }
1009
+ const declaredFKRelations = new Set(sourceRelations.filter((relation) => !relation.array && relation.fields && relation.references).map((relation) => makePhysicalRelationSignature(relation.fields, relation.references, relation.array)));
1010
+ for (const fk of fksByTable.get(table.modelName) || []) {
1011
+ const targetTable = sqlToBaseTable.get(fk.foreignTable);
1012
+ if (!targetTable) continue;
1013
+ const signature = makePhysicalFKSignature(table, targetTable, fk);
1014
+ if (declaredFKRelations.has(signature)) continue;
1015
+ throw new Error(`Missing explicit relation in supabase/schema/relations.ts for "${table.exportName}": [${fk.localColumns.join(", ")}] -> ${targetTable.exportName}([${fk.foreignColumns.join(", ")}]).`);
1016
+ }
1017
+ }
1018
+ const forwardByTarget = /* @__PURE__ */ new Map();
1019
+ for (const sourceTable of tables) {
1020
+ for (const relation of modelRelations.get(sourceTable.modelName) || []) {
1021
+ if (relation.kind && relation.kind !== "normal") continue;
1022
+ const group = forwardByTarget.get(relation.targetModel) || [];
1023
+ group.push({
1024
+ source: sourceTable,
1025
+ relation
1026
+ });
1027
+ forwardByTarget.set(relation.targetModel, group);
1028
+ }
1029
+ }
1030
+ const inverseRelations = /* @__PURE__ */ new Map();
1031
+ for (const table of tables) {
1032
+ const inverses = [];
1033
+ const existingNames = new Set((modelRelations.get(table.modelName) || []).map((relation) => relation.fieldName));
1034
+ for (const { source: sourceTable, relation } of forwardByTarget.get(table.modelName) || []) {
1035
+ const sourceExport = sourceTable.exportName || sourceTable.sqlName;
1036
+ let fieldName = sourceExport.endsWith("s") ? sourceExport : sourceExport + "s";
1037
+ if (existingNames.has(fieldName)) {
1038
+ const explicitRelation = (modelRelations.get(table.modelName) || []).find((item) => item.fieldName === fieldName);
1039
+ if (explicitRelation) {
1040
+ relation._opposite = fieldName;
1041
+ continue;
1042
+ }
1043
+ const mainField = relation.fields?.find((field) => field !== APP_SLUG_JS) || relation.fields?.[0] || relation.fieldName;
1044
+ fieldName = sourceExport + "By" + capitalize(mainField);
1045
+ }
1046
+ inverses.push({
1047
+ fieldName,
1048
+ targetModel: sourceTable.modelName,
1049
+ optional: false,
1050
+ array: true,
1051
+ relationName: relation.relationName,
1052
+ fields: null,
1053
+ references: null,
1054
+ hasDefault: false,
1055
+ _opposite: relation.fieldName
1056
+ });
1057
+ relation._opposite = fieldName;
1058
+ existingNames.add(fieldName);
1059
+ }
1060
+ inverseRelations.set(table.modelName, inverses);
1061
+ }
1062
+ const getAvailableRelations = /* @__PURE__ */ __name((modelName) => [
1063
+ ...modelRelations.get(modelName) || [],
1064
+ ...inverseRelations.get(modelName) || []
1065
+ ], "getAvailableRelations");
1066
+ for (const [modelName, declarations] of Object.entries(filteredRelations)) {
1067
+ const sourceTable = modelToTable.get(modelName);
1068
+ if (!sourceTable) {
1069
+ throw new Error(`Filtered relations declared for unknown model "${modelName}".`);
1070
+ }
1071
+ const sourceRelations = modelRelations.get(modelName) || [];
1072
+ const availableRelations = getAvailableRelations(modelName);
1073
+ for (const [fieldName, declaration] of Object.entries(declarations)) {
1074
+ const sourceRelation = unfoldRelationSelector(declaration.relation);
1075
+ const existingFk = sourceRelations.find((r) => r.fieldName === fieldName);
1076
+ if (existingFk && sourceRelation === fieldName) {
1077
+ existingFk.kind = "filtered";
1078
+ existingFk.sourceRelation = sourceRelation;
1079
+ existingFk.where = declaration.where;
1080
+ existingFk.single = declaration.single;
1081
+ continue;
1082
+ }
1083
+ assertNoRelationFieldCollision(sourceTable, [
1084
+ ...sourceRelations,
1085
+ ...inverseRelations.get(modelName) || []
1086
+ ], fieldName);
1087
+ const baseRelation = availableRelations.find((relation) => relation.fieldName === sourceRelation);
1088
+ if (!baseRelation) {
1089
+ throw new Error(`Filtered relation "${modelName}.${fieldName}" references unknown relation "${sourceRelation}".`);
1090
+ }
1091
+ sourceRelations.push({
1092
+ fieldName,
1093
+ targetModel: baseRelation.targetModel,
1094
+ optional: declaration.single ? true : baseRelation.optional,
1095
+ array: declaration.single ? false : baseRelation.array,
1096
+ relationName: null,
1097
+ fields: baseRelation.fields,
1098
+ references: baseRelation.references,
1099
+ hasDefault: false,
1100
+ kind: "filtered",
1101
+ sourceRelation,
1102
+ where: declaration.where,
1103
+ single: declaration.single
1104
+ });
1105
+ }
1106
+ modelRelations.set(modelName, sourceRelations);
1107
+ }
1108
+ for (const [modelName, declarations] of Object.entries(throughRelations)) {
1109
+ const sourceTable = modelToTable.get(modelName);
1110
+ if (!sourceTable) {
1111
+ throw new Error(`Through relations declared for unknown model "${modelName}".`);
1112
+ }
1113
+ const sourceRelations = modelRelations.get(modelName) || [];
1114
+ for (const [fieldName, declaration] of Object.entries(declarations)) {
1115
+ assertNoRelationFieldCollision(sourceTable, [
1116
+ ...sourceRelations,
1117
+ ...inverseRelations.get(modelName) || []
1118
+ ], fieldName);
1119
+ const throughPath = unfoldThroughPath(declaration.path);
1120
+ let currentModel = modelName;
1121
+ let targetRelation;
1122
+ let isMany = false;
1123
+ for (const relationName of throughPath) {
1124
+ const relation = getAvailableRelations(currentModel).find((item) => item.fieldName === relationName);
1125
+ if (!relation) {
1126
+ throw new Error(`Through relation "${modelName}.${fieldName}" references unknown relation "${currentModel}.${relationName}".`);
1127
+ }
1128
+ targetRelation = relation;
1129
+ currentModel = relation.targetModel;
1130
+ if (relation.array) {
1131
+ isMany = true;
1132
+ }
1133
+ }
1134
+ if (!targetRelation) {
1135
+ throw new Error(`Through relation "${modelName}.${fieldName}" is missing a target path.`);
1136
+ }
1137
+ sourceRelations.push({
1138
+ fieldName,
1139
+ targetModel: targetRelation.targetModel,
1140
+ optional: !isMany,
1141
+ array: isMany,
1142
+ relationName: null,
1143
+ fields: null,
1144
+ references: null,
1145
+ hasDefault: false,
1146
+ kind: "through",
1147
+ throughPath
1148
+ });
1149
+ }
1150
+ modelRelations.set(modelName, sourceRelations);
1151
+ }
1152
+ return {
1153
+ modelRelations,
1154
+ inverseRelations
1155
+ };
1156
+ }
1157
+ __name(buildRelations, "buildRelations");
1158
+
1159
+ // src/codegen/typed-json.ts
1160
+ import { toCamelCase } from "drizzle-orm/casing";
1161
+ import { ModuleKind, ModuleResolutionKind, Project, ScriptTarget as ScriptTarget2, SyntaxKind } from "ts-morph";
1162
+ function unwrapNullableType(type) {
1163
+ if (!type.isUnion()) return type;
1164
+ const nonNull = type.getUnionTypes().filter((member) => !member.isNull() && !member.isUndefined());
1165
+ if (nonNull.length !== 1) return type;
1166
+ return unwrapNullableType(nonNull[0]);
1167
+ }
1168
+ __name(unwrapNullableType, "unwrapNullableType");
1169
+ function getResolvedArrayInfo(type) {
1170
+ const resolvedType = unwrapNullableType(type);
1171
+ if (!resolvedType.isArray()) {
1172
+ return {
1173
+ resolvedType,
1174
+ isArray: false
1175
+ };
1176
+ }
1177
+ return {
1178
+ resolvedType: resolvedType.getArrayElementTypeOrThrow(),
1179
+ isArray: true
1180
+ };
1181
+ }
1182
+ __name(getResolvedArrayInfo, "getResolvedArrayInfo");
1183
+ function normalizeTypeText(typeText) {
1184
+ let normalized = typeText.replace(/\s+/g, " ").trim();
1185
+ normalized = normalized.replace(/\s*\|\s*(?:null|undefined)\s*$/g, "").trim();
1186
+ let isArray = false;
1187
+ if (normalized.endsWith("[]")) {
1188
+ normalized = normalized.slice(0, -2).trim();
1189
+ isArray = true;
1190
+ }
1191
+ if (normalized.startsWith("(") && normalized.endsWith(")")) {
1192
+ normalized = normalized.slice(1, -1).trim();
1193
+ }
1194
+ return {
1195
+ baseText: normalized,
1196
+ isArray
1197
+ };
1198
+ }
1199
+ __name(normalizeTypeText, "normalizeTypeText");
1200
+ function buildTypeDefs(typesPath, tables, views, enumMap) {
1201
+ const project = createTypedJsonProject(typesPath, !!views?.length);
1202
+ const sf = project.getSourceFileOrThrow(typesPath);
1203
+ const typeDefs = /* @__PURE__ */ new Map();
1204
+ const fieldToTypeDef = /* @__PURE__ */ new Map();
1205
+ const typedJsonFieldMap = /* @__PURE__ */ new Map();
1206
+ const exportedTypes = createExportedTypeRegistry(sf);
1207
+ const entityBySqlName = /* @__PURE__ */ new Map();
1208
+ for (const table of tables) entityBySqlName.set(table.sqlName, table);
1209
+ for (const view of views || []) entityBySqlName.set(view.sqlName, view);
1210
+ const tableByExportName = new Map(tables.map((table) => [
1211
+ table.exportName,
1212
+ table
1213
+ ]));
1214
+ const sourceFiles = [
1215
+ "supabase/schema/tables.ts"
1216
+ ];
1217
+ if (views?.length) sourceFiles.push("supabase/schema/views.ts");
1218
+ for (const filePath of sourceFiles) {
1219
+ scanFileForTypedColumns({
1220
+ sourceFile: project.getSourceFileOrThrow(filePath),
1221
+ exportedTypes,
1222
+ typeDefs,
1223
+ fieldToTypeDef,
1224
+ typedJsonFieldMap,
1225
+ entityBySqlName,
1226
+ tableByExportName,
1227
+ enumMap: enumMap || /* @__PURE__ */ new Map()
1228
+ });
1229
+ }
1230
+ return {
1231
+ typeDefs,
1232
+ fieldToTypeDef,
1233
+ typedJsonFields: sortTypedJsonFields([
1234
+ ...typedJsonFieldMap.values()
1235
+ ])
1236
+ };
1237
+ }
1238
+ __name(buildTypeDefs, "buildTypeDefs");
1239
+ function createExportedTypeRegistry(sourceFile) {
1240
+ const declarations = /* @__PURE__ */ new Map();
1241
+ const resolvedTypes = /* @__PURE__ */ new Map();
1242
+ for (const stmt of sourceFile.getStatements()) {
1243
+ if (stmt.getKind() === SyntaxKind.TypeAliasDeclaration) {
1244
+ const typeAlias = stmt.asKindOrThrow(SyntaxKind.TypeAliasDeclaration);
1245
+ if (typeAlias.isExported()) {
1246
+ declarations.set(typeAlias.getName(), typeAlias);
1247
+ }
1248
+ }
1249
+ if (stmt.getKind() === SyntaxKind.InterfaceDeclaration) {
1250
+ const iface = stmt.asKindOrThrow(SyntaxKind.InterfaceDeclaration);
1251
+ if (iface.isExported()) {
1252
+ declarations.set(iface.getName(), iface);
1253
+ }
1254
+ }
1255
+ }
1256
+ return {
1257
+ has(name) {
1258
+ return declarations.has(name);
1259
+ },
1260
+ get(name) {
1261
+ if (!declarations.has(name)) return void 0;
1262
+ const cachedType = resolvedTypes.get(name);
1263
+ if (cachedType) return cachedType;
1264
+ const declaration = declarations.get(name);
1265
+ if (!declaration) return void 0;
1266
+ const resolvedType = declaration.getType();
1267
+ resolvedTypes.set(name, resolvedType);
1268
+ return resolvedType;
1269
+ }
1270
+ };
1271
+ }
1272
+ __name(createExportedTypeRegistry, "createExportedTypeRegistry");
1273
+ function createTypedJsonProject(typesPath, includeViews) {
1274
+ const project = new Project({
1275
+ skipAddingFilesFromTsConfig: true,
1276
+ compilerOptions: {
1277
+ module: ModuleKind.ESNext,
1278
+ moduleResolution: ModuleResolutionKind.Bundler,
1279
+ target: ScriptTarget2.ES2022,
1280
+ allowJs: false,
1281
+ baseUrl: ".",
1282
+ paths: {
1283
+ "@/*": [
1284
+ "src/*"
1285
+ ],
1286
+ "~/*": [
1287
+ "app/*"
1288
+ ]
1289
+ }
1290
+ }
1291
+ });
1292
+ project.addSourceFileAtPath(typesPath);
1293
+ project.addSourceFileAtPath("supabase/schema/tables.ts");
1294
+ if (includeViews) {
1295
+ project.addSourceFileAtPath("supabase/schema/views.ts");
1296
+ }
1297
+ return project;
1298
+ }
1299
+ __name(createTypedJsonProject, "createTypedJsonProject");
1300
+ function scanFileForTypedColumns({ sourceFile, exportedTypes, typeDefs, fieldToTypeDef, typedJsonFieldMap, entityBySqlName, tableByExportName, enumMap }) {
1301
+ const registerTypedJsonField = /* @__PURE__ */ __name((entitySqlName, columnSqlName, typeDefName, isArray, sourceTypeName) => {
1302
+ const entity = entityBySqlName.get(entitySqlName);
1303
+ if (!entity) return;
1304
+ const fieldName = entity.sqlToJsKey.get(columnSqlName) || columnSqlName;
1305
+ const fieldKey = `${entitySqlName}.${fieldName}`;
1306
+ fieldToTypeDef.set(fieldKey, {
1307
+ typeDefName,
1308
+ isArray
1309
+ });
1310
+ typedJsonFieldMap.set(fieldKey, {
1311
+ entitySqlName,
1312
+ entityTypeName: entity.typeName,
1313
+ fieldName,
1314
+ typeDefName,
1315
+ isArray,
1316
+ sourceTypeName
1317
+ });
1318
+ }, "registerTypedJsonField");
1319
+ for (const access of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression)) {
1320
+ if (access.getName() !== "$type") continue;
1321
+ const call = access.getParentIfKind(SyntaxKind.CallExpression);
1322
+ if (!call || call.getExpression() !== access) continue;
1323
+ const typeArg = call.getTypeArguments()[0];
1324
+ if (!typeArg) continue;
1325
+ const propertyAssignment = call.getFirstAncestorByKind(SyntaxKind.PropertyAssignment);
1326
+ if (!propertyAssignment) continue;
1327
+ const columnSqlName = propertyAssignment.getName();
1328
+ const entitySqlName = getEntitySqlName(call);
1329
+ if (!entitySqlName) continue;
1330
+ const rawTypeText = typeArg.getText().trim();
1331
+ const { baseText, isArray: isArrayFromText } = normalizeTypeText(rawTypeText);
1332
+ const rowTypeDefName = resolveWholeRowTypeDefName(baseText, tableByExportName, typeDefs, enumMap);
1333
+ if (rowTypeDefName) {
1334
+ const isArray2 = isArrayFromText || getResolvedArrayInfo(typeArg.getType()).isArray;
1335
+ registerTypedJsonField(entitySqlName, columnSqlName, rowTypeDefName, isArray2);
1336
+ continue;
1337
+ }
1338
+ if (exportedTypes.has(baseText)) {
1339
+ const type = exportedTypes.get(baseText);
1340
+ if (type && tryBuildTypeDef(baseText, type, typeDefs, exportedTypes)) {
1341
+ const isArray2 = isArrayFromText || getResolvedArrayInfo(type).isArray;
1342
+ registerTypedJsonField(entitySqlName, columnSqlName, baseText, isArray2, baseText);
1343
+ }
1344
+ continue;
1345
+ }
1346
+ const { resolvedType, isArray: isArrayFromType } = getResolvedArrayInfo(typeArg.getType());
1347
+ const isArray = isArrayFromType || isArrayFromText;
1348
+ const generatedName = `${toPascalCase(entitySqlName)}${toPascalCase(columnSqlName)}`;
1349
+ if (tryBuildTypeDef(generatedName, resolvedType, typeDefs, exportedTypes)) {
1350
+ registerTypedJsonField(entitySqlName, columnSqlName, generatedName, isArray);
1351
+ }
1352
+ }
1353
+ }
1354
+ __name(scanFileForTypedColumns, "scanFileForTypedColumns");
1355
+ function getEntitySqlName(call) {
1356
+ let node = call.getParent();
1357
+ while (node) {
1358
+ if (node.getKind() === SyntaxKind.CallExpression) {
1359
+ const candidate = node.asKindOrThrow(SyntaxKind.CallExpression);
1360
+ const callee = candidate.getExpression().getText();
1361
+ if (callee === "pgTable" || callee === "pgView") {
1362
+ const firstArg = candidate.getArguments()[0];
1363
+ return firstArg ? firstArg.getText().replace(/['"]/g, "") : null;
1364
+ }
1365
+ }
1366
+ node = node.getParent();
1367
+ }
1368
+ return null;
1369
+ }
1370
+ __name(getEntitySqlName, "getEntitySqlName");
1371
+ function resolveWholeRowTypeDefName(typeText, tableByExportName, typeDefs, enumMap) {
1372
+ const wholeRowMatch = typeText.match(/^typeof\s+(?:t\.)?(\w+)\.\$infer(?:Select|Insert)$/);
1373
+ if (!wholeRowMatch) return null;
1374
+ const refTable = tableByExportName.get(wholeRowMatch[1]);
1375
+ if (!refTable) return null;
1376
+ const rowTypeDefName = `${refTable.typeName}Row`;
1377
+ if (!typeDefs.has(rowTypeDefName)) {
1378
+ buildRowTypeDef(rowTypeDefName, refTable, typeDefs, enumMap);
1379
+ }
1380
+ return typeDefs.has(rowTypeDefName) ? rowTypeDefName : null;
1381
+ }
1382
+ __name(resolveWholeRowTypeDefName, "resolveWholeRowTypeDefName");
1383
+ function buildRowTypeDef(name, table, typeDefs, enumMap) {
1384
+ const fields = {};
1385
+ for (const jsKey of [
1386
+ ...table.sqlToJsKey.values()
1387
+ ]) {
1388
+ const col = table.table[jsKey];
1389
+ if (!col?.columnType) continue;
1390
+ const mapped = mapColumn(jsKey, col, enumMap);
1391
+ if (mapped.isGenerated) continue;
1392
+ if (mapped.sqlName === "$hash") continue;
1393
+ let type;
1394
+ switch (mapped.type) {
1395
+ case "String":
1396
+ case "Int":
1397
+ case "Float":
1398
+ case "Boolean":
1399
+ case "DateTime":
1400
+ case "Json":
1401
+ type = mapped.type;
1402
+ break;
1403
+ case "BigInt":
1404
+ type = "Int";
1405
+ break;
1406
+ case "Decimal":
1407
+ type = "Float";
1408
+ break;
1409
+ default:
1410
+ type = "String";
1411
+ break;
1412
+ }
1413
+ const fieldName = toCamelCase(mapped.name);
1414
+ fields[fieldName] = {
1415
+ name: fieldName,
1416
+ ...fieldName !== mapped.name && {
1417
+ rawName: mapped.name
1418
+ },
1419
+ type,
1420
+ ...mapped.optional && {
1421
+ optional: true
1422
+ },
1423
+ ...mapped.array && {
1424
+ array: true
1425
+ }
1426
+ };
1427
+ }
1428
+ if (Object.keys(fields).length > 0) {
1429
+ typeDefs.set(name, {
1430
+ name,
1431
+ fields
1432
+ });
1433
+ }
1434
+ }
1435
+ __name(buildRowTypeDef, "buildRowTypeDef");
1436
+ function tryBuildTypeDef(name, type, typeDefs, exportedTypes) {
1437
+ if (typeDefs.has(name)) return true;
1438
+ if (type.isArray()) {
1439
+ return tryBuildTypeDef(name, type.getArrayElementTypeOrThrow(), typeDefs, exportedTypes);
1440
+ }
1441
+ if (type.isUnion()) {
1442
+ const nonNull = type.getUnionTypes().filter((member) => !member.isNull() && !member.isUndefined());
1443
+ if (nonNull.length === 1) {
1444
+ return tryBuildTypeDef(name, nonNull[0], typeDefs, exportedTypes);
1445
+ }
1446
+ return false;
1447
+ }
1448
+ if (!type.isObject() || type.getProperties().length === 0) return false;
1449
+ if (type.getStringIndexType()) return false;
1450
+ if (type.getCallSignatures().length > 0) return false;
1451
+ const fields = {};
1452
+ for (const prop of type.getProperties()) {
1453
+ const propName = prop.getName();
1454
+ const declaration = prop.getValueDeclaration();
1455
+ if (!declaration) continue;
1456
+ const propType = prop.getTypeAtLocation(declaration);
1457
+ const fieldName = toCamelCase(propName);
1458
+ const mappedField = mapTypeToTypeDef(propName, propType, name, typeDefs, exportedTypes);
1459
+ fields[fieldName] = {
1460
+ name: fieldName,
1461
+ ...fieldName !== propName && {
1462
+ rawName: propName
1463
+ },
1464
+ type: mappedField?.type || "Json",
1465
+ ...prop.isOptional() && {
1466
+ optional: true
1467
+ },
1468
+ ...mappedField?.isArray && {
1469
+ array: true
1470
+ }
1471
+ };
1472
+ }
1473
+ if (Object.keys(fields).length === 0) return false;
1474
+ typeDefs.set(name, {
1475
+ name,
1476
+ fields
1477
+ });
1478
+ return true;
1479
+ }
1480
+ __name(tryBuildTypeDef, "tryBuildTypeDef");
1481
+ function mapTypeToTypeDef(fieldName, type, parentName, typeDefs, exportedTypes) {
1482
+ if (type.isUnion()) {
1483
+ const unwrapped = unwrapNullableType(type);
1484
+ if (unwrapped !== type) {
1485
+ return mapTypeToTypeDef(fieldName, unwrapped, parentName, typeDefs, exportedTypes);
1486
+ }
1487
+ const nonNull = type.getUnionTypes().filter((member) => !member.isNull() && !member.isUndefined());
1488
+ if (nonNull.every((member) => member.isStringLiteral() || member.isString())) {
1489
+ return {
1490
+ type: "String",
1491
+ isArray: false
1492
+ };
1493
+ }
1494
+ if (nonNull.every((member) => member.isNumberLiteral() || member.isNumber())) {
1495
+ return {
1496
+ type: "Float",
1497
+ isArray: false
1498
+ };
1499
+ }
1500
+ if (nonNull.every((member) => member.isBooleanLiteral() || member.isBoolean())) {
1501
+ return {
1502
+ type: "Boolean",
1503
+ isArray: false
1504
+ };
1505
+ }
1506
+ return null;
1507
+ }
1508
+ if (type.isString() || type.isStringLiteral()) return {
1509
+ type: "String",
1510
+ isArray: false
1511
+ };
1512
+ if (type.isNumber() || type.isNumberLiteral()) return {
1513
+ type: "Float",
1514
+ isArray: false
1515
+ };
1516
+ if (type.isBoolean() || type.isBooleanLiteral()) return {
1517
+ type: "Boolean",
1518
+ isArray: false
1519
+ };
1520
+ if (type.getSymbol()?.getName() === "Date") return {
1521
+ type: "DateTime",
1522
+ isArray: false
1523
+ };
1524
+ if (type.isArray()) {
1525
+ const inner = mapTypeToTypeDef(fieldName, type.getArrayElementTypeOrThrow(), parentName, typeDefs, exportedTypes);
1526
+ return inner ? {
1527
+ type: inner.type,
1528
+ isArray: true
1529
+ } : null;
1530
+ }
1531
+ if (type.isObject() && type.getProperties().length > 0) {
1532
+ if (type.getStringIndexType()) return {
1533
+ type: "Json",
1534
+ isArray: false
1535
+ };
1536
+ if (type.getCallSignatures().length > 0) return null;
1537
+ const symbol = type.getAliasSymbol() || type.getSymbol();
1538
+ const knownName = symbol?.getName();
1539
+ if (knownName && exportedTypes.has(knownName)) {
1540
+ if (tryBuildTypeDef(knownName, type, typeDefs, exportedTypes)) {
1541
+ return {
1542
+ type: knownName,
1543
+ isArray: false
1544
+ };
1545
+ }
1546
+ }
1547
+ const subTypeDefName = `${parentName}${toPascalCase(fieldName)}`;
1548
+ if (tryBuildTypeDef(subTypeDefName, type, typeDefs, exportedTypes)) {
1549
+ return {
1550
+ type: subTypeDefName,
1551
+ isArray: false
1552
+ };
1553
+ }
1554
+ }
1555
+ return null;
1556
+ }
1557
+ __name(mapTypeToTypeDef, "mapTypeToTypeDef");
1558
+ function emitTypeDefsBlock(typeDefs) {
1559
+ if (typeDefs.size === 0) return "";
1560
+ const lines = [];
1561
+ lines.push(" typeDefs = {");
1562
+ for (const [name, typeDef] of sortTypeDefs(typeDefs)) {
1563
+ lines.push(` ${name}: {`);
1564
+ lines.push(` name: ${esc(typeDef.name)},`);
1565
+ lines.push(` fields: {`);
1566
+ for (const field of Object.values(typeDef.fields)) {
1567
+ const parts = [
1568
+ `name: ${esc(field.name)}`,
1569
+ `type: ${esc(field.type)}`
1570
+ ];
1571
+ if (field.optional) parts.push("optional: true");
1572
+ if (field.array) parts.push("array: true");
1573
+ if (field.rawName && field.rawName !== field.name) {
1574
+ parts.push(`attributes: [{ name: "@map", args: [{ name: "name", value: ExpressionUtils.literal(${esc(field.rawName)}) }] }]`);
1575
+ }
1576
+ lines.push(` ${field.name}: { ${parts.join(", ")} },`);
1577
+ }
1578
+ lines.push(" }");
1579
+ lines.push(" },");
1580
+ }
1581
+ lines.push(" } as const;");
1582
+ return lines.join("\n");
1583
+ }
1584
+ __name(emitTypeDefsBlock, "emitTypeDefsBlock");
1585
+ function mapTypeDefFieldToTs(field, typeDefs) {
1586
+ let tsType;
1587
+ switch (field.type) {
1588
+ case "String":
1589
+ tsType = "string";
1590
+ break;
1591
+ case "Int":
1592
+ case "Float":
1593
+ tsType = "number";
1594
+ break;
1595
+ case "Boolean":
1596
+ tsType = "boolean";
1597
+ break;
1598
+ case "DateTime":
1599
+ tsType = "Date";
1600
+ break;
1601
+ case "Json":
1602
+ tsType = "unknown";
1603
+ break;
1604
+ default:
1605
+ tsType = typeDefs.has(field.type) ? `${field.type}JsonShape` : "unknown";
1606
+ break;
1607
+ }
1608
+ return field.array ? `${tsType}[]` : tsType;
1609
+ }
1610
+ __name(mapTypeDefFieldToTs, "mapTypeDefFieldToTs");
1611
+ function getJsonFieldAlias(info) {
1612
+ return `${info.entityTypeName}${toPascalCase(info.fieldName)}Json`;
1613
+ }
1614
+ __name(getJsonFieldAlias, "getJsonFieldAlias");
1615
+ function getJsonRawFieldAlias(info) {
1616
+ return `${getJsonFieldAlias(info)}Raw`;
1617
+ }
1618
+ __name(getJsonRawFieldAlias, "getJsonRawFieldAlias");
1619
+ function emitJsonNamespaceBlock(typeDefs, typedJsonFields, indent = "") {
1620
+ const out = [];
1621
+ for (const [name, typeDef] of sortTypeDefs(typeDefs)) {
1622
+ out.push(`${indent}export type ${name}JsonShape = {`);
1623
+ for (const field of Object.values(typeDef.fields)) {
1624
+ const optional = field.optional ? "?" : "";
1625
+ out.push(`${indent} ${field.name}${optional}: ${mapTypeDefFieldToTs(field, typeDefs)};`);
1626
+ }
1627
+ out.push(`${indent}};`);
1628
+ out.push("");
1629
+ }
1630
+ for (const info of typedJsonFields) {
1631
+ out.push(`${indent}export type ${getJsonFieldAlias(info)} = ${info.typeDefName}JsonShape;`);
1632
+ out.push("");
1633
+ }
1634
+ if (out.at(-1) === "") {
1635
+ out.pop();
1636
+ }
1637
+ return out;
1638
+ }
1639
+ __name(emitJsonNamespaceBlock, "emitJsonNamespaceBlock");
1640
+ function emitJsonRawNamespaceBlock(typedJsonFields, indent = "") {
1641
+ const out = [];
1642
+ for (const info of typedJsonFields.filter((field) => field.sourceTypeName)) {
1643
+ out.push(`${indent}export type ${getJsonRawFieldAlias(info)} = RawJson.${info.sourceTypeName};`);
1644
+ out.push("");
1645
+ }
1646
+ if (out.at(-1) === "") {
1647
+ out.pop();
1648
+ }
1649
+ return out;
1650
+ }
1651
+ __name(emitJsonRawNamespaceBlock, "emitJsonRawNamespaceBlock");
1652
+ function emitJsonTs(typeDefs, typedJsonFields) {
1653
+ const out = [
1654
+ ...emitGeneratedFileBanner(),
1655
+ ""
1656
+ ];
1657
+ out.push(...emitJsonNamespaceBlock(typeDefs, typedJsonFields));
1658
+ out.push("");
1659
+ return out.join("\n");
1660
+ }
1661
+ __name(emitJsonTs, "emitJsonTs");
1662
+ function emitJsonRawTs(typedJsonFields) {
1663
+ const out = [
1664
+ ...emitGeneratedFileBanner(),
1665
+ "",
1666
+ 'import type * as RawJson from "../../supabase/schema/types";',
1667
+ ""
1668
+ ];
1669
+ out.push(...emitJsonRawNamespaceBlock(typedJsonFields));
1670
+ out.push("");
1671
+ return out.join("\n");
1672
+ }
1673
+ __name(emitJsonRawTs, "emitJsonRawTs");
1674
+ function sortTypeDefs(typeDefs) {
1675
+ return [
1676
+ ...typeDefs.entries()
1677
+ ].sort(([left], [right]) => left.localeCompare(right));
1678
+ }
1679
+ __name(sortTypeDefs, "sortTypeDefs");
1680
+ function sortTypedJsonFields(typedJsonFields) {
1681
+ return [
1682
+ ...typedJsonFields
1683
+ ].sort((left, right) => {
1684
+ const leftKey = `${getJsonFieldAlias(left)}:${left.sourceTypeName || ""}`;
1685
+ const rightKey = `${getJsonFieldAlias(right)}:${right.sourceTypeName || ""}`;
1686
+ return leftKey.localeCompare(rightKey);
1687
+ });
1688
+ }
1689
+ __name(sortTypedJsonFields, "sortTypedJsonFields");
1690
+
1691
+ // src/codegen/emit.ts
1692
+ var DB_ATTR_RE = /@db\.(\w+)(?:\((\d+)\))?/;
1693
+ function buildDerivedEnumName(modelName, fieldName) {
1694
+ return `${toPascalCase(modelName)}${toPascalCase(fieldName)}`;
1695
+ }
1696
+ __name(buildDerivedEnumName, "buildDerivedEnumName");
1697
+ function inferFieldIsNonNull(defaultWhere, fieldName) {
1698
+ if (!defaultWhere) return false;
1699
+ const condition = defaultWhere[fieldName];
1700
+ if (condition === void 0 || condition === null) return false;
1701
+ if (Array.isArray(condition)) return condition.length > 0;
1702
+ if (typeof condition !== "object") return true;
1703
+ if (Object.prototype.hasOwnProperty.call(condition, "not") && Reflect.get(condition, "not") === null) {
1704
+ return true;
1705
+ }
1706
+ if (Object.prototype.hasOwnProperty.call(condition, "in")) {
1707
+ const values = Reflect.get(condition, "in");
1708
+ return Array.isArray(values) && values.length > 0;
1709
+ }
1710
+ return false;
1711
+ }
1712
+ __name(inferFieldIsNonNull, "inferFieldIsNonNull");
1713
+ function applyDerivedFieldOverrides(field, table) {
1714
+ if (!table.derivedFrom) return field;
1715
+ const narrowedValues = table.narrow?.[field.name];
1716
+ return {
1717
+ ...field,
1718
+ // Keep base enum type — narrowing is handled at runtime by derived-models plugin
1719
+ optional: narrowedValues && narrowedValues.length > 0 ? false : field.optional && !inferFieldIsNonNull(table.defaultWhere, field.name)
1720
+ };
1721
+ }
1722
+ __name(applyDerivedFieldOverrides, "applyDerivedFieldOverrides");
1723
+ function collectDerivedEnums(tables, enumMap) {
1724
+ const derivedEnums = /* @__PURE__ */ new Map();
1725
+ const tablesByModel = new Map(tables.map((table) => [
1726
+ table.modelName,
1727
+ table
1728
+ ]));
1729
+ for (const table of tables) {
1730
+ if (!table.derivedFrom || !table.narrow) continue;
1731
+ const baseTable = tablesByModel.get(table.derivedFrom);
1732
+ if (!baseTable) continue;
1733
+ const baseFields = /* @__PURE__ */ new Map();
1734
+ for (const jsKey of baseTable.sqlToJsKey.values()) {
1735
+ const column = baseTable.table[jsKey];
1736
+ const field = mapColumn(jsKey, column, enumMap);
1737
+ baseFields.set(field.name === "$hash" ? "hash" : field.name, field);
1738
+ }
1739
+ for (const [fieldName, narrowedValues] of Object.entries(table.narrow)) {
1740
+ if (!narrowedValues.length) continue;
1741
+ const baseField = baseFields.get(fieldName);
1742
+ if (!baseField) {
1743
+ throw new Error(`Unknown narrowed field "${table.modelName}.${fieldName}".`);
1744
+ }
1745
+ const baseEnum = [
1746
+ ...enumMap.values()
1747
+ ].find((info) => info.zenstackName === baseField.type);
1748
+ if (!baseEnum) {
1749
+ continue;
1750
+ }
1751
+ const values = narrowedValues.map((value) => String(value));
1752
+ for (const value of values) {
1753
+ if (!baseEnum.values.includes(value)) {
1754
+ throw new Error(`Invalid narrowed enum value "${value}" for "${table.modelName}.${fieldName}".`);
1755
+ }
1756
+ }
1757
+ const enumName = buildDerivedEnumName(table.modelName, fieldName);
1758
+ if (derivedEnums.has(enumName)) continue;
1759
+ const mapping = baseEnum.mapping ? Object.fromEntries(Object.entries(baseEnum.mapping).filter(([, value]) => values.includes(value))) : Object.fromEntries(values.map((value) => [
1760
+ toPascalCase(value).toUpperCase(),
1761
+ value
1762
+ ]));
1763
+ derivedEnums.set(enumName, {
1764
+ pgName: `$derived:${enumName}`,
1765
+ zenstackName: enumName,
1766
+ values,
1767
+ mapping,
1768
+ mappedName: null
1769
+ });
1770
+ }
1771
+ }
1772
+ return derivedEnums;
1773
+ }
1774
+ __name(collectDerivedEnums, "collectDerivedEnums");
1775
+ function emitEnumBlock(info) {
1776
+ const lines = [];
1777
+ lines.push(` ${info.zenstackName}: {`);
1778
+ lines.push(` name: ${esc(info.zenstackName)},`);
1779
+ const tuples = info.mapping ? (() => {
1780
+ const invertedMap = Object.fromEntries(Object.entries(info.mapping).map(([k, v]) => [
1781
+ v,
1782
+ k
1783
+ ]));
1784
+ return info.values.map((v) => {
1785
+ const key = invertedMap[v];
1786
+ if (!key) throw new Error(`Enum "${info.pgName}" value "${v}" not found in mapping.`);
1787
+ return [
1788
+ v,
1789
+ key
1790
+ ];
1791
+ });
1792
+ })() : info.values.map((v) => [
1793
+ v,
1794
+ v
1795
+ ]);
1796
+ const valuesEntries = tuples.map(([value]) => `${esc(value)}: ${esc(value)}`);
1797
+ lines.push(` values: { ${valuesEntries.join(", ")} },`);
1798
+ lines.push(` fields: {`);
1799
+ for (const [v] of tuples) {
1800
+ lines.push(` ${esc(v)}: { name: ${esc(v)} },`);
1801
+ }
1802
+ lines.push(` },`);
1803
+ const mappedName = info.mappedName === void 0 ? info.pgName : info.mappedName;
1804
+ if (mappedName) {
1805
+ lines.push(` attributes: [{ name: "@@map", args: [{ name: "name", value: ExpressionUtils.literal(${esc(mappedName)}) }] }]`);
1806
+ }
1807
+ lines.push(` }`);
1808
+ return lines.join("\n");
1809
+ }
1810
+ __name(emitEnumBlock, "emitEnumBlock");
1811
+ function emitFieldBlock(field) {
1812
+ const parts = [];
1813
+ parts.push(`name: ${esc(field.name)}`);
1814
+ parts.push(`type: ${esc(field.type)}`);
1815
+ if (field.optional) parts.push("optional: true");
1816
+ if (field.array) parts.push("array: true");
1817
+ if (field.id) parts.push("id: true");
1818
+ if (field.unique) parts.push("unique: true");
1819
+ const attrs = [];
1820
+ if (field.id) attrs.push('{ name: "@id" }');
1821
+ if (field.unique) attrs.push('{ name: "@unique" }');
1822
+ if (field.name !== field.sqlName) {
1823
+ attrs.push(`{ name: "@map", args: [{ name: "name", value: ExpressionUtils.literal(${esc(field.sqlName)}) }] }`);
1824
+ }
1825
+ for (const da of field.dbAttrs) {
1826
+ const match = da.match(DB_ATTR_RE);
1827
+ if (match) {
1828
+ const [, attrName, arg] = match;
1829
+ if (arg) {
1830
+ attrs.push(`{ name: "@db.${attrName}", args: [{ name: "x", value: ExpressionUtils.literal(${arg}) }] }`);
1831
+ } else {
1832
+ attrs.push(`{ name: "@db.${attrName}" }`);
1833
+ }
1834
+ }
1835
+ }
1836
+ if (field.defaultExpr) {
1837
+ const attrValue = field.defaultExpr === "[] as FieldDefault" ? 'ExpressionUtils.literal("[]")' : field.defaultExpr;
1838
+ attrs.push(`{ name: "@default", args: [{ name: "value", value: ${attrValue} }] }`);
1839
+ }
1840
+ if (field.isGenerated) {
1841
+ attrs.push('{ name: "@ignore" }');
1842
+ }
1843
+ if (field.isJsonColumn && field.type !== "Json") {
1844
+ attrs.push('{ name: "@json" }');
1845
+ }
1846
+ if (attrs.length > 0) {
1847
+ parts.push(`attributes: [${attrs.join(", ")}]`);
1848
+ }
1849
+ if (field.defaultExpr) {
1850
+ if (field.defaultExpr.startsWith("ExpressionUtils.literal(")) {
1851
+ const inner = field.defaultExpr.slice("ExpressionUtils.literal(".length, -1);
1852
+ parts.push(`default: ${inner}`);
1853
+ } else {
1854
+ parts.push(`default: ${field.defaultExpr}`);
1855
+ }
1856
+ }
1857
+ return `{ ${parts.join(", ")} }`;
1858
+ }
1859
+ __name(emitFieldBlock, "emitFieldBlock");
1860
+ function emitRelationField(rel, opposite) {
1861
+ const parts = [];
1862
+ parts.push(`name: ${esc(rel.fieldName)}`);
1863
+ parts.push(`type: ${esc(rel.targetModel)}`);
1864
+ if (rel.optional) parts.push("optional: true");
1865
+ if (rel.array) parts.push("array: true");
1866
+ const relParts = [];
1867
+ if (opposite) relParts.push(`opposite: ${esc(opposite)}`);
1868
+ if (rel.relationName) relParts.push(`name: ${esc(rel.relationName)}`);
1869
+ if (rel.fields) relParts.push(`fields: [${rel.fields.map((f) => esc(f)).join(", ")}]`);
1870
+ if (rel.references) relParts.push(`references: [${rel.references.map((r) => esc(r)).join(", ")}]`);
1871
+ if (rel.hasDefault) relParts.push("hasDefault: true");
1872
+ parts.push(`relation: { ${relParts.join(", ")} }`);
1873
+ const attrArgs = [];
1874
+ if (rel.relationName) {
1875
+ attrArgs.push(`{ name: "name", value: ExpressionUtils.literal(${esc(rel.relationName)}) }`);
1876
+ }
1877
+ if (rel.fields) {
1878
+ attrArgs.push(`{ name: "fields", value: ExpressionUtils.array("String", [${rel.fields.map((f) => `ExpressionUtils.field(${esc(f)})`).join(", ")}]) }`);
1879
+ }
1880
+ if (rel.references) {
1881
+ attrArgs.push(`{ name: "references", value: ExpressionUtils.array("String", [${rel.references.map((r) => `ExpressionUtils.field(${esc(r)})`).join(", ")}]) }`);
1882
+ }
1883
+ if (attrArgs.length > 0) {
1884
+ parts.push(`attributes: [{ name: "@relation", args: [${attrArgs.join(", ")}] }]`);
1885
+ }
1886
+ return `{ ${parts.join(", ")} }`;
1887
+ }
1888
+ __name(emitRelationField, "emitRelationField");
1889
+ function emitUnknownLiteral(value) {
1890
+ if (value === null) return "null";
1891
+ if (typeof value === "string") return esc(value);
1892
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1893
+ if (Array.isArray(value)) {
1894
+ return `[${value.map((item) => emitUnknownLiteral(item)).join(", ")}]`;
1895
+ }
1896
+ if (typeof value === "object") {
1897
+ return `{ ${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}: ${emitUnknownLiteral(item)}`).join(", ")} }`;
1898
+ }
1899
+ throw new Error(`Unsupported config literal: ${String(value)}`);
1900
+ }
1901
+ __name(emitUnknownLiteral, "emitUnknownLiteral");
1902
+ function emitPluginsBlock(modelRelations, searchDefaults, modelScopes) {
1903
+ const lines = [];
1904
+ lines.push(" plugins = {");
1905
+ lines.push(" virtualRelations: {");
1906
+ for (const [model2, relations] of modelRelations) {
1907
+ const virtualRelations = relations.filter((relation) => relation.kind && relation.kind !== "normal");
1908
+ if (virtualRelations.length === 0) continue;
1909
+ lines.push(` ${model2}: {`);
1910
+ for (const relation of virtualRelations) {
1911
+ const parts = [
1912
+ `kind: ${esc(relation.kind)}`,
1913
+ `targetModel: ${esc(relation.targetModel)}`
1914
+ ];
1915
+ if (relation.sourceRelation) {
1916
+ parts.push(`relation: ${esc(relation.sourceRelation)}`);
1917
+ }
1918
+ if (relation.throughPath) {
1919
+ parts.push(`path: [${relation.throughPath.map((segment) => esc(segment)).join(", ")}]`);
1920
+ }
1921
+ if (relation.where) {
1922
+ parts.push(`where: ${emitUnknownLiteral(relation.where)}`);
1923
+ }
1924
+ if (relation.single) {
1925
+ parts.push("single: true");
1926
+ }
1927
+ lines.push(` ${relation.fieldName}: { ${parts.join(", ")} },`);
1928
+ }
1929
+ lines.push(" },");
1930
+ }
1931
+ lines.push(" },");
1932
+ lines.push(" searchDefaults: {");
1933
+ for (const [model2, profiles] of Object.entries(searchDefaults)) {
1934
+ if (!profiles) continue;
1935
+ lines.push(` ${model2}: {`);
1936
+ for (const [profile, declaration] of Object.entries(profiles)) {
1937
+ const parts = [
1938
+ `fields: ${emitUnknownLiteral(declaration.fields)}`
1939
+ ];
1940
+ if (declaration.mode) {
1941
+ parts.push(`mode: ${esc(declaration.mode)}`);
1942
+ }
1943
+ if (declaration.strategy) {
1944
+ parts.push(`strategy: ${esc(declaration.strategy)}`);
1945
+ }
1946
+ lines.push(` ${profile}: { ${parts.join(", ")} },`);
1947
+ }
1948
+ lines.push(" },");
1949
+ }
1950
+ lines.push(" },");
1951
+ if (Object.keys(modelScopes).length > 0) {
1952
+ lines.push(" modelScopes: {");
1953
+ for (const [scopeModel, where] of Object.entries(modelScopes)) {
1954
+ lines.push(` ${scopeModel}: ${emitUnknownLiteral(where)},`);
1955
+ }
1956
+ lines.push(" },");
1957
+ }
1958
+ lines.push(" } as const;");
1959
+ return lines.join("\n");
1960
+ }
1961
+ __name(emitPluginsBlock, "emitPluginsBlock");
1962
+ function applyTypeDefOverride(field, fieldMapping) {
1963
+ if (!fieldMapping) return field;
1964
+ return {
1965
+ ...field,
1966
+ type: fieldMapping.typeDefName,
1967
+ array: fieldMapping.isArray || field.array,
1968
+ dbAttrs: field.dbAttrs.filter((attr) => !attr.startsWith("@db.Json"))
1969
+ };
1970
+ }
1971
+ __name(applyTypeDefOverride, "applyTypeDefOverride");
1972
+ function emitModelBlock(t, enumMap, modelRelations, inverseRelations, fieldToTypeDef) {
1973
+ const out = [];
1974
+ const { cfg } = t;
1975
+ const fields = [];
1976
+ const fieldByName = /* @__PURE__ */ new Map();
1977
+ for (const jsKey of [
1978
+ ...t.sqlToJsKey.values()
1979
+ ]) {
1980
+ const col = t.table[jsKey];
1981
+ const field = mapColumn(jsKey, col, enumMap);
1982
+ if (field.sqlName === "$hash") {
1983
+ field.isGenerated = true;
1984
+ field.name = "hash";
1985
+ }
1986
+ const typedField = applyDerivedFieldOverrides(applyTypeDefOverride(field, fieldToTypeDef?.get(`${t.sqlName}.${jsKey}`)), t);
1987
+ fields.push(typedField);
1988
+ fieldByName.set(typedField.name, typedField);
1989
+ }
1990
+ const fkRels = modelRelations.get(t.modelName) || [];
1991
+ const fkFieldMap = /* @__PURE__ */ new Map();
1992
+ for (const rel of fkRels) {
1993
+ if (rel.fields) {
1994
+ for (const f of rel.fields) {
1995
+ if (!fkFieldMap.has(f)) fkFieldMap.set(f, []);
1996
+ fkFieldMap.get(f).push(rel.fieldName);
1997
+ }
1998
+ }
1999
+ }
2000
+ out.push(` ${t.modelName}: {`);
2001
+ out.push(` name: ${esc(t.modelName)},`);
2002
+ out.push(` fields: {`);
2003
+ for (const field of fields) {
2004
+ const fkFor = fkFieldMap.get(field.name);
2005
+ let block = emitFieldBlock(field);
2006
+ if (fkFor) {
2007
+ block = block.slice(0, -2) + `, foreignKeyFor: [${fkFor.map((f) => esc(f)).join(", ")}] }`;
2008
+ }
2009
+ out.push(` ${field.name}: ${block},`);
2010
+ }
2011
+ for (const rel of fkRels) {
2012
+ const isVirtualOnly = rel.kind === "through" || rel.kind === "filtered" && !rel.fields;
2013
+ const opposite = isVirtualOnly ? "" : rel._opposite || rel.fieldName;
2014
+ const block = emitRelationField(rel, opposite);
2015
+ out.push(` ${rel.fieldName}: ${block},`);
2016
+ }
2017
+ const invRels = inverseRelations.get(t.modelName) || [];
2018
+ for (const rel of invRels) {
2019
+ const opposite = rel._opposite || rel.fieldName;
2020
+ const block = emitRelationField(rel, opposite);
2021
+ out.push(` ${rel.fieldName}: ${block},`);
2022
+ }
2023
+ for (const computedField of t.computedFields) {
2024
+ out.push(` ${computedField.name}: { name: ${esc(computedField.name)}, type: ${esc(computedField.type)}, computed: true, attributes: [{ name: "@computed" }] },`);
2025
+ }
2026
+ out.push(` },`);
2027
+ if (t.computedFields.length > 0) {
2028
+ out.push(` computedFields: {`);
2029
+ for (const computedField of t.computedFields) {
2030
+ out.push(` ${computedField.name}(_context: { modelAlias: ${esc(t.modelName)} }): ${computedField.tsType} { throw new Error("computed stub"); },`);
2031
+ }
2032
+ out.push(` },`);
2033
+ }
2034
+ const modelAttrs = [];
2035
+ modelAttrs.push(`{ name: "@@map", args: [{ name: "name", value: ExpressionUtils.literal(${esc(t.sqlName)}) }] }`);
2036
+ for (const uc of cfg.uniqueConstraints) {
2037
+ const ucCols = uc.columns.map((c) => c.name);
2038
+ if (ucCols.length > 1) {
2039
+ modelAttrs.push(`{ name: "@@unique", args: [{ name: "fields", value: ExpressionUtils.array("String", [${ucCols.map((c) => `ExpressionUtils.field(${esc(t.sqlToJsKey.get(c) || c)})`).join(", ")}]) }] }`);
2040
+ }
2041
+ }
2042
+ if (cfg.primaryKeys.length > 0) {
2043
+ for (const pk of cfg.primaryKeys) {
2044
+ const pkCols = pk.columns.map((c) => c.name);
2045
+ modelAttrs.push(`{ name: "@@id", args: [{ name: "fields", value: ExpressionUtils.array("String", [${pkCols.map((c) => `ExpressionUtils.field(${esc(t.sqlToJsKey.get(c) || c)})`).join(", ")}]) }] }`);
2046
+ }
2047
+ }
2048
+ out.push(` attributes: [${modelAttrs.join(", ")}],`);
2049
+ const idCols = cfg.columns.filter((c) => c.primary).map((c) => t.sqlToJsKey.get(c.name) || c.name);
2050
+ if (idCols.length === 0 && cfg.primaryKeys.length > 0) {
2051
+ const pkCols = cfg.primaryKeys[0].columns.map((c) => t.sqlToJsKey.get(c.name) || c.name);
2052
+ out.push(` idFields: [${pkCols.map((c) => esc(c)).join(", ")}],`);
2053
+ } else {
2054
+ out.push(` idFields: [${idCols.map((c) => esc(c)).join(", ")}],`);
2055
+ }
2056
+ const ufEntries = [];
2057
+ const ufKeys = /* @__PURE__ */ new Set();
2058
+ const addUnique = /* @__PURE__ */ __name((cols) => {
2059
+ const key = cols.join("_");
2060
+ if (ufKeys.has(key)) return;
2061
+ ufKeys.add(key);
2062
+ if (cols.length === 1) {
2063
+ ufEntries.push(`${key}: { type: ${esc(fieldByName.get(key)?.type || "String")} }`);
2064
+ } else {
2065
+ const inner = cols.map((c) => `${c}: { type: ${esc(fieldByName.get(c)?.type || "String")} }`).join(", ");
2066
+ ufEntries.push(`${key}: { ${inner} }`);
2067
+ }
2068
+ }, "addUnique");
2069
+ if (idCols.length > 0) {
2070
+ addUnique(idCols);
2071
+ } else if (cfg.primaryKeys.length > 0) {
2072
+ const pkCols = cfg.primaryKeys[0].columns.map((c) => t.sqlToJsKey.get(c.name) || c.name);
2073
+ addUnique(pkCols);
2074
+ }
2075
+ for (const uc of cfg.uniqueConstraints) {
2076
+ addUnique(uc.columns.map((c) => t.sqlToJsKey.get(c.name) || c.name));
2077
+ }
2078
+ for (const f of fields) {
2079
+ if (f.unique) addUnique([
2080
+ f.name
2081
+ ]);
2082
+ }
2083
+ out.push(` uniqueFields: { ${ufEntries.join(", ")} }`);
2084
+ out.push(` },`);
2085
+ return out;
2086
+ }
2087
+ __name(emitModelBlock, "emitModelBlock");
2088
+ function emitViewModelBlock(v, enumMap, fieldToTypeDef) {
2089
+ const out = [];
2090
+ const fields = [];
2091
+ const fieldByName = /* @__PURE__ */ new Map();
2092
+ for (const [jsKey, col] of v.columns) {
2093
+ const field = mapColumn(jsKey, col, enumMap);
2094
+ if (field.sqlName === "$hash") {
2095
+ field.isGenerated = true;
2096
+ field.name = "hash";
2097
+ }
2098
+ const typedField = applyTypeDefOverride(field, fieldToTypeDef?.get(`${v.sqlName}.${jsKey}`));
2099
+ fields.push(typedField);
2100
+ fieldByName.set(typedField.name, typedField);
2101
+ }
2102
+ out.push(` ${v.modelName}: {`);
2103
+ out.push(` name: ${esc(v.modelName)},`);
2104
+ out.push(` isView: true,`);
2105
+ out.push(` fields: {`);
2106
+ for (const field of fields) {
2107
+ const block = emitFieldBlock(field);
2108
+ out.push(` ${field.name}: ${block},`);
2109
+ }
2110
+ out.push(` },`);
2111
+ const modelAttrs = [];
2112
+ modelAttrs.push(`{ name: "@@map", args: [{ name: "name", value: ExpressionUtils.literal(${esc(v.sqlName)}) }] }`);
2113
+ out.push(` attributes: [${modelAttrs.join(", ")}],`);
2114
+ const idCols = [];
2115
+ for (const [jsKey, col] of v.columns) {
2116
+ if (col.primary) {
2117
+ const name = jsKey === "$hash" ? "hash" : jsKey;
2118
+ idCols.push(name);
2119
+ }
2120
+ }
2121
+ if (idCols.length === 0 && fields.length > 0) {
2122
+ idCols.push(fields[0].name);
2123
+ }
2124
+ out.push(` idFields: [${idCols.map((c) => esc(c)).join(", ")}],`);
2125
+ const ufEntries = [];
2126
+ if (idCols.length > 0) {
2127
+ const key = idCols.join("_");
2128
+ if (idCols.length === 1) {
2129
+ ufEntries.push(`${key}: { type: ${esc(fieldByName.get(key)?.type || "String")} }`);
2130
+ } else {
2131
+ const inner = idCols.map((c) => `${c}: { type: ${esc(fieldByName.get(c)?.type || "String")} }`).join(", ");
2132
+ ufEntries.push(`${key}: { ${inner} }`);
2133
+ }
2134
+ }
2135
+ for (const f of fields) {
2136
+ if (f.unique && !idCols.includes(f.name)) {
2137
+ const key = f.name;
2138
+ ufEntries.push(`${key}: { type: ${esc(f.type)} }`);
2139
+ }
2140
+ }
2141
+ out.push(` uniqueFields: { ${ufEntries.join(", ")} }`);
2142
+ out.push(` },`);
2143
+ return out;
2144
+ }
2145
+ __name(emitViewModelBlock, "emitViewModelBlock");
2146
+ function emitSchemaTs({ tables, enumMap, modelRelations, inverseRelations, searchDefaults, modelScopes, typeDefs, fieldToTypeDef, views }) {
2147
+ const out = [
2148
+ ...emitGeneratedFileBanner()
2149
+ ];
2150
+ const allEnums = new Map([
2151
+ ...enumMap,
2152
+ ...collectDerivedEnums(tables, enumMap)
2153
+ ]);
2154
+ const hasJsonComputedField = tables.some((table) => table.computedFields.some((field) => field.tsType === "JsonValue"));
2155
+ out.push("");
2156
+ out.push('import { ExpressionUtils, type FieldDefault, type SchemaDef } from "@zenstackhq/schema";');
2157
+ if (hasJsonComputedField) {
2158
+ out.push('import type { JsonValue } from "@zenstackhq/orm";');
2159
+ }
2160
+ out.push("export class SchemaType implements SchemaDef {");
2161
+ out.push(' provider = { type: "postgresql" } as const;');
2162
+ out.push(" models = {");
2163
+ for (const t of tables) {
2164
+ out.push(...emitModelBlock(t, enumMap, modelRelations, inverseRelations, fieldToTypeDef));
2165
+ }
2166
+ if (views) {
2167
+ for (const v of views) {
2168
+ out.push(...emitViewModelBlock(v, enumMap, fieldToTypeDef));
2169
+ }
2170
+ }
2171
+ out.push(" } as const;");
2172
+ if (typeDefs && typeDefs.size > 0) {
2173
+ out.push(emitTypeDefsBlock(typeDefs));
2174
+ }
2175
+ out.push(" enums = {");
2176
+ for (const [, info] of allEnums) {
2177
+ out.push(emitEnumBlock(info) + ",");
2178
+ }
2179
+ out.push(" } as const;");
2180
+ out.push(emitPluginsBlock(modelRelations, searchDefaults, modelScopes ?? {}));
2181
+ out.push("}");
2182
+ out.push("");
2183
+ out.push("export const schema = new SchemaType();");
2184
+ out.push("");
2185
+ return out.join("\n");
2186
+ }
2187
+ __name(emitSchemaTs, "emitSchemaTs");
2188
+ function emitModelsTs(tables, typedJsonFields = []) {
2189
+ const jsonFieldAliases = createJsonFieldAliasMap(typedJsonFields);
2190
+ const out = [
2191
+ ...emitGeneratedFileBanner()
2192
+ ];
2193
+ out.push("");
2194
+ out.push('import type * as $ from "@zenstackhq/orm";');
2195
+ out.push('import type * as Json from "./json";');
2196
+ out.push('import { type SchemaType as Schema } from "./schema";');
2197
+ out.push("");
2198
+ for (const t of tables) {
2199
+ out.push(`export interface ${t.typeName} extends $.ModelResult<Schema, ${esc(t.modelName)}> {}`);
2200
+ out.push(`export namespace ${t.typeName} {`);
2201
+ for (const fieldName of getEntityFieldNames(t)) {
2202
+ const exportName = toPascalCase(fieldName);
2203
+ const jsonAlias = jsonFieldAliases.get(`${t.typeName}.${fieldName}`);
2204
+ if (jsonAlias) {
2205
+ out.push(` export interface ${exportName} extends Json.${jsonAlias} {}`);
2206
+ } else {
2207
+ out.push(` export type ${exportName} = ${t.typeName}[${esc(fieldName)}];`);
2208
+ }
2209
+ }
2210
+ out.push("}");
2211
+ out.push("");
2212
+ }
2213
+ return out.join("\n");
2214
+ }
2215
+ __name(emitModelsTs, "emitModelsTs");
2216
+ function emitViewsTs(views, typedJsonFields = []) {
2217
+ const jsonFieldAliases = createJsonFieldAliasMap(typedJsonFields);
2218
+ const out = [
2219
+ ...emitGeneratedFileBanner()
2220
+ ];
2221
+ out.push("");
2222
+ out.push('import type * as $ from "@zenstackhq/orm";');
2223
+ out.push('import type * as Json from "./json";');
2224
+ out.push('import { type SchemaType as Schema } from "./schema";');
2225
+ out.push("");
2226
+ for (const v of views) {
2227
+ out.push(`export interface ${v.typeName} extends $.ModelResult<Schema, ${esc(v.modelName)}> {}`);
2228
+ out.push(`export namespace ${v.typeName} {`);
2229
+ for (const fieldName of getEntityFieldNames(v)) {
2230
+ const exportName = toPascalCase(fieldName);
2231
+ const jsonAlias = jsonFieldAliases.get(`${v.typeName}.${fieldName}`);
2232
+ if (jsonAlias) {
2233
+ out.push(` export interface ${exportName} extends Json.${jsonAlias} {}`);
2234
+ } else {
2235
+ out.push(` export type ${exportName} = ${v.typeName}[${esc(fieldName)}];`);
2236
+ }
2237
+ }
2238
+ out.push("}");
2239
+ out.push("");
2240
+ }
2241
+ return out.join("\n");
2242
+ }
2243
+ __name(emitViewsTs, "emitViewsTs");
2244
+ function emitInputTs(tables) {
2245
+ const out = [
2246
+ ...emitGeneratedFileBanner()
2247
+ ];
2248
+ out.push("");
2249
+ out.push('import type * as $ from "@zenstackhq/orm";');
2250
+ out.push('import { type SchemaType as Schema } from "./schema";');
2251
+ out.push("");
2252
+ for (const t of tables) {
2253
+ out.push(`export namespace ${t.typeName} {`);
2254
+ out.push(` export interface FindManyArgs extends $.FindManyArgs<Schema, ${esc(t.modelName)}> {}`);
2255
+ out.push(` export interface FindUniqueArgs extends $.FindUniqueArgs<Schema, ${esc(t.modelName)}> {}`);
2256
+ out.push(` export interface FindFirstArgs extends $.FindFirstArgs<Schema, ${esc(t.modelName)}> {}`);
2257
+ out.push(` export interface ExistsArgs extends $.ExistsArgs<Schema, ${esc(t.modelName)}> {}`);
2258
+ out.push(` export interface CreateArgs extends $.CreateArgs<Schema, ${esc(t.modelName)}> {}`);
2259
+ out.push(` export interface CreateManyArgs extends $.CreateManyArgs<Schema, ${esc(t.modelName)}> {}`);
2260
+ out.push(` export interface CreateManyAndReturnArgs extends $.CreateManyAndReturnArgs<Schema, ${esc(t.modelName)}> {}`);
2261
+ out.push(` export interface UpdateArgs extends $.UpdateArgs<Schema, ${esc(t.modelName)}> {}`);
2262
+ out.push(` export interface UpdateManyArgs extends $.UpdateManyArgs<Schema, ${esc(t.modelName)}> {}`);
2263
+ out.push(` export interface UpdateManyAndReturnArgs extends $.UpdateManyAndReturnArgs<Schema, ${esc(t.modelName)}> {}`);
2264
+ out.push(` export interface UpsertArgs extends $.UpsertArgs<Schema, ${esc(t.modelName)}> {}`);
2265
+ out.push(` export interface DeleteArgs extends $.DeleteArgs<Schema, ${esc(t.modelName)}> {}`);
2266
+ out.push(` export interface DeleteManyArgs extends $.DeleteManyArgs<Schema, ${esc(t.modelName)}> {}`);
2267
+ out.push(` export interface CountArgs extends $.CountArgs<Schema, ${esc(t.modelName)}> {}`);
2268
+ out.push(` export interface AggregateArgs extends $.AggregateArgs<Schema, ${esc(t.modelName)}> {}`);
2269
+ out.push(` export interface GroupByArgs extends $.GroupByArgs<Schema, ${esc(t.modelName)}> {}`);
2270
+ out.push(` export interface WhereInput extends $.WhereInput<Schema, ${esc(t.modelName)}> {}`);
2271
+ out.push(` export interface Select extends $.SelectInput<Schema, ${esc(t.modelName)}> {}`);
2272
+ out.push(` export interface Include extends $.IncludeInput<Schema, ${esc(t.modelName)}> {}`);
2273
+ out.push(` export interface Omit extends $.OmitInput<Schema, ${esc(t.modelName)}> {}`);
2274
+ out.push(` export type GetPayload<Args extends $.SelectIncludeOmit<Schema, ${esc(t.modelName)}, true>, Options extends $.QueryOptions<Schema> = $.QueryOptions<Schema>> = $.SimplifiedPlainResult<Schema, ${esc(t.modelName)}, Args, Options>;`);
2275
+ out.push("}");
2276
+ out.push("");
2277
+ }
2278
+ return out.join("\n");
2279
+ }
2280
+ __name(emitInputTs, "emitInputTs");
2281
+ function emitIndexTs({ tables, views, enumMap, typeDefs, typedJsonFields }) {
2282
+ const allEnums = new Map([
2283
+ ...enumMap,
2284
+ ...collectDerivedEnums(tables, enumMap)
2285
+ ]);
2286
+ const jsonFieldAliases = createJsonFieldAliasMap(typedJsonFields);
2287
+ const out = [
2288
+ ...emitGeneratedFileBanner()
2289
+ ];
2290
+ out.push("");
2291
+ out.push('import type * as $ from "@zenstackhq/orm";');
2292
+ out.push('import type * as RawJson from "../../supabase/schema/types";');
2293
+ out.push('import { type SchemaType as Schema } from "./schema";');
2294
+ out.push("");
2295
+ out.push("export namespace Json {");
2296
+ out.push(...emitJsonNamespaceBlock(typeDefs, typedJsonFields, " "));
2297
+ out.push("}");
2298
+ out.push("");
2299
+ out.push("export namespace JsonRaw {");
2300
+ const jsonRawLines = emitJsonRawNamespaceBlock(typedJsonFields, " ");
2301
+ if (jsonRawLines.length > 0) {
2302
+ out.push(...jsonRawLines);
2303
+ }
2304
+ out.push("}");
2305
+ out.push("");
2306
+ out.push("export namespace Table {");
2307
+ for (const table of tables) {
2308
+ out.push(...emitEntityNamespaceBlock(table, table.modelName, jsonFieldAliases, " "));
2309
+ out.push("");
2310
+ }
2311
+ out.push("}");
2312
+ out.push("");
2313
+ out.push("export namespace View {");
2314
+ for (const view of views) {
2315
+ out.push(...emitEntityNamespaceBlock(view, view.modelName, jsonFieldAliases, " "));
2316
+ out.push("");
2317
+ }
2318
+ out.push("}");
2319
+ out.push("");
2320
+ out.push("export namespace Input {");
2321
+ for (const table of tables) {
2322
+ out.push(...emitInputNamespaceBlock(table, " "));
2323
+ out.push("");
2324
+ }
2325
+ out.push("}");
2326
+ out.push("");
2327
+ out.push("export namespace ComputedFields {");
2328
+ out.push(" export type All = $.ComputedFieldsOptions<Schema>;");
2329
+ for (const table of tables) {
2330
+ if (table.computedFields.length === 0) continue;
2331
+ out.push(` export type ${table.typeName} = $.ComputedFieldsOptions<Schema>[${esc(table.modelName)}];`);
2332
+ }
2333
+ out.push("}");
2334
+ out.push("");
2335
+ out.push("export namespace Enum {");
2336
+ for (const [, info] of allEnums) {
2337
+ out.push(...emitEnumNamespaceBlock(info, " "));
2338
+ out.push("");
2339
+ }
2340
+ out.push("}");
2341
+ out.push("");
2342
+ return out.join("\n");
2343
+ }
2344
+ __name(emitIndexTs, "emitIndexTs");
2345
+ function emitCompatTs({ tables, views, enumMap, typedJsonFields }) {
2346
+ const out = [
2347
+ ...emitGeneratedFileBanner()
2348
+ ];
2349
+ const jsonAliases = typedJsonFields.map((field) => `${field.entityTypeName}${toPascalCase(field.fieldName)}Json`);
2350
+ const jsonRawAliases = typedJsonFields.filter((field) => field.sourceTypeName).map((field) => `${field.entityTypeName}${toPascalCase(field.fieldName)}JsonRaw`);
2351
+ out.push("");
2352
+ out.push('import type * as $ from "@zenstackhq/orm";');
2353
+ out.push('import * as Db from "./index";');
2354
+ out.push('import type { SchemaType as Schema } from "./schema";');
2355
+ out.push("");
2356
+ out.push("export namespace Models {");
2357
+ for (const table of tables) {
2358
+ out.push(...emitCompatEntityAlias(table, "Table", " "));
2359
+ out.push("");
2360
+ }
2361
+ out.push("}");
2362
+ out.push("");
2363
+ out.push("export namespace Views {");
2364
+ for (const view of views) {
2365
+ out.push(...emitCompatEntityAlias(view, "View", " "));
2366
+ out.push("");
2367
+ }
2368
+ out.push("}");
2369
+ out.push("");
2370
+ out.push("export namespace Input {");
2371
+ for (const table of tables) {
2372
+ out.push(...emitCompatInputAliases(table, " "));
2373
+ out.push("");
2374
+ }
2375
+ out.push("}");
2376
+ out.push("");
2377
+ out.push("export namespace Json {");
2378
+ for (const alias of jsonAliases) {
2379
+ out.push(...emitDeprecatedTypeAlias(alias, `Db.Json.${alias}`, " "));
2380
+ }
2381
+ out.push("}");
2382
+ out.push("");
2383
+ out.push("export namespace JsonRaw {");
2384
+ for (const alias of jsonRawAliases) {
2385
+ out.push(...emitDeprecatedTypeAlias(alias, `Db.JsonRaw.${alias}`, " "));
2386
+ }
2387
+ out.push("}");
2388
+ out.push("");
2389
+ out.push("export namespace Enums {");
2390
+ for (const [, info] of enumMap) {
2391
+ if (!info.mapping) continue;
2392
+ out.push(...emitDeprecatedEnumAliases(info.zenstackName, " "));
2393
+ out.push("");
2394
+ }
2395
+ out.push("}");
2396
+ out.push("");
2397
+ for (const table of tables) {
2398
+ out.push(...emitDeprecatedTypeAlias(table.typeName, `Models.${table.typeName}`));
2399
+ }
2400
+ for (const view of views) {
2401
+ out.push(...emitDeprecatedTypeAlias(view.typeName, `Views.${view.typeName}`));
2402
+ }
2403
+ for (const table of tables) {
2404
+ out.push(...emitCompatInputAliases(table));
2405
+ }
2406
+ for (const alias of jsonAliases) {
2407
+ out.push(...emitDeprecatedTypeAlias(alias, `Json.${alias}`));
2408
+ }
2409
+ for (const alias of jsonRawAliases) {
2410
+ out.push(...emitDeprecatedTypeAlias(alias, `JsonRaw.${alias}`));
2411
+ }
2412
+ for (const [, info] of enumMap) {
2413
+ if (!info.mapping) continue;
2414
+ out.push(...emitDeprecatedEnumAliases(info.zenstackName));
2415
+ out.push("");
2416
+ }
2417
+ return out.join("\n");
2418
+ }
2419
+ __name(emitCompatTs, "emitCompatTs");
2420
+ function emitOrmTypesTs(tables) {
2421
+ const out = [
2422
+ ...emitGeneratedFileBanner()
2423
+ ];
2424
+ out.push("");
2425
+ out.push('import type * as $ from "@zenstackhq/orm";');
2426
+ out.push('import type { SchemaType as Schema } from "./schema";');
2427
+ out.push("");
2428
+ out.push("export type Client = $.ClientContract<Schema>;");
2429
+ out.push("");
2430
+ out.push("export namespace ComputedFields {");
2431
+ out.push(" export type All = $.ComputedFieldsOptions<Schema>;");
2432
+ for (const table of tables) {
2433
+ if (table.computedFields.length === 0) continue;
2434
+ out.push(` export type ${table.typeName} = $.ComputedFieldsOptions<Schema>[${esc(table.modelName)}];`);
2435
+ }
2436
+ out.push("}");
2437
+ out.push("");
2438
+ return out.join("\n");
2439
+ }
2440
+ __name(emitOrmTypesTs, "emitOrmTypesTs");
2441
+ function getEntityFieldNames(entity) {
2442
+ const fieldNames = /* @__PURE__ */ new Set();
2443
+ if ("table" in entity) {
2444
+ for (const jsKey of entity.sqlToJsKey.values()) {
2445
+ fieldNames.add(jsKey === "$hash" ? "hash" : jsKey);
2446
+ }
2447
+ for (const computedField of entity.computedFields) {
2448
+ fieldNames.add(computedField.name);
2449
+ }
2450
+ } else {
2451
+ for (const jsKey of entity.columns.keys()) {
2452
+ fieldNames.add(jsKey === "$hash" ? "hash" : jsKey);
2453
+ }
2454
+ }
2455
+ return [
2456
+ ...fieldNames
2457
+ ];
2458
+ }
2459
+ __name(getEntityFieldNames, "getEntityFieldNames");
2460
+ function createJsonFieldAliasMap(typedJsonFields) {
2461
+ return new Map(typedJsonFields.map((field) => [
2462
+ `${field.entityTypeName}.${field.fieldName}`,
2463
+ `${field.entityTypeName}${toPascalCase(field.fieldName)}Json`
2464
+ ]));
2465
+ }
2466
+ __name(createJsonFieldAliasMap, "createJsonFieldAliasMap");
2467
+ function emitEntityNamespaceBlock(entity, modelName, jsonFieldAliases, indent = "") {
2468
+ const out = [];
2469
+ out.push(`${indent}export interface ${entity.typeName} extends $.ModelResult<Schema, ${esc(modelName)}> {}`);
2470
+ out.push(`${indent}export namespace ${entity.typeName} {`);
2471
+ for (const fieldName of getEntityFieldNames(entity)) {
2472
+ const exportName = toPascalCase(fieldName);
2473
+ const jsonAlias = jsonFieldAliases.get(`${entity.typeName}.${fieldName}`);
2474
+ if (jsonAlias) {
2475
+ out.push(`${indent} export interface ${exportName} extends Json.${jsonAlias} {}`);
2476
+ } else {
2477
+ out.push(`${indent} export type ${exportName} = ${entity.typeName}[${esc(fieldName)}];`);
2478
+ }
2479
+ }
2480
+ out.push(`${indent}}`);
2481
+ return out;
2482
+ }
2483
+ __name(emitEntityNamespaceBlock, "emitEntityNamespaceBlock");
2484
+ function emitInputNamespaceBlock(table, indent = "") {
2485
+ const out = [];
2486
+ out.push(`${indent}export namespace ${table.typeName} {`);
2487
+ out.push(`${indent} export interface FindManyArgs extends $.FindManyArgs<Schema, ${esc(table.modelName)}> {}`);
2488
+ out.push(`${indent} export interface FindUniqueArgs extends $.FindUniqueArgs<Schema, ${esc(table.modelName)}> {}`);
2489
+ out.push(`${indent} export interface FindFirstArgs extends $.FindFirstArgs<Schema, ${esc(table.modelName)}> {}`);
2490
+ out.push(`${indent} export interface ExistsArgs extends $.ExistsArgs<Schema, ${esc(table.modelName)}> {}`);
2491
+ out.push(`${indent} export interface CreateArgs extends $.CreateArgs<Schema, ${esc(table.modelName)}> {}`);
2492
+ out.push(`${indent} export interface CreateManyArgs extends $.CreateManyArgs<Schema, ${esc(table.modelName)}> {}`);
2493
+ out.push(`${indent} export interface CreateManyAndReturnArgs extends $.CreateManyAndReturnArgs<Schema, ${esc(table.modelName)}> {}`);
2494
+ out.push(`${indent} export interface UpdateArgs extends $.UpdateArgs<Schema, ${esc(table.modelName)}> {}`);
2495
+ out.push(`${indent} export interface UpdateManyArgs extends $.UpdateManyArgs<Schema, ${esc(table.modelName)}> {}`);
2496
+ out.push(`${indent} export interface UpdateManyAndReturnArgs extends $.UpdateManyAndReturnArgs<Schema, ${esc(table.modelName)}> {}`);
2497
+ out.push(`${indent} export interface UpsertArgs extends $.UpsertArgs<Schema, ${esc(table.modelName)}> {}`);
2498
+ out.push(`${indent} export interface DeleteArgs extends $.DeleteArgs<Schema, ${esc(table.modelName)}> {}`);
2499
+ out.push(`${indent} export interface DeleteManyArgs extends $.DeleteManyArgs<Schema, ${esc(table.modelName)}> {}`);
2500
+ out.push(`${indent} export interface CountArgs extends $.CountArgs<Schema, ${esc(table.modelName)}> {}`);
2501
+ out.push(`${indent} export interface AggregateArgs extends $.AggregateArgs<Schema, ${esc(table.modelName)}> {}`);
2502
+ out.push(`${indent} export interface GroupByArgs extends $.GroupByArgs<Schema, ${esc(table.modelName)}> {}`);
2503
+ out.push(`${indent} export interface WhereInput extends $.WhereInput<Schema, ${esc(table.modelName)}> {}`);
2504
+ out.push(`${indent} export interface Select extends $.SelectInput<Schema, ${esc(table.modelName)}> {}`);
2505
+ out.push(`${indent} export interface Include extends $.IncludeInput<Schema, ${esc(table.modelName)}> {}`);
2506
+ out.push(`${indent} export interface Omit extends $.OmitInput<Schema, ${esc(table.modelName)}> {}`);
2507
+ out.push(`${indent} export type GetPayload<Args extends $.SelectIncludeOmit<Schema, ${esc(table.modelName)}, true>, Options extends $.QueryOptions<Schema> = $.QueryOptions<Schema>> = $.SimplifiedPlainResult<Schema, ${esc(table.modelName)}, Args, Options>;`);
2508
+ out.push(`${indent}}`);
2509
+ return out;
2510
+ }
2511
+ __name(emitInputNamespaceBlock, "emitInputNamespaceBlock");
2512
+ function emitEnumNamespaceBlock(info, indent = "") {
2513
+ if (!info.mapping) return [];
2514
+ const out = [];
2515
+ const entries = Object.entries(info.mapping).map(([key, value]) => `${indent} ${key}: ${esc(value)}`).join(",\n");
2516
+ out.push(`${indent}export const ${info.zenstackName} = {`);
2517
+ out.push(entries);
2518
+ out.push(`${indent}} as const;`);
2519
+ out.push(`${indent}export type ${info.zenstackName} = (typeof ${info.zenstackName})[keyof typeof ${info.zenstackName}];`);
2520
+ out.push(`${indent}export type ${info.zenstackName}Key = ${Object.keys(info.mapping).map((key) => esc(key)).join(" | ")};`);
2521
+ out.push(`${indent}export const ${info.zenstackName}Values = Object.values(${info.zenstackName});`);
2522
+ out.push(`${indent}export const ${info.zenstackName}Keys = Object.keys(${info.zenstackName}) as ${info.zenstackName}Key[];`);
2523
+ return out;
2524
+ }
2525
+ __name(emitEnumNamespaceBlock, "emitEnumNamespaceBlock");
2526
+ function emitDeprecatedTypeAlias(name, target, indent = "") {
2527
+ return [
2528
+ `${indent}/** @deprecated Use ${target} instead. */`,
2529
+ `${indent}export type ${name} = ${target};`
2530
+ ];
2531
+ }
2532
+ __name(emitDeprecatedTypeAlias, "emitDeprecatedTypeAlias");
2533
+ function emitDeprecatedValueAlias(name, target, indent = "") {
2534
+ return [
2535
+ `${indent}/** @deprecated Use ${target} instead. */`,
2536
+ `${indent}export const ${name} = ${target};`
2537
+ ];
2538
+ }
2539
+ __name(emitDeprecatedValueAlias, "emitDeprecatedValueAlias");
2540
+ function emitDeprecatedEnumAliases(enumName, indent = "") {
2541
+ return [
2542
+ ...emitDeprecatedValueAlias(enumName, `Db.Enum.${enumName}`, indent),
2543
+ ...emitDeprecatedTypeAlias(enumName, `Db.Enum.${enumName}`, indent),
2544
+ ...emitDeprecatedTypeAlias(`${enumName}Key`, `Db.Enum.${enumName}Key`, indent),
2545
+ ...emitDeprecatedValueAlias(`${enumName}Values`, `Db.Enum.${enumName}Values`, indent),
2546
+ ...emitDeprecatedValueAlias(`${enumName}Keys`, `Db.Enum.${enumName}Keys`, indent)
2547
+ ];
2548
+ }
2549
+ __name(emitDeprecatedEnumAliases, "emitDeprecatedEnumAliases");
2550
+ function emitCompatEntityAlias(entity, namespace, indent = "") {
2551
+ const target = `Db.${namespace}.${entity.typeName}`;
2552
+ const out = [
2553
+ `${indent}/** @deprecated Use ${target} instead. */`
2554
+ ];
2555
+ const legacyFields = [
2556
+ ...entity.sqlToJsKey.entries()
2557
+ ].map(([sqlName, jsName]) => ({
2558
+ sqlName,
2559
+ fieldName: jsName === "$hash" ? "hash" : jsName
2560
+ })).filter(({ sqlName, fieldName }) => sqlName !== "$hash" && sqlName !== fieldName);
2561
+ if (legacyFields.length === 0) {
2562
+ out.push(`${indent}export type ${entity.typeName} = ${target};`);
2563
+ return out;
2564
+ }
2565
+ out.push(`${indent}export type ${entity.typeName} = ${target} & {`);
2566
+ for (const { sqlName, fieldName } of legacyFields) {
2567
+ out.push(`${indent} /** @deprecated Use ${fieldName} instead. */`);
2568
+ out.push(`${indent} ${esc(sqlName)}: ${target}[${esc(fieldName)}];`);
2569
+ }
2570
+ out.push(`${indent}};`);
2571
+ return out;
2572
+ }
2573
+ __name(emitCompatEntityAlias, "emitCompatEntityAlias");
2574
+ function emitCompatInputAliases(table, indent = "") {
2575
+ const target = `Db.Input.${table.typeName}`;
2576
+ return [
2577
+ ...emitDeprecatedTypeAlias(`${table.typeName}FindManyArgs`, `${target}.FindManyArgs`, indent),
2578
+ ...emitDeprecatedTypeAlias(`${table.typeName}FindUniqueArgs`, `${target}.FindUniqueArgs`, indent),
2579
+ ...emitDeprecatedTypeAlias(`${table.typeName}FindFirstArgs`, `${target}.FindFirstArgs`, indent),
2580
+ ...emitDeprecatedTypeAlias(`${table.typeName}ExistsArgs`, `${target}.ExistsArgs`, indent),
2581
+ ...emitDeprecatedTypeAlias(`${table.typeName}CreateArgs`, `${target}.CreateArgs`, indent),
2582
+ ...emitDeprecatedTypeAlias(`${table.typeName}CreateManyArgs`, `${target}.CreateManyArgs`, indent),
2583
+ ...emitDeprecatedTypeAlias(`${table.typeName}CreateManyAndReturnArgs`, `${target}.CreateManyAndReturnArgs`, indent),
2584
+ ...emitDeprecatedTypeAlias(`${table.typeName}UpdateArgs`, `${target}.UpdateArgs`, indent),
2585
+ ...emitDeprecatedTypeAlias(`${table.typeName}UpdateManyArgs`, `${target}.UpdateManyArgs`, indent),
2586
+ ...emitDeprecatedTypeAlias(`${table.typeName}UpdateManyAndReturnArgs`, `${target}.UpdateManyAndReturnArgs`, indent),
2587
+ ...emitDeprecatedTypeAlias(`${table.typeName}UpsertArgs`, `${target}.UpsertArgs`, indent),
2588
+ ...emitDeprecatedTypeAlias(`${table.typeName}DeleteArgs`, `${target}.DeleteArgs`, indent),
2589
+ ...emitDeprecatedTypeAlias(`${table.typeName}DeleteManyArgs`, `${target}.DeleteManyArgs`, indent),
2590
+ ...emitDeprecatedTypeAlias(`${table.typeName}CountArgs`, `${target}.CountArgs`, indent),
2591
+ ...emitDeprecatedTypeAlias(`${table.typeName}AggregateArgs`, `${target}.AggregateArgs`, indent),
2592
+ ...emitDeprecatedTypeAlias(`${table.typeName}GroupByArgs`, `${target}.GroupByArgs`, indent),
2593
+ ...emitDeprecatedTypeAlias(`${table.typeName}WhereInput`, `${target}.WhereInput`, indent),
2594
+ ...emitDeprecatedTypeAlias(`${table.typeName}Select`, `${target}.Select`, indent),
2595
+ ...emitDeprecatedTypeAlias(`${table.typeName}Include`, `${target}.Include`, indent),
2596
+ ...emitDeprecatedTypeAlias(`${table.typeName}Omit`, `${target}.Omit`, indent),
2597
+ `${indent}/** @deprecated Use ${target}.GetPayload instead. */`,
2598
+ `${indent}export type ${table.typeName}GetPayload<Args extends $.SelectIncludeOmit<Schema, ${esc(table.modelName)}, true>, Options extends $.QueryOptions<Schema> = $.QueryOptions<Schema>> = ${target}.GetPayload<Args, Options>;`
2599
+ ];
2600
+ }
2601
+ __name(emitCompatInputAliases, "emitCompatInputAliases");
2602
+ function emitEnumsTs(enumMap) {
2603
+ const out = [
2604
+ ...emitGeneratedFileBanner()
2605
+ ];
2606
+ out.push("");
2607
+ for (const [, info] of enumMap) {
2608
+ if (!info.mapping) continue;
2609
+ const n = info.zenstackName;
2610
+ const entries = Object.entries(info.mapping).map(([k, v]) => ` ${k}: ${esc(v)}`).join(",\n");
2611
+ out.push(`export const ${n} = {
2612
+ ${entries},
2613
+ } as const;`);
2614
+ out.push(`export type ${n} = (typeof ${n})[keyof typeof ${n}];`);
2615
+ out.push(`export type ${n}Key = ${Object.keys(info.mapping).map((k) => esc(k)).join(" | ")};`);
2616
+ out.push(`export const ${n}Values = Object.values(${n});`);
2617
+ out.push(`export const ${n}Keys = Object.keys(${n}) as ${n}Key[];`);
2618
+ out.push("");
2619
+ }
2620
+ return out.join("\n");
2621
+ }
2622
+ __name(emitEnumsTs, "emitEnumsTs");
2623
+ export {
2624
+ APP_SLUG_JS,
2625
+ APP_SLUG_SQL,
2626
+ GENERATED_FILE_BANNER,
2627
+ adaptToLegacyConfig,
2628
+ assertNoTypedColumnOverrides,
2629
+ buildRelations,
2630
+ buildTypeDefs,
2631
+ capitalize,
2632
+ defineConfig,
2633
+ defineModels,
2634
+ derived,
2635
+ discoverEnums,
2636
+ discoverTables,
2637
+ discoverViews,
2638
+ emitCompatTs,
2639
+ emitEnumBlock,
2640
+ emitEnumsTs,
2641
+ emitFieldBlock,
2642
+ emitGeneratedFileBanner,
2643
+ emitIndexTs,
2644
+ emitInputTs,
2645
+ emitJsonNamespaceBlock,
2646
+ emitJsonRawNamespaceBlock,
2647
+ emitJsonRawTs,
2648
+ emitJsonTs,
2649
+ emitModelsTs,
2650
+ emitOrmTypesTs,
2651
+ emitRelationField,
2652
+ emitSchemaTs,
2653
+ emitTypeDefsBlock,
2654
+ emitViewsTs,
2655
+ esc,
2656
+ extend,
2657
+ extractFKs,
2658
+ getDrizzleTableName,
2659
+ many,
2660
+ mapColumn,
2661
+ model,
2662
+ one,
2663
+ through,
2664
+ toPascalCase,
2665
+ uncapitalize,
2666
+ writeFileIfChanged
2667
+ };
2668
+ //# sourceMappingURL=index.js.map