arkormx 1.1.0 → 1.2.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.
package/dist/index.d.mts CHANGED
@@ -24,10 +24,12 @@ type FactoryDefinition<TAttributes extends FactoryAttributes> = (sequence: numbe
24
24
  type FactoryState<TAttributes extends FactoryAttributes> = (attributes: TAttributes, sequence: number) => TAttributes;
25
25
  //#endregion
26
26
  //#region src/types/migrations.d.ts
27
- type SchemaColumnType = 'id' | 'uuid' | 'string' | 'text' | 'integer' | 'bigInteger' | 'float' | 'boolean' | 'json' | 'date' | 'timestamp';
27
+ type SchemaColumnType = 'id' | 'uuid' | 'enum' | 'string' | 'text' | 'integer' | 'bigInteger' | 'float' | 'boolean' | 'json' | 'date' | 'timestamp';
28
28
  interface SchemaColumn {
29
29
  name: string;
30
30
  type: SchemaColumnType;
31
+ enumName?: string;
32
+ enumValues?: string[];
31
33
  map?: string;
32
34
  nullable?: boolean;
33
35
  unique?: boolean;
@@ -2670,6 +2672,58 @@ declare class ForeignKeyBuilder {
2670
2672
  }
2671
2673
  //#endregion
2672
2674
  //#region src/database/TableBuilder.d.ts
2675
+ /**
2676
+ * The EnumBuilder class provides a fluent interface for configuring enum columns
2677
+ * after they are defined on a table.
2678
+ *
2679
+ * @author Legacy (3m1n3nc3)
2680
+ * @since 0.2.3
2681
+ */
2682
+ declare class EnumBuilder {
2683
+ private readonly tableBuilder;
2684
+ private readonly columnName;
2685
+ constructor(tableBuilder: TableBuilder, columnName: string);
2686
+ /**
2687
+ * Defines the Prisma enum name for this column.
2688
+ *
2689
+ * @param name
2690
+ * @returns
2691
+ */
2692
+ enumName(name: string): this;
2693
+ /**
2694
+ * Marks the enum column as nullable.
2695
+ *
2696
+ * @returns
2697
+ */
2698
+ nullable(): this;
2699
+ /**
2700
+ * Marks the enum column as unique.
2701
+ *
2702
+ * @returns
2703
+ */
2704
+ unique(): this;
2705
+ /**
2706
+ * Sets a default value for the enum column.
2707
+ *
2708
+ * @param value
2709
+ * @returns
2710
+ */
2711
+ default(value: unknown): this;
2712
+ /**
2713
+ * Positions the enum column after another column when supported.
2714
+ *
2715
+ * @param referenceColumn
2716
+ * @returns
2717
+ */
2718
+ after(referenceColumn: string): this;
2719
+ /**
2720
+ * Maps the enum column to a custom database column name.
2721
+ *
2722
+ * @param name
2723
+ * @returns
2724
+ */
2725
+ map(name: string): this;
2726
+ }
2673
2727
  /**
2674
2728
  * The TableBuilder class provides a fluent interface for defining
2675
2729
  * the structure of a database table in a migration, including columns to add or drop.
@@ -2714,6 +2768,17 @@ declare class TableBuilder {
2714
2768
  * @returns The current TableBuilder instance for chaining.
2715
2769
  */
2716
2770
  uuid(name: string, options?: Partial<SchemaColumn>): this;
2771
+ /**
2772
+ * Defines an enum column in the table.
2773
+ *
2774
+ * @param name The name of the enum column.
2775
+ * @param values Either an array of string values for the enum or the name of an existing enum to reuse.
2776
+ * @param options Additional options for the enum column.
2777
+ * @returns
2778
+ */
2779
+ enum(name: string, valuesOrEnumName: string[] | string, options?: Partial<SchemaColumn> & {
2780
+ enumName?: string;
2781
+ }): EnumBuilder;
2717
2782
  /**
2718
2783
  * Defines a string column in the table.
2719
2784
  *
@@ -2835,6 +2900,14 @@ declare class TableBuilder {
2835
2900
  * @returns The current TableBuilder instance for chaining.
2836
2901
  */
2837
2902
  nullable(columnName?: string): this;
2903
+ /**
2904
+ * Sets the Prisma enum name for an enum column.
2905
+ *
2906
+ * @param name The enum name to assign.
2907
+ * @param columnName Optional explicit target column name. When omitted, applies to the latest defined column.
2908
+ * @returns The current TableBuilder instance for chaining.
2909
+ */
2910
+ enumName(name: string, columnName?: string): this;
2838
2911
  /**
2839
2912
  * Sets a default value for a column.
2840
2913
  *
@@ -3124,6 +3197,8 @@ declare const getLatestAppliedMigrations: (state: AppliedMigrationsState, steps:
3124
3197
  //#endregion
3125
3198
  //#region src/helpers/migrations.d.ts
3126
3199
  declare const PRISMA_MODEL_REGEX: RegExp;
3200
+ declare const PRISMA_ENUM_REGEX: RegExp;
3201
+ declare const PRISMA_ENUM_MEMBER_REGEX: RegExp;
3127
3202
  /**
3128
3203
  * Convert a table name to a PascalCase model name, with basic singularization.
3129
3204
  *
@@ -3145,6 +3220,7 @@ declare const escapeRegex: (value: string) => string;
3145
3220
  * @returns
3146
3221
  */
3147
3222
  declare const resolvePrismaType: (column: SchemaColumn) => string;
3223
+ declare const resolveEnumName: (column: SchemaColumn) => string;
3148
3224
  /**
3149
3225
  * Format a default value for inclusion in a Prisma schema field definition, based on its type.
3150
3226
  *
@@ -3152,6 +3228,13 @@ declare const resolvePrismaType: (column: SchemaColumn) => string;
3152
3228
  * @returns
3153
3229
  */
3154
3230
  declare const formatDefaultValue: (value: unknown) => string | undefined;
3231
+ /**
3232
+ * Format a default value for an enum column as a Prisma @default attribute, validating that it is a non-empty string.
3233
+ *
3234
+ * @param value
3235
+ * @returns
3236
+ */
3237
+ declare const formatEnumDefaultValue: (value: unknown) => string | undefined;
3155
3238
  /**
3156
3239
  * Build a single line of a Prisma model field definition based on a SchemaColumn, including type and modifiers.
3157
3240
  *
@@ -3159,6 +3242,29 @@ declare const formatDefaultValue: (value: unknown) => string | undefined;
3159
3242
  * @returns
3160
3243
  */
3161
3244
  declare const buildFieldLine: (column: SchemaColumn) => string;
3245
+ /**
3246
+ * Build a Prisma enum block string based on an enum name and its values, validating that
3247
+ * at least one value is provided.
3248
+ *
3249
+ * @param enumName The name of the enum to create.
3250
+ * @param values The array of values for the enum.
3251
+ * @returns The Prisma enum block string.
3252
+ */
3253
+ declare const buildEnumBlock: (enumName: string, values: string[]) => string;
3254
+ /**
3255
+ * Find the Prisma enum block in a schema string that corresponds to a given enum
3256
+ * name, returning its details if found.
3257
+ *
3258
+ * @param schema The Prisma schema string to search for the enum block.
3259
+ * @param enumName The name of the enum to find in the schema.
3260
+ * @returns
3261
+ */
3262
+ declare const findEnumBlock: (schema: string, enumName: string) => {
3263
+ enumName: string;
3264
+ block: string;
3265
+ start: number;
3266
+ end: number;
3267
+ } | null;
3162
3268
  /**
3163
3269
  * Build a Prisma model-level @@index definition line.
3164
3270
  *
@@ -3492,4 +3598,4 @@ declare class URLDriver {
3492
3598
  url(page: number): string;
3493
3599
  }
3494
3600
  //#endregion
3495
- export { ArkormCollection, ArkormErrorContext, ArkormException, Attribute, AttributeOptions, CliApp, ForeignKeyBuilder, InitCommand, InlineFactory, LengthAwarePaginator, MIGRATION_BRAND, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, MigrateRollbackCommand, Migration, MigrationHistoryCommand, MissingDelegateException, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_MODEL_REGEX, Paginator, PrismaDelegateMap, QueryBuilder, QueryConstraintException, RelationResolutionException, SEEDER_BRAND, SchemaBuilder, ScopeNotDefinedException, SeedCommand, Seeder, SeederCallArgument, SeederConstructor, SeederInput, TableBuilder, URLDriver, UniqueConstraintResolutionException, UnsupportedAdapterFeatureException, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationRollbackToPrismaSchema, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildFieldLine, buildIndexLine, buildInverseRelationLine, buildMigrationIdentity, buildMigrationRunId, buildMigrationSource, buildModelBlock, buildRelationLine, computeMigrationChecksum, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, deriveCollectionFieldName, deriveInverseRelationAlias, deriveRelationFieldName, ensureArkormConfigLoading, escapeRegex, findAppliedMigration, findModelBlock, formatDefaultValue, formatRelationAction, generateMigrationFile, getActiveTransactionClient, getDefaultStubsPath, getLastMigrationRun, getLatestAppliedMigrations, getMigrationPlan, getRuntimePaginationCurrentPageResolver, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, isMigrationApplied, isTransactionCapableClient, loadArkormConfig, markMigrationApplied, markMigrationRun, pad, readAppliedMigrationsState, removeAppliedMigration, resetArkormRuntimeForTests, resolveCast, resolveMigrationClassName, resolveMigrationStateFilePath, resolvePrismaType, runArkormTransaction, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName, writeAppliedMigrationsState };
3601
+ export { ArkormCollection, ArkormErrorContext, ArkormException, Attribute, AttributeOptions, CliApp, EnumBuilder, ForeignKeyBuilder, InitCommand, InlineFactory, LengthAwarePaginator, MIGRATION_BRAND, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, MigrateRollbackCommand, Migration, MigrationHistoryCommand, MissingDelegateException, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_ENUM_MEMBER_REGEX, PRISMA_ENUM_REGEX, PRISMA_MODEL_REGEX, Paginator, PrismaDelegateMap, QueryBuilder, QueryConstraintException, RelationResolutionException, SEEDER_BRAND, SchemaBuilder, ScopeNotDefinedException, SeedCommand, Seeder, SeederCallArgument, SeederConstructor, SeederInput, TableBuilder, URLDriver, UniqueConstraintResolutionException, UnsupportedAdapterFeatureException, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationRollbackToPrismaSchema, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildEnumBlock, buildFieldLine, buildIndexLine, buildInverseRelationLine, buildMigrationIdentity, buildMigrationRunId, buildMigrationSource, buildModelBlock, buildRelationLine, computeMigrationChecksum, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, deriveCollectionFieldName, deriveInverseRelationAlias, deriveRelationFieldName, ensureArkormConfigLoading, escapeRegex, findAppliedMigration, findEnumBlock, findModelBlock, formatDefaultValue, formatEnumDefaultValue, formatRelationAction, generateMigrationFile, getActiveTransactionClient, getDefaultStubsPath, getLastMigrationRun, getLatestAppliedMigrations, getMigrationPlan, getRuntimePaginationCurrentPageResolver, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, isMigrationApplied, isTransactionCapableClient, loadArkormConfig, markMigrationApplied, markMigrationRun, pad, readAppliedMigrationsState, removeAppliedMigration, resetArkormRuntimeForTests, resolveCast, resolveEnumName, resolveMigrationClassName, resolveMigrationStateFilePath, resolvePrismaType, runArkormTransaction, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName, writeAppliedMigrationsState };
package/dist/index.mjs CHANGED
@@ -209,6 +209,95 @@ var ForeignKeyBuilder = class {
209
209
 
210
210
  //#endregion
211
211
  //#region src/database/TableBuilder.ts
212
+ const PRISMA_ENUM_MEMBER_REGEX$1 = /^[A-Za-z][A-Za-z0-9_]*$/;
213
+ const normalizeEnumMember = (columnName, value) => {
214
+ const normalized = value.trim();
215
+ if (!normalized) throw new Error(`Enum column [${columnName}] must define only non-empty values.`);
216
+ if (!PRISMA_ENUM_MEMBER_REGEX$1.test(normalized)) throw new Error(`Enum column [${columnName}] contains invalid Prisma enum value [${normalized}].`);
217
+ return normalized;
218
+ };
219
+ const normalizeEnumMembers = (columnName, values) => {
220
+ const normalizedValues = values.map((value) => normalizeEnumMember(columnName, value));
221
+ const seen = /* @__PURE__ */ new Set();
222
+ for (const value of normalizedValues) {
223
+ if (seen.has(value)) throw new Error(`Enum column [${columnName}] contains duplicate enum value [${value}].`);
224
+ seen.add(value);
225
+ }
226
+ return normalizedValues;
227
+ };
228
+ /**
229
+ * The EnumBuilder class provides a fluent interface for configuring enum columns
230
+ * after they are defined on a table.
231
+ *
232
+ * @author Legacy (3m1n3nc3)
233
+ * @since 0.2.3
234
+ */
235
+ var EnumBuilder = class {
236
+ tableBuilder;
237
+ columnName;
238
+ constructor(tableBuilder, columnName) {
239
+ this.tableBuilder = tableBuilder;
240
+ this.columnName = columnName;
241
+ }
242
+ /**
243
+ * Defines the Prisma enum name for this column.
244
+ *
245
+ * @param name
246
+ * @returns
247
+ */
248
+ enumName(name) {
249
+ this.tableBuilder.enumName(name, this.columnName);
250
+ return this;
251
+ }
252
+ /**
253
+ * Marks the enum column as nullable.
254
+ *
255
+ * @returns
256
+ */
257
+ nullable() {
258
+ this.tableBuilder.nullable(this.columnName);
259
+ return this;
260
+ }
261
+ /**
262
+ * Marks the enum column as unique.
263
+ *
264
+ * @returns
265
+ */
266
+ unique() {
267
+ this.tableBuilder.unique(this.columnName);
268
+ return this;
269
+ }
270
+ /**
271
+ * Sets a default value for the enum column.
272
+ *
273
+ * @param value
274
+ * @returns
275
+ */
276
+ default(value) {
277
+ this.tableBuilder.default(value, this.columnName);
278
+ return this;
279
+ }
280
+ /**
281
+ * Positions the enum column after another column when supported.
282
+ *
283
+ * @param referenceColumn
284
+ * @returns
285
+ */
286
+ after(referenceColumn) {
287
+ this.tableBuilder.after(referenceColumn, this.columnName);
288
+ return this;
289
+ }
290
+ /**
291
+ * Maps the enum column to a custom database column name.
292
+ *
293
+ * @param name
294
+ * @returns
295
+ */
296
+ map(name) {
297
+ this.tableBuilder.map(name, this.columnName);
298
+ return this;
299
+ }
300
+ };
212
301
  /**
213
302
  * The TableBuilder class provides a fluent interface for defining
214
303
  * the structure of a database table in a migration, including columns to add or drop.
@@ -261,6 +350,27 @@ var TableBuilder = class {
261
350
  return this.column(name, "uuid", options);
262
351
  }
263
352
  /**
353
+ * Defines an enum column in the table.
354
+ *
355
+ * @param name The name of the enum column.
356
+ * @param values Either an array of string values for the enum or the name of an existing enum to reuse.
357
+ * @param options Additional options for the enum column.
358
+ * @returns
359
+ */
360
+ enum(name, valuesOrEnumName, options = {}) {
361
+ const isEnumReuse = typeof valuesOrEnumName === "string";
362
+ if (!isEnumReuse && valuesOrEnumName.length === 0) throw new Error(`Enum column [${name}] must define at least one value.`);
363
+ const normalizedEnumValues = isEnumReuse ? void 0 : normalizeEnumMembers(name, valuesOrEnumName);
364
+ const enumName = isEnumReuse ? valuesOrEnumName.trim() : options.enumName?.trim();
365
+ if (isEnumReuse && !enumName) throw new Error(`Enum column [${name}] must define an enum name.`);
366
+ this.column(name, "enum", {
367
+ ...options,
368
+ enumName,
369
+ enumValues: normalizedEnumValues
370
+ });
371
+ return new EnumBuilder(this, name);
372
+ }
373
+ /**
264
374
  * Defines a string column in the table.
265
375
  *
266
376
  * @param name The name of the string column.
@@ -430,6 +540,21 @@ var TableBuilder = class {
430
540
  return this;
431
541
  }
432
542
  /**
543
+ * Sets the Prisma enum name for an enum column.
544
+ *
545
+ * @param name The enum name to assign.
546
+ * @param columnName Optional explicit target column name. When omitted, applies to the latest defined column.
547
+ * @returns The current TableBuilder instance for chaining.
548
+ */
549
+ enumName(name, columnName) {
550
+ const column = this.resolveColumn(columnName);
551
+ if (column.type !== "enum") throw new Error(`Column [${column.name}] is not an enum column.`);
552
+ const enumName = name.trim();
553
+ if (!enumName) throw new Error(`Enum column [${column.name}] must define an enum name.`);
554
+ column.enumName = enumName;
555
+ return this;
556
+ }
557
+ /**
433
558
  * Sets a default value for a column.
434
559
  *
435
560
  * @param value The default scalar value or Prisma expression (e.g. 'now()').
@@ -512,7 +637,10 @@ var TableBuilder = class {
512
637
  * @returns
513
638
  */
514
639
  getColumns() {
515
- return this.columns.map((column) => ({ ...column }));
640
+ return this.columns.map((column) => ({
641
+ ...column,
642
+ enumValues: column.enumValues ? [...column.enumValues] : void 0
643
+ }));
516
644
  }
517
645
  /**
518
646
  * Returns a copy of the defined column names to be dropped from the table.
@@ -553,6 +681,8 @@ var TableBuilder = class {
553
681
  this.columns.push({
554
682
  name,
555
683
  type,
684
+ enumName: options.enumName,
685
+ enumValues: options.enumValues ? [...options.enumValues] : void 0,
556
686
  map: options.map,
557
687
  nullable: options.nullable,
558
688
  unique: options.unique,
@@ -652,7 +782,10 @@ var SchemaBuilder = class {
652
782
  return this.operations.map((operation) => {
653
783
  if (operation.type === "createTable") return {
654
784
  ...operation,
655
- columns: operation.columns.map((column) => ({ ...column })),
785
+ columns: operation.columns.map((column) => ({
786
+ ...column,
787
+ enumValues: column.enumValues ? [...column.enumValues] : void 0
788
+ })),
656
789
  indexes: operation.indexes.map((index) => ({
657
790
  ...index,
658
791
  columns: [...index.columns]
@@ -661,7 +794,10 @@ var SchemaBuilder = class {
661
794
  };
662
795
  if (operation.type === "alterTable") return {
663
796
  ...operation,
664
- addColumns: operation.addColumns.map((column) => ({ ...column })),
797
+ addColumns: operation.addColumns.map((column) => ({
798
+ ...column,
799
+ enumValues: column.enumValues ? [...column.enumValues] : void 0
800
+ })),
665
801
  dropColumns: [...operation.dropColumns],
666
802
  addIndexes: operation.addIndexes.map((index) => ({
667
803
  ...index,
@@ -677,6 +813,8 @@ var SchemaBuilder = class {
677
813
  //#endregion
678
814
  //#region src/helpers/migrations.ts
679
815
  const PRISMA_MODEL_REGEX = /model\s+(\w+)\s*\{[\s\S]*?\n\}/g;
816
+ const PRISMA_ENUM_REGEX = /enum\s+(\w+)\s*\{[\s\S]*?\n\}/g;
817
+ const PRISMA_ENUM_MEMBER_REGEX = /^[A-Za-z][A-Za-z0-9_]*$/;
680
818
  /**
681
819
  * Convert a table name to a PascalCase model name, with basic singularization.
682
820
  *
@@ -704,6 +842,7 @@ const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
704
842
  */
705
843
  const resolvePrismaType = (column) => {
706
844
  if (column.type === "id") return "Int";
845
+ if (column.type === "enum") return resolveEnumName(column);
707
846
  if (column.type === "uuid") return "String";
708
847
  if (column.type === "string" || column.type === "text") return "String";
709
848
  if (column.type === "integer") return "Int";
@@ -713,6 +852,11 @@ const resolvePrismaType = (column) => {
713
852
  if (column.type === "json") return "Json";
714
853
  return "DateTime";
715
854
  };
855
+ const resolveEnumName = (column) => {
856
+ if (column.type !== "enum") throw new ArkormException(`Column [${column.name}] is not an enum column.`);
857
+ if (column.enumName && column.enumName.trim().length > 0) return column.enumName.trim();
858
+ throw new ArkormException(`Enum column [${column.name}] must define an enum name.`);
859
+ };
716
860
  /**
717
861
  * Format a default value for inclusion in a Prisma schema field definition, based on its type.
718
862
  *
@@ -727,6 +871,61 @@ const formatDefaultValue = (value) => {
727
871
  if (typeof value === "boolean") return `@default(${value ? "true" : "false"})`;
728
872
  };
729
873
  /**
874
+ * Format a default value for an enum column as a Prisma @default attribute, validating that it is a non-empty string.
875
+ *
876
+ * @param value
877
+ * @returns
878
+ */
879
+ const formatEnumDefaultValue = (value) => {
880
+ if (value == null) return void 0;
881
+ if (typeof value !== "string" || value.trim().length === 0) throw new ArkormException("Enum default values must be provided as non-empty strings.");
882
+ return `@default(${value.trim()})`;
883
+ };
884
+ /**
885
+ * Normalize an enum value by ensuring it is a non-empty string and trimming whitespace.
886
+ *
887
+ * @param value
888
+ * @returns
889
+ */
890
+ const normalizeEnumValue = (value) => {
891
+ if (typeof value !== "string" || value.trim().length === 0) throw new ArkormException("Enum values must be provided as non-empty strings.");
892
+ const normalized = value.trim();
893
+ if (!PRISMA_ENUM_MEMBER_REGEX.test(normalized)) throw new ArkormException(`Enum value [${normalized}] is not a valid Prisma enum member name.`);
894
+ return normalized;
895
+ };
896
+ /**
897
+ * Extract the enum values from a Prisma enum block string.
898
+ *
899
+ * @param block
900
+ * @returns
901
+ */
902
+ const extractEnumBlockValues = (block) => {
903
+ return block.split("\n").slice(1, -1).map((line) => line.trim()).filter(Boolean);
904
+ };
905
+ const validateEnumValues = (column, enumName, enumValues) => {
906
+ const normalizedValues = enumValues.map(normalizeEnumValue);
907
+ const seen = /* @__PURE__ */ new Set();
908
+ for (const value of normalizedValues) {
909
+ if (seen.has(value)) throw new ArkormException(`Prisma enum [${enumName}] for column [${column.name}] contains duplicate value [${value}].`);
910
+ seen.add(value);
911
+ }
912
+ return normalizedValues;
913
+ };
914
+ /**
915
+ * Validate that a default value for an enum column is included in the defined enum values.
916
+ *
917
+ * @param column
918
+ * @param enumName
919
+ * @param enumValues
920
+ * @returns
921
+ */
922
+ const validateEnumDefaultValue = (column, enumName, enumValues) => {
923
+ if (column.default == null) return;
924
+ const normalizedDefault = normalizeEnumValue(column.default);
925
+ if (enumValues.includes(normalizedDefault)) return;
926
+ throw new ArkormException(`Enum default value [${normalizedDefault}] is not defined in Prisma enum [${enumName}] for column [${column.name}].`);
927
+ };
928
+ /**
730
929
  * Build a single line of a Prisma model field definition based on a SchemaColumn, including type and modifiers.
731
930
  *
732
931
  * @param column
@@ -747,11 +946,82 @@ const buildFieldLine = (column) => {
747
946
  const primary = column.primary ? " @id" : "";
748
947
  const mapped = typeof column.map === "string" && column.map.trim().length > 0 ? ` @map("${column.map.replace(/"/g, "\\\"")}")` : "";
749
948
  const updatedAt = column.updatedAt ? " @updatedAt" : "";
750
- const defaultValue = formatDefaultValue(column.default) ?? (column.type === "uuid" && column.primary ? "@default(uuid())" : void 0);
949
+ const defaultValue = column.type === "enum" ? formatEnumDefaultValue(column.default) : formatDefaultValue(column.default) ?? (column.type === "uuid" && column.primary ? "@default(uuid())" : void 0);
751
950
  const defaultSuffix = defaultValue ? ` ${defaultValue}` : "";
752
951
  return ` ${column.name} ${scalar}${nullable}${primary}${unique}${defaultSuffix}${updatedAt}${mapped}`;
753
952
  };
754
953
  /**
954
+ * Build a Prisma enum block string based on an enum name and its values, validating that
955
+ * at least one value is provided.
956
+ *
957
+ * @param enumName The name of the enum to create.
958
+ * @param values The array of values for the enum.
959
+ * @returns The Prisma enum block string.
960
+ */
961
+ const buildEnumBlock = (enumName, values) => {
962
+ if (values.length === 0) throw new ArkormException(`Enum [${enumName}] must define at least one value.`);
963
+ return `enum ${enumName} {\n${values.map((value) => ` ${value}`).join("\n")}\n}`;
964
+ };
965
+ /**
966
+ * Find the Prisma enum block in a schema string that corresponds to a given enum
967
+ * name, returning its details if found.
968
+ *
969
+ * @param schema The Prisma schema string to search for the enum block.
970
+ * @param enumName The name of the enum to find in the schema.
971
+ * @returns
972
+ */
973
+ const findEnumBlock = (schema, enumName) => {
974
+ const candidates = [...schema.matchAll(PRISMA_ENUM_REGEX)];
975
+ for (const match of candidates) {
976
+ const block = match[0];
977
+ const matchedEnumName = match[1];
978
+ const start = match.index ?? 0;
979
+ const end = start + block.length;
980
+ if (matchedEnumName === enumName) return {
981
+ enumName: matchedEnumName,
982
+ block,
983
+ start,
984
+ end
985
+ };
986
+ }
987
+ return null;
988
+ };
989
+ /**
990
+ * Ensure that Prisma enum blocks exist in the schema for any enum columns defined in a
991
+ * create or alter table operation, adding them if necessary and validating against
992
+ * existing blocks.
993
+ *
994
+ * @param schema The current Prisma schema string to check and modify.
995
+ * @param columns The array of schema column definitions to check for enum types and ensure corresponding blocks exist for.
996
+ * @returns
997
+ */
998
+ const ensureEnumBlocks = (schema, columns) => {
999
+ let nextSchema = schema;
1000
+ for (const column of columns) {
1001
+ if (column.type !== "enum") continue;
1002
+ const enumName = resolveEnumName(column);
1003
+ const enumValues = column.enumValues ?? [];
1004
+ const existing = findEnumBlock(nextSchema, enumName);
1005
+ if (existing) {
1006
+ const existingValues = validateEnumValues(column, enumName, extractEnumBlockValues(existing.block));
1007
+ if (enumValues.length === 0) {
1008
+ validateEnumDefaultValue(column, enumName, existingValues);
1009
+ continue;
1010
+ }
1011
+ const normalizedEnumValues = validateEnumValues(column, enumName, enumValues);
1012
+ if (existingValues.join("|") !== normalizedEnumValues.join("|")) throw new ArkormException(`Prisma enum [${enumName}] already exists with different values.`);
1013
+ validateEnumDefaultValue(column, enumName, existingValues);
1014
+ continue;
1015
+ }
1016
+ if (enumValues.length === 0) throw new ArkormException(`Prisma enum [${enumName}] was not found for column [${column.name}].`);
1017
+ const normalizedEnumValues = validateEnumValues(column, enumName, enumValues);
1018
+ validateEnumDefaultValue(column, enumName, normalizedEnumValues);
1019
+ const block = buildEnumBlock(enumName, normalizedEnumValues);
1020
+ nextSchema = `${nextSchema.trimEnd()}\n\n${block}\n`;
1021
+ }
1022
+ return nextSchema;
1023
+ };
1024
+ /**
755
1025
  * Build a Prisma model-level @@index definition line.
756
1026
  *
757
1027
  * @param index The schema index definition to convert to a Prisma \@\@index line.
@@ -953,8 +1223,9 @@ const findModelBlock = (schema, table) => {
953
1223
  */
954
1224
  const applyCreateTableOperation = (schema, operation) => {
955
1225
  if (findModelBlock(schema, operation.table)) throw new ArkormException(`Prisma model for table [${operation.table}] already exists.`);
1226
+ const schemaWithEnums = ensureEnumBlocks(schema, operation.columns);
956
1227
  const block = buildModelBlock(operation);
957
- return applyInverseRelations(`${schema.trimEnd()}\n\n${block}\n`, toModelName(operation.table), operation.foreignKeys ?? []);
1228
+ return applyInverseRelations(`${schemaWithEnums.trimEnd()}\n\n${block}\n`, toModelName(operation.table), operation.foreignKeys ?? []);
958
1229
  };
959
1230
  /**
960
1231
  * Apply an alter table operation to a Prisma schema string, modifying the model
@@ -967,7 +1238,10 @@ const applyCreateTableOperation = (schema, operation) => {
967
1238
  const applyAlterTableOperation = (schema, operation) => {
968
1239
  const model = findModelBlock(schema, operation.table);
969
1240
  if (!model) throw new ArkormException(`Prisma model for table [${operation.table}] was not found.`);
970
- let block = model.block;
1241
+ const schemaWithEnums = ensureEnumBlocks(schema, operation.addColumns);
1242
+ const refreshedModel = findModelBlock(schemaWithEnums, operation.table);
1243
+ if (!refreshedModel) throw new ArkormException(`Prisma model for table [${operation.table}] was not found.`);
1244
+ let block = refreshedModel.block;
971
1245
  const bodyLines = block.split("\n");
972
1246
  operation.dropColumns.forEach((column) => {
973
1247
  const columnRegex = new RegExp(`^\\s*${escapeRegex(column)}\\s+`);
@@ -997,7 +1271,7 @@ const applyAlterTableOperation = (schema, operation) => {
997
1271
  injectLineIntoModelBody(bodyLines, relationLine, (line) => relationRegex.test(line));
998
1272
  }
999
1273
  block = bodyLines.join("\n");
1000
- return applyInverseRelations(`${schema.slice(0, model.start)}${block}${schema.slice(model.end)}`, model.modelName, operation.addForeignKeys ?? []);
1274
+ return applyInverseRelations(`${schemaWithEnums.slice(0, refreshedModel.start)}${block}${schemaWithEnums.slice(refreshedModel.end)}`, model.modelName, operation.addForeignKeys ?? []);
1001
1275
  };
1002
1276
  /**
1003
1277
  * Apply a drop table operation to a Prisma schema string, removing the model block
@@ -6102,4 +6376,4 @@ var Model = class Model {
6102
6376
  };
6103
6377
 
6104
6378
  //#endregion
6105
- export { ArkormCollection, ArkormException, Attribute, CliApp, ForeignKeyBuilder, InitCommand, InlineFactory, LengthAwarePaginator, MIGRATION_BRAND, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, MigrateRollbackCommand, Migration, MigrationHistoryCommand, MissingDelegateException, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_MODEL_REGEX, Paginator, QueryBuilder, QueryConstraintException, RelationResolutionException, SEEDER_BRAND, SchemaBuilder, ScopeNotDefinedException, SeedCommand, Seeder, TableBuilder, URLDriver, UniqueConstraintResolutionException, UnsupportedAdapterFeatureException, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationRollbackToPrismaSchema, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildFieldLine, buildIndexLine, buildInverseRelationLine, buildMigrationIdentity, buildMigrationRunId, buildMigrationSource, buildModelBlock, buildRelationLine, computeMigrationChecksum, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, deriveCollectionFieldName, deriveInverseRelationAlias, deriveRelationFieldName, ensureArkormConfigLoading, escapeRegex, findAppliedMigration, findModelBlock, formatDefaultValue, formatRelationAction, generateMigrationFile, getActiveTransactionClient, getDefaultStubsPath, getLastMigrationRun, getLatestAppliedMigrations, getMigrationPlan, getRuntimePaginationCurrentPageResolver, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, isMigrationApplied, isTransactionCapableClient, loadArkormConfig, markMigrationApplied, markMigrationRun, pad, readAppliedMigrationsState, removeAppliedMigration, resetArkormRuntimeForTests, resolveCast, resolveMigrationClassName, resolveMigrationStateFilePath, resolvePrismaType, runArkormTransaction, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName, writeAppliedMigrationsState };
6379
+ export { ArkormCollection, ArkormException, Attribute, CliApp, EnumBuilder, ForeignKeyBuilder, InitCommand, InlineFactory, LengthAwarePaginator, MIGRATION_BRAND, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, MigrateRollbackCommand, Migration, MigrationHistoryCommand, MissingDelegateException, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_ENUM_MEMBER_REGEX, PRISMA_ENUM_REGEX, PRISMA_MODEL_REGEX, Paginator, QueryBuilder, QueryConstraintException, RelationResolutionException, SEEDER_BRAND, SchemaBuilder, ScopeNotDefinedException, SeedCommand, Seeder, TableBuilder, URLDriver, UniqueConstraintResolutionException, UnsupportedAdapterFeatureException, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationRollbackToPrismaSchema, applyMigrationToPrismaSchema, applyOperationsToPrismaSchema, buildEnumBlock, buildFieldLine, buildIndexLine, buildInverseRelationLine, buildMigrationIdentity, buildMigrationRunId, buildMigrationSource, buildModelBlock, buildRelationLine, computeMigrationChecksum, configureArkormRuntime, createMigrationTimestamp, createPrismaAdapter, createPrismaDelegateMap, defineConfig, defineFactory, deriveCollectionFieldName, deriveInverseRelationAlias, deriveRelationFieldName, ensureArkormConfigLoading, escapeRegex, findAppliedMigration, findEnumBlock, findModelBlock, formatDefaultValue, formatEnumDefaultValue, formatRelationAction, generateMigrationFile, getActiveTransactionClient, getDefaultStubsPath, getLastMigrationRun, getLatestAppliedMigrations, getMigrationPlan, getRuntimePaginationCurrentPageResolver, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, isMigrationApplied, isTransactionCapableClient, loadArkormConfig, markMigrationApplied, markMigrationRun, pad, readAppliedMigrationsState, removeAppliedMigration, resetArkormRuntimeForTests, resolveCast, resolveEnumName, resolveMigrationClassName, resolveMigrationStateFilePath, resolvePrismaType, runArkormTransaction, runMigrationWithPrisma, runPrismaCommand, toMigrationFileSlug, toModelName, writeAppliedMigrationsState };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkormx",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Modern TypeScript-first ORM for Node.js.",
5
5
  "keywords": [
6
6
  "orm",