arkormx 2.4.5 → 2.4.7

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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as deletePersistedColumnMappingsState, $t as supportsDatabaseCreation, A as isDelegateLike, At as buildModelBlock, B as getRegisteredSeeders, Bt as findModelBlock, C as getRuntimeAdapter, Cn as resolveMigrationStateFilePath, Ct as applyMigrationToPrismaSchema, D as getRuntimePaginationURLDriverFactory, Dn as RuntimeModuleLoader, Dt as buildIndexLine, E as getRuntimePaginationCurrentPageResolver, En as writeAppliedMigrationsStateToStore, Et as buildFieldLine, F as runArkormTransaction, Ft as deriveRelationAlias, G as registerFactories, Gt as getMigrationPlan, H as loadMigrationsFrom, Ht as formatEnumDefaultValue, I as getRegisteredFactories, It as deriveRelationFieldName, J as registerPaths, Jt as resolveMigrationClassName, K as registerMigrations, Kt as pad, L as getRegisteredMigrations, Lt as deriveSingularFieldName, M as isTransactionCapableClient, Mn as ArkormCollection, Mt as createMigrationTimestamp, N as loadArkormConfig, Nn as ArkormException, Nt as deriveCollectionFieldName, O as getRuntimePrismaClient, On as UnsupportedAdapterFeatureException, Ot as buildInverseRelationLine, P as resetArkormRuntimeForTests, Pt as deriveInverseRelationAlias, Q as createEmptyPersistedColumnMappingsState, Qt as stripPrismaSchemaModelsAndEnums, R as getRegisteredModels, Rt as escapeRegex, S as getDefaultStubsPath, Sn as removeAppliedMigration, St as applyMigrationToDatabase, T as getRuntimeDebugHandler, Tn as writeAppliedMigrationsState, Tt as buildEnumBlock, U as loadModelsFrom, Ut as formatRelationAction, V as loadFactoriesFrom, Vt as formatDefaultValue, W as loadSeedersFrom, Wt as generateMigrationFile, X as resetRuntimeRegistryForTests, Xt as runMigrationWithPrisma, Y as registerSeeders, Yt as resolvePrismaType, Z as applyOperationsToPersistedColumnMappingsState, Zt as runPrismaCommand, _ as defineConfig, _n as isMigrationApplied, _t as applyAlterTableOperation, a as HasOneRelation, an as EnumBuilder, at as getPersistedTimestampColumns, b as getActiveTransactionAdapter, bn as readAppliedMigrationsState, bt as applyMigrationRollbackToDatabase, c as BelongsToRelation, cn as PrimaryKeyGenerationPlanner, ct as resetPersistedColumnMappingsCache, d as Relation, dn as computeMigrationChecksum, dt as syncPersistedColumnMappingsFromState, en as supportsDatabaseMigrationExecution, et as getPersistedColumnMap, f as LengthAwarePaginator, fn as createEmptyAppliedMigrationsState, ft as validatePersistedMetadataFeaturesForMigrations, g as configureArkormRuntime, gn as getLatestAppliedMigrations, gt as PRISMA_MODEL_REGEX, h as bindAdapterToModels, hn as getLastMigrationRun, ht as PRISMA_ENUM_REGEX, i as HasOneThroughRelation, in as SchemaBuilder, it as getPersistedTableMetadata, j as isQuerySchemaLike, jn as RelationResolutionException, jt as buildRelationLine, k as getUserConfig, kn as SetBasedEagerLoader, kt as buildMigrationSource, ln as buildMigrationIdentity, lt as resolveColumnMappingsFilePath, m as URLDriver, mn as findAppliedMigration, mt as PRISMA_ENUM_MEMBER_REGEX, n as MorphOneRelation, nn as toMigrationFileSlug, nt as getPersistedEnumTsType, o as HasManyThroughRelation, on as TableBuilder, ot as readPersistedColumnMappingsState, p as Paginator, pn as deleteAppliedMigrationsStateFromStore, pt as writePersistedColumnMappingsState, q as registerModels, qt as resolveEnumName, r as MorphManyRelation, rn as toModelName, rt as getPersistedPrimaryKeyGeneration, s as HasManyRelation, sn as ForeignKeyBuilder, st as rebuildPersistedColumnMappingsState, t as MorphToManyRelation, tn as supportsDatabaseReset, tt as getPersistedEnumMap, u as BelongsToManyRelation, un as buildMigrationRunId, ut as resolvePersistedMetadataFeatures, v as emitRuntimeDebugEvent, vn as markMigrationApplied, vt as applyCreateTableOperation, w as getRuntimeClient, wn as supportsDatabaseMigrationState, wt as applyOperationsToPrismaSchema, x as getActiveTransactionClient, xn as readAppliedMigrationsStateFromStore, xt as applyMigrationRollbackToPrismaSchema, y as ensureArkormConfigLoading, yn as markMigrationRun, yt as applyDropTableOperation, z as getRegisteredPaths, zt as findEnumBlock } from "./relationship-DcvK5Xn-.mjs";
1
+ import { $ as deletePersistedColumnMappingsState, $t as runPrismaCommand, A as isDelegateLike, An as UnsupportedAdapterFeatureException, At as buildModelBlock, B as getRegisteredSeeders, Bt as escapeRegex, C as getRuntimeAdapter, Cn as readAppliedMigrationsStateFromStore, Ct as applyMigrationToPrismaSchema, D as getRuntimePaginationURLDriverFactory, Dn as writeAppliedMigrationsState, Dt as buildIndexLine, E as getRuntimePaginationCurrentPageResolver, En as supportsDatabaseMigrationState, Et as buildFieldLine, F as runArkormTransaction, Fn as ArkormException, Ft as deriveCollectionFieldName, G as registerFactories, Gt as formatRelationAction, H as loadMigrationsFrom, Ht as findModelBlock, I as getRegisteredFactories, It as deriveInverseRelationAlias, J as registerPaths, Jt as pad, K as registerMigrations, Kt as generateMigrationFile, L as getRegisteredMigrations, Lt as deriveRelationAlias, M as isTransactionCapableClient, Mt as buildRelationLine, N as loadArkormConfig, Nn as RelationResolutionException, Nt as buildUniqueConstraintLine, O as getRuntimePrismaClient, On as writeAppliedMigrationsStateToStore, Ot as buildInverseRelationLine, P as resetArkormRuntimeForTests, Pn as ArkormCollection, Pt as createMigrationTimestamp, Q as createEmptyPersistedColumnMappingsState, Qt as runMigrationWithPrisma, R as getRegisteredModels, Rt as deriveRelationFieldName, S as getDefaultStubsPath, Sn as readAppliedMigrationsState, St as applyMigrationToDatabase, T as getRuntimeDebugHandler, Tn as resolveMigrationStateFilePath, Tt as buildEnumBlock, U as loadModelsFrom, Ut as formatDefaultValue, V as loadFactoriesFrom, Vt as findEnumBlock, W as loadSeedersFrom, Wt as formatEnumDefaultValue, X as resetRuntimeRegistryForTests, Xt as resolveMigrationClassName, Y as registerSeeders, Yt as resolveEnumName, Z as applyOperationsToPersistedColumnMappingsState, Zt as resolvePrismaType, _ as defineConfig, _n as getLastMigrationRun, _t as applyAlterTableOperation, a as HasOneRelation, an as toModelName, at as getPersistedTimestampColumns, b as getActiveTransactionAdapter, bn as markMigrationApplied, bt as applyMigrationRollbackToDatabase, c as BelongsToRelation, cn as TableBuilder, ct as resetPersistedColumnMappingsCache, d as Relation, dn as buildMigrationIdentity, dt as syncPersistedColumnMappingsFromState, en as stripPrismaSchemaModelsAndEnums, et as getPersistedColumnMap, f as LengthAwarePaginator, fn as buildMigrationRunId, ft as validatePersistedMetadataFeaturesForMigrations, g as configureArkormRuntime, gn as findAppliedMigration, gt as PRISMA_MODEL_REGEX, h as bindAdapterToModels, hn as deleteAppliedMigrationsStateFromStore, ht as PRISMA_ENUM_REGEX, i as HasOneThroughRelation, in as toMigrationFileSlug, it as getPersistedTableMetadata, j as isQuerySchemaLike, jn as SetBasedEagerLoader, jt as buildPrimaryKeyLine, k as getUserConfig, kn as RuntimeModuleLoader, kt as buildMigrationSource, ln as ForeignKeyBuilder, lt as resolveColumnMappingsFilePath, m as URLDriver, mn as createEmptyAppliedMigrationsState, mt as PRISMA_ENUM_MEMBER_REGEX, n as MorphOneRelation, nn as supportsDatabaseMigrationExecution, nt as getPersistedEnumTsType, o as HasManyThroughRelation, on as SchemaBuilder, ot as readPersistedColumnMappingsState, p as Paginator, pn as computeMigrationChecksum, pt as writePersistedColumnMappingsState, q as registerModels, qt as getMigrationPlan, r as MorphManyRelation, rn as supportsDatabaseReset, rt as getPersistedPrimaryKeyGeneration, s as HasManyRelation, sn as EnumBuilder, st as rebuildPersistedColumnMappingsState, t as MorphToManyRelation, tn as supportsDatabaseCreation, tt as getPersistedEnumMap, u as BelongsToManyRelation, un as PrimaryKeyGenerationPlanner, ut as resolvePersistedMetadataFeatures, v as emitRuntimeDebugEvent, vn as getLatestAppliedMigrations, vt as applyCreateTableOperation, w as getRuntimeClient, wn as removeAppliedMigration, wt as applyOperationsToPrismaSchema, x as getActiveTransactionClient, xn as markMigrationRun, xt as applyMigrationRollbackToPrismaSchema, y as ensureArkormConfigLoading, yn as isMigrationApplied, yt as applyDropTableOperation, z as getRegisteredPaths, zt as deriveSingularFieldName } from "./relationship-BkNxySap.mjs";
2
2
  import { Pool } from "pg";
3
3
  import { join, resolve } from "node:path";
4
4
  import { createRequire } from "module";
@@ -9,6 +9,7 @@ import { str } from "@h3ravel/support";
9
9
  import { sql } from "kysely";
10
10
  import { Logger } from "@h3ravel/shared";
11
11
  import { Command } from "@h3ravel/musket";
12
+ import { AsyncLocalStorage } from "node:async_hooks";
12
13
 
13
14
  //#region src/Exceptions/QueryExecutionException.ts
14
15
  var QueryExecutionException = class extends ArkormException {
@@ -187,6 +188,17 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
187
188
  const mappedColumns = index.columns.map((column) => this.quoteIdentifier(this.resolveSchemaColumnName(column, columns))).join(", ");
188
189
  return `create index if not exists ${this.quoteIdentifier(this.resolveSchemaIndexName(table, index))} on ${this.quoteIdentifier(table)} (${mappedColumns})`;
189
190
  }
191
+ buildSchemaPrimaryKeyConstraint(table, primaryKey, columns = []) {
192
+ const name = primaryKey.name?.trim() || `${table}_pkey`;
193
+ const mappedColumns = primaryKey.columns.map((column) => this.quoteIdentifier(this.resolveSchemaColumnName(column, columns))).join(", ");
194
+ return `constraint ${this.quoteIdentifier(name)} primary key (${mappedColumns})`;
195
+ }
196
+ buildSchemaUniqueConstraint(table, constraint, columns = []) {
197
+ const mappedColumnNames = constraint.columns.map((column) => this.resolveSchemaColumnName(column, columns));
198
+ const name = constraint.name?.trim() || `${table}_${mappedColumnNames.join("_")}_key`;
199
+ const mappedColumns = mappedColumnNames.map((column) => this.quoteIdentifier(column)).join(", ");
200
+ return `constraint ${this.quoteIdentifier(name)} unique (${mappedColumns})`;
201
+ }
190
202
  async ensureEnumTypes(table, columns, executor = this.db) {
191
203
  for (const column of columns) {
192
204
  if (column.type !== "enum") continue;
@@ -207,8 +219,15 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
207
219
  const table = this.resolveMappedTable(operation.table);
208
220
  await this.ensureEnumTypes(table, operation.columns, executor);
209
221
  const columnDefinitions = operation.columns.map((column) => this.buildSchemaColumnDefinition(table, column));
222
+ const primaryKeys = operation.primaryKey ? [this.buildSchemaPrimaryKeyConstraint(table, operation.primaryKey, operation.columns)] : [];
223
+ const uniqueConstraints = (operation.uniqueConstraints ?? []).map((constraint) => this.buildSchemaUniqueConstraint(table, constraint, operation.columns));
210
224
  const foreignKeys = (operation.foreignKeys ?? []).map((foreignKey) => this.buildSchemaForeignKeyConstraint(table, foreignKey, operation.columns));
211
- const definitions = [...columnDefinitions, ...foreignKeys].join(", ");
225
+ const definitions = [
226
+ ...columnDefinitions,
227
+ ...primaryKeys,
228
+ ...uniqueConstraints,
229
+ ...foreignKeys
230
+ ].join(", ");
212
231
  await this.executeRawStatement(`create table if not exists ${this.quoteIdentifier(table)} (${definitions})`, executor);
213
232
  for (const index of operation.indexes ?? []) await this.executeRawStatement(this.buildSchemaIndexStatement(table, index, operation.columns), executor);
214
233
  }
@@ -218,6 +237,8 @@ var KyselyDatabaseAdapter = class KyselyDatabaseAdapter {
218
237
  for (const column of operation.addColumns) await this.executeRawStatement(`alter table ${this.quoteIdentifier(table)} add column if not exists ${this.buildSchemaColumnDefinition(table, column)}`, executor);
219
238
  for (const column of operation.dropColumns) await this.executeRawStatement(`alter table ${this.quoteIdentifier(table)} drop column if exists ${this.quoteIdentifier(column)}`, executor);
220
239
  for (const foreignKey of operation.addForeignKeys ?? []) await this.executeRawStatement(`alter table ${this.quoteIdentifier(table)} add ${this.buildSchemaForeignKeyConstraint(table, foreignKey, operation.addColumns)}`, executor);
240
+ if (operation.addPrimaryKey) await this.executeRawStatement(`alter table ${this.quoteIdentifier(table)} add ${this.buildSchemaPrimaryKeyConstraint(table, operation.addPrimaryKey, operation.addColumns)}`, executor);
241
+ for (const constraint of operation.addUniqueConstraints ?? []) await this.executeRawStatement(`alter table ${this.quoteIdentifier(table)} add ${this.buildSchemaUniqueConstraint(table, constraint, operation.addColumns)}`, executor);
221
242
  for (const index of operation.addIndexes ?? []) await this.executeRawStatement(this.buildSchemaIndexStatement(table, index, operation.addColumns), executor);
222
243
  }
223
244
  async executeDropTableOperation(operation, executor) {
@@ -3528,6 +3549,9 @@ var Seeder = class Seeder {
3528
3549
  static {
3529
3550
  this[SEEDER_BRAND] = true;
3530
3551
  }
3552
+ static {
3553
+ this.executionReport = new AsyncLocalStorage();
3554
+ }
3531
3555
  /**
3532
3556
  * Runs one or more seeders.
3533
3557
  *
@@ -3537,6 +3561,19 @@ var Seeder = class Seeder {
3537
3561
  await Seeder.runSeeders(...seeders);
3538
3562
  }
3539
3563
  /**
3564
+ * Run seeders and return every seeder class executed, including nested calls.
3565
+ *
3566
+ * @param seeders
3567
+ * @returns
3568
+ */
3569
+ static async runWithReport(...seeders) {
3570
+ const report = [];
3571
+ await this.executionReport.run(report, async () => {
3572
+ await this.runSeeders(...seeders);
3573
+ });
3574
+ return report;
3575
+ }
3576
+ /**
3540
3577
  * Converts a SeederInput into a Seeder instance.
3541
3578
  *
3542
3579
  * @param input The SeederInput to convert.
@@ -3560,7 +3597,11 @@ var Seeder = class Seeder {
3560
3597
  all.push(current);
3561
3598
  return all;
3562
3599
  }, []);
3563
- for (const seeder of queue) await this.toSeederInstance(seeder).run();
3600
+ for (const seeder of queue) {
3601
+ const instance = this.toSeederInstance(seeder);
3602
+ this.executionReport.getStore()?.push(instance.constructor.name);
3603
+ await instance.run();
3604
+ }
3564
3605
  }
3565
3606
  };
3566
3607
 
@@ -3593,9 +3634,10 @@ var SeedCommand = class extends Command {
3593
3634
  if (seederDirs.length === 0 && getRegisteredSeeders().length === 0) return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(configuredSeedersDir)}`);
3594
3635
  const classes = this.option("all") ? await this.loadAllSeeders(seederDirs) : await this.loadNamedSeeder(seederDirs, this.argument("name") ?? "DatabaseSeeder");
3595
3636
  if (classes.length === 0) return void this.error("ERROR: No seeder classes found to run.");
3596
- for (const SeederClassItem of classes) await new SeederClassItem().run();
3637
+ const executedSeeders = [];
3638
+ for (const SeederClassItem of classes) executedSeeders.push(...await Seeder.runWithReport(new SeederClassItem()));
3597
3639
  this.success("Database seeding completed");
3598
- classes.forEach((cls) => this.success(this.app.splitLogger("Seeded", cls.name)));
3640
+ executedSeeders.forEach((name) => this.success(this.app.splitLogger("Seeded", name)));
3599
3641
  }
3600
3642
  /**
3601
3643
  * Load all seeder classes from the specified directory.
@@ -3664,191 +3706,42 @@ var logo_default = String.raw`
3664
3706
  `;
3665
3707
 
3666
3708
  //#endregion
3667
- //#region src/database/factories.ts
3668
- /**
3669
- * Base class for defining model factories.
3670
- * Not meant to be used directly.
3671
- *
3672
- * @template TModel The type of model the factory creates.
3673
- * @template TAttributes The type of attributes used to create the model.
3674
- * @author Legacy (3m1n3nc3)
3675
- * @since 0.1.0
3676
- */
3677
- var ModelFactory = class ModelFactory {
3678
- constructor() {
3679
- this.amount = 1;
3680
- this.sequence = 0;
3681
- this.states = [];
3682
- }
3683
- /**
3684
- * Set the number of models to create.
3685
- *
3686
- * @param amount
3687
- * @returns
3688
- */
3689
- count(amount) {
3690
- this.amount = Math.max(1, Math.floor(amount));
3691
- return this;
3692
- }
3693
- /**
3694
- * Define a state transformation for the factory.
3695
- * States are applied in the order they were defined.
3696
- *
3697
- * @param resolver A function that takes the current attributes and sequence number, and returns the transformed attributes.
3698
- * @returns The factory instance for chaining.
3699
- */
3700
- state(resolver) {
3701
- this.states.push(resolver);
3702
- return this;
3703
- }
3704
- /**
3705
- * Create a new model instance without saving it to the database.
3706
- *
3707
- * @param overrides
3708
- * @returns
3709
- */
3710
- make(overrides = {}) {
3711
- const attributes = this.buildAttributes(overrides);
3712
- return new this.model(attributes);
3713
- }
3714
- /**
3715
- * Create a new model instance from an async factory definition without
3716
- * saving it to the database.
3717
- *
3718
- * @param overrides
3719
- * @returns
3720
- */
3721
- async makeAsync(overrides = {}) {
3722
- const attributes = await this.buildAttributesAsync(overrides);
3723
- return new this.model(attributes);
3724
- }
3725
- /**
3726
- * Create multiple model instances without saving them to the database.
3727
- *
3728
- * @param amount
3729
- * @param overrides
3730
- * @returns
3731
- */
3732
- makeMany(amount = this.amount, overrides = {}) {
3733
- const total = Math.max(1, Math.floor(amount));
3734
- return Array.from({ length: total }, () => this.make(overrides));
3735
- }
3736
- /**
3737
- * Create multiple model instances from async factory definitions without
3738
- * saving them to the database.
3739
- *
3740
- * @param amount
3741
- * @param overrides
3742
- * @returns
3743
- */
3744
- async makeManyAsync(amount = this.amount, overrides = {}) {
3745
- const total = Math.max(1, Math.floor(amount));
3746
- const models = [];
3747
- for (let index = 0; index < total; index++) models.push(await this.makeAsync(overrides));
3748
- return models;
3749
- }
3750
- /**
3751
- * Create a new model instance and save it to the database.
3752
- *
3753
- * @param overrides
3754
- * @returns
3755
- */
3756
- async create(overrides = {}) {
3757
- const model = await this.makeAsync(overrides);
3758
- if (typeof model.save !== "function") throw new Error("Factory model does not support save().");
3759
- return await model.save();
3760
- }
3761
- /**
3762
- * Create multiple model instances and save them to the database.
3763
- *
3764
- * @param amount
3765
- * @param overrides
3766
- * @returns
3767
- */
3768
- async createMany(amount = this.amount, overrides = {}) {
3769
- const models = await this.makeManyAsync(amount, overrides);
3770
- return await Promise.all(models.map(async (model) => {
3771
- if (typeof model.save !== "function") throw new Error("Factory model does not support save().");
3772
- return await model.save();
3773
- }));
3774
- }
3775
- /**
3776
- * Build the attributes for a model instance, applying the factory
3777
- * definition and any defined states, and merging in any overrides.
3778
- *
3779
- * @param overrides
3780
- * @returns
3781
- */
3782
- buildAttributes(overrides) {
3783
- const sequence = this.sequence;
3784
- this.sequence += 1;
3785
- let resolved = this.definition(sequence);
3786
- if (ModelFactory.isPromiseLike(resolved)) {
3787
- this.sequence = sequence;
3788
- throw new Error("This factory has an async definition. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
3789
- }
3790
- for (const state of this.states) {
3791
- resolved = state(resolved, sequence);
3792
- if (ModelFactory.isPromiseLike(resolved)) {
3793
- this.sequence = sequence;
3794
- throw new Error("This factory has an async state. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
3795
- }
3796
- }
3797
- return {
3798
- ...resolved,
3799
- ...overrides
3800
- };
3801
- }
3802
- /**
3803
- * Build attributes for async and sync factory definitions.
3804
- *
3805
- * @param overrides
3806
- * @returns
3807
- */
3808
- async buildAttributesAsync(overrides) {
3809
- const sequence = this.sequence;
3810
- this.sequence += 1;
3811
- let resolved = await this.definition(sequence);
3812
- for (const state of this.states) resolved = await state(resolved, sequence);
3813
- return {
3814
- ...resolved,
3815
- ...overrides
3816
- };
3817
- }
3818
- static isPromiseLike(value) {
3819
- return typeof value?.then === "function";
3820
- }
3709
+ //#region src/helpers/runtime-compatibility.ts
3710
+ const isObjectLike = (value) => {
3711
+ return Boolean(value) && typeof value === "object";
3821
3712
  };
3822
- /**
3823
- * A helper class for defining factories using an inline definition
3824
- * function, without needing to create a separate factory class.
3825
- *
3826
- * @template TModel
3827
- * @template TAttributes
3828
- * @author Legacy (3m1n3nc3)
3829
- * @since 0.1.0
3830
- */
3831
- var InlineFactory = class extends ModelFactory {
3832
- constructor(model, resolver) {
3833
- super();
3834
- this.resolver = resolver;
3835
- this.model = model;
3836
- }
3837
- definition(sequence) {
3838
- return this.resolver(sequence);
3839
- }
3713
+ const isCompatibilityClient = (value) => {
3714
+ return Boolean(value) && typeof value === "object";
3840
3715
  };
3841
- /**
3842
- * Define a factory for a given model using an inline definition function.
3843
- *
3844
- * @template TModel The type of model the factory creates.
3845
- * @template TAttributes The type of attributes used to create the model.
3846
- * @param model The model constructor.
3847
- * @param definition The factory definition function.
3848
- * @returns A new instance of the model factory.
3849
- */
3850
- const defineFactory = (model, definition) => {
3851
- return new InlineFactory(model, definition);
3716
+ const getCompatibilitySources = (preferredClient) => {
3717
+ const activeTransactionClient = getActiveTransactionClient();
3718
+ const runtimeClient = getRuntimeClient();
3719
+ return activeTransactionClient ? [
3720
+ activeTransactionClient,
3721
+ preferredClient,
3722
+ runtimeClient
3723
+ ] : [preferredClient, runtimeClient];
3724
+ };
3725
+ const getRuntimeCompatibilityAdapter = (preferredClient) => {
3726
+ const client = getCompatibilitySources(preferredClient).find((source) => isCompatibilityClient(source));
3727
+ if (!client) return void 0;
3728
+ return createPrismaCompatibilityAdapter(client);
3729
+ };
3730
+ const resolveRuntimeCompatibilityQuerySchema = (candidates, preferredClient) => {
3731
+ return getCompatibilitySources(preferredClient).flatMap((source) => {
3732
+ if (!isObjectLike(source)) return [];
3733
+ return candidates.map((candidate) => source[candidate]);
3734
+ }).find((candidate) => isQuerySchemaLike(candidate));
3735
+ };
3736
+ const resolveRuntimeCompatibilityQuerySchemaOrThrow = (key, candidates, modelName, preferredClient) => {
3737
+ const resolved = resolveRuntimeCompatibilityQuerySchema(candidates, preferredClient);
3738
+ if (!resolved) throw new MissingDelegateException(`Database delegate [${key}] is not configured.`, {
3739
+ operation: "getDelegate",
3740
+ model: modelName,
3741
+ delegate: key,
3742
+ meta: { candidates }
3743
+ });
3744
+ return resolved;
3852
3745
  };
3853
3746
 
3854
3747
  //#endregion
@@ -6324,164 +6217,6 @@ var QueryBuilder = class QueryBuilder {
6324
6217
  }
6325
6218
  };
6326
6219
 
6327
- //#endregion
6328
- //#region src/helpers/runtime-compatibility.ts
6329
- const isObjectLike = (value) => {
6330
- return Boolean(value) && typeof value === "object";
6331
- };
6332
- const isCompatibilityClient = (value) => {
6333
- return Boolean(value) && typeof value === "object";
6334
- };
6335
- const getCompatibilitySources = (preferredClient) => {
6336
- const activeTransactionClient = getActiveTransactionClient();
6337
- const runtimeClient = getRuntimeClient();
6338
- return activeTransactionClient ? [
6339
- activeTransactionClient,
6340
- preferredClient,
6341
- runtimeClient
6342
- ] : [preferredClient, runtimeClient];
6343
- };
6344
- const getRuntimeCompatibilityAdapter = (preferredClient) => {
6345
- const client = getCompatibilitySources(preferredClient).find((source) => isCompatibilityClient(source));
6346
- if (!client) return void 0;
6347
- return createPrismaCompatibilityAdapter(client);
6348
- };
6349
- const resolveRuntimeCompatibilityQuerySchema = (candidates, preferredClient) => {
6350
- return getCompatibilitySources(preferredClient).flatMap((source) => {
6351
- if (!isObjectLike(source)) return [];
6352
- return candidates.map((candidate) => source[candidate]);
6353
- }).find((candidate) => isQuerySchemaLike(candidate));
6354
- };
6355
- const resolveRuntimeCompatibilityQuerySchemaOrThrow = (key, candidates, modelName, preferredClient) => {
6356
- const resolved = resolveRuntimeCompatibilityQuerySchema(candidates, preferredClient);
6357
- if (!resolved) throw new MissingDelegateException(`Database delegate [${key}] is not configured.`, {
6358
- operation: "getDelegate",
6359
- model: modelName,
6360
- delegate: key,
6361
- meta: { candidates }
6362
- });
6363
- return resolved;
6364
- };
6365
-
6366
- //#endregion
6367
- //#region src/DB.ts
6368
- const defaultSoftDeleteConfig = {
6369
- enabled: false,
6370
- column: "deletedAt"
6371
- };
6372
- var DB = class DB {
6373
- constructor(adapter) {
6374
- this.scopedAdapter = adapter;
6375
- }
6376
- static setAdapter(adapter) {
6377
- this.adapter = adapter;
6378
- }
6379
- static getAdapter() {
6380
- const runtimeAdapter = getRuntimeAdapter();
6381
- if (runtimeAdapter) return runtimeAdapter;
6382
- if (this.adapter) return this.adapter;
6383
- return getRuntimeCompatibilityAdapter();
6384
- }
6385
- getAdapter() {
6386
- return this.scopedAdapter ?? DB.getAdapter();
6387
- }
6388
- static table(table, options = {}) {
6389
- return new DB().table(table, options);
6390
- }
6391
- table(table, options = {}) {
6392
- return DB.createTableModel(table, options, this.getAdapter()).query();
6393
- }
6394
- static async raw(sql, bindings = []) {
6395
- return await new DB().raw(sql, bindings);
6396
- }
6397
- async raw(sql, bindings = []) {
6398
- const adapter = this.getAdapter();
6399
- if (!adapter) throw new ArkormException("Raw queries require a configured database adapter.", {
6400
- code: "ADAPTER_NOT_CONFIGURED",
6401
- operation: "db.raw"
6402
- });
6403
- if (!adapter.rawQuery) throw new UnsupportedAdapterFeatureException("Raw queries are not supported by the current adapter.", {
6404
- operation: "db.raw",
6405
- meta: { feature: "rawQuery" }
6406
- });
6407
- const rows = await adapter.rawQuery({
6408
- sql,
6409
- bindings
6410
- });
6411
- return ArkormCollection.make(rows);
6412
- }
6413
- static async transaction(callback, context) {
6414
- return await new DB().transaction(callback, context);
6415
- }
6416
- async transaction(callback, context) {
6417
- const adapter = this.getAdapter();
6418
- if (!adapter) throw new ArkormException("DB transactions require a configured database adapter.", {
6419
- code: "ADAPTER_NOT_CONFIGURED",
6420
- operation: "db.transaction"
6421
- });
6422
- return await adapter.transaction(async (transactionAdapter) => {
6423
- return await callback(new DB(transactionAdapter));
6424
- }, context);
6425
- }
6426
- static createTableModel(table, options, adapter) {
6427
- const primaryKey = options.primaryKey ?? "id";
6428
- const resolvedAdapter = options.adapter ?? adapter ?? DB.getAdapter();
6429
- const persistedMetadata = DB.resolvePersistedTableMetadata(table, options, resolvedAdapter);
6430
- const columns = {
6431
- ...persistedMetadata.columns,
6432
- ...options.columns ?? {}
6433
- };
6434
- const softDelete = options.softDelete ?? defaultSoftDeleteConfig;
6435
- const primaryKeyGeneration = options.primaryKeyGeneration ? { ...options.primaryKeyGeneration } : persistedMetadata.primaryKeyGeneration?.column === primaryKey ? {
6436
- strategy: persistedMetadata.primaryKeyGeneration.strategy,
6437
- prismaDefault: persistedMetadata.primaryKeyGeneration.prismaDefault,
6438
- databaseDefault: persistedMetadata.primaryKeyGeneration.databaseDefault,
6439
- runtimeFactory: persistedMetadata.primaryKeyGeneration.runtimeFactory
6440
- } : void 0;
6441
- const timestampColumns = options.timestampColumns?.map((column) => ({ ...column })) ?? persistedMetadata.timestampColumns?.map((column) => ({ ...column }));
6442
- const buildMetadata = () => {
6443
- return {
6444
- table,
6445
- primaryKey,
6446
- columns: { ...columns },
6447
- softDelete: { ...softDelete },
6448
- primaryKeyGeneration,
6449
- timestampColumns
6450
- };
6451
- };
6452
- const modelStatic = {
6453
- query: () => new QueryBuilder(modelStatic, modelStatic.getAdapter()),
6454
- hydrate: (attributes) => ({ ...attributes }),
6455
- hydrateMany: (attributes) => attributes.map((attribute) => ({ ...attribute })),
6456
- hydrateRetrieved: async (attributes) => ({ ...attributes }),
6457
- hydrateManyRetrieved: async (attributes) => attributes.map((attribute) => ({ ...attribute })),
6458
- getAdapter: () => resolvedAdapter,
6459
- getColumnMap: () => ({ ...columns }),
6460
- getColumnName: (attribute) => columns[attribute] ?? attribute,
6461
- getModelMetadata: () => buildMetadata(),
6462
- getPrimaryKey: () => primaryKey,
6463
- getRelationMetadata: () => null,
6464
- setAdapter: () => {},
6465
- getSoftDeleteConfig: () => ({ ...softDelete }),
6466
- getTable: () => table
6467
- };
6468
- return modelStatic;
6469
- }
6470
- static resolvePersistedTableMetadata(table, options, adapter) {
6471
- if (options.persistedMetadata === false) return {
6472
- columns: {},
6473
- enums: {}
6474
- };
6475
- const persistedMetadataOptions = typeof options.persistedMetadata === "object" ? options.persistedMetadata : {};
6476
- return getPersistedTableMetadata(table, {
6477
- cwd: persistedMetadataOptions.cwd,
6478
- configuredPath: persistedMetadataOptions.configuredPath,
6479
- features: resolvePersistedMetadataFeatures(getUserConfig("features")),
6480
- strict: persistedMetadataOptions.strict ?? (Boolean(adapter) && !(adapter instanceof PrismaDatabaseAdapter))
6481
- });
6482
- }
6483
- };
6484
-
6485
6220
  //#endregion
6486
6221
  //#region src/Model.ts
6487
6222
  /**
@@ -7724,6 +7459,552 @@ var Model = class Model {
7724
7459
  }
7725
7460
  };
7726
7461
 
7462
+ //#endregion
7463
+ //#region src/database/factories.ts
7464
+ /**
7465
+ * Base class for defining model factories.
7466
+ * Not meant to be used directly.
7467
+ *
7468
+ * @template TModel The type of model the factory creates.
7469
+ * @template TAttributes The type of attributes used to create the model.
7470
+ * @author Legacy (3m1n3nc3)
7471
+ * @since 0.1.0
7472
+ */
7473
+ var ModelFactory = class ModelFactory {
7474
+ constructor() {
7475
+ this.amount = 1;
7476
+ this.sequence = 0;
7477
+ this.states = [];
7478
+ this.configured = false;
7479
+ this.afterMakingCallbacks = [];
7480
+ this.afterCreatingCallbacks = [];
7481
+ this.hasRelations = [];
7482
+ this.forRelations = [];
7483
+ this.attachedRelations = [];
7484
+ this.recyclePool = /* @__PURE__ */ new Map();
7485
+ this.recycleOffsets = /* @__PURE__ */ new Map();
7486
+ }
7487
+ /**
7488
+ * Configure states and lifecycle callbacks for each new factory instance.
7489
+ */
7490
+ configure() {}
7491
+ /**
7492
+ * Set the number of models to create.
7493
+ *
7494
+ * @param amount
7495
+ * @returns
7496
+ */
7497
+ count(amount) {
7498
+ this.ensureConfigured();
7499
+ this.amount = Math.max(1, Math.floor(amount));
7500
+ return this;
7501
+ }
7502
+ /**
7503
+ * Define a state transformation for the factory.
7504
+ * States are applied in the order they were defined.
7505
+ *
7506
+ * @param resolver A function that takes the current attributes and sequence number, and returns the transformed attributes.
7507
+ * @returns The factory instance for chaining.
7508
+ */
7509
+ state(resolver) {
7510
+ this.ensureConfigured();
7511
+ this.states.push(resolver);
7512
+ return this;
7513
+ }
7514
+ /**
7515
+ * Register a callback that runs after a model is made.
7516
+ *
7517
+ * @param callback
7518
+ * @returns
7519
+ */
7520
+ afterMaking(callback) {
7521
+ this.ensureConfigured();
7522
+ this.afterMakingCallbacks.push(callback);
7523
+ return this;
7524
+ }
7525
+ /**
7526
+ * Register a callback that runs after a model is persisted.
7527
+ *
7528
+ * @param callback
7529
+ * @returns
7530
+ */
7531
+ afterCreating(callback) {
7532
+ this.ensureConfigured();
7533
+ this.afterCreatingCallbacks.push(callback);
7534
+ return this;
7535
+ }
7536
+ /**
7537
+ * Create a new model instance without saving it to the database.
7538
+ *
7539
+ * @param overrides
7540
+ * @returns
7541
+ */
7542
+ make(overrides = {}) {
7543
+ this.ensureConfigured();
7544
+ const attributes = this.buildAttributes(overrides);
7545
+ const model = new this.model(attributes);
7546
+ this.runCallbacksSync(this.afterMakingCallbacks, model, "afterMaking");
7547
+ return model;
7548
+ }
7549
+ /**
7550
+ * Create a new model instance from an async factory definition without
7551
+ * saving it to the database.
7552
+ *
7553
+ * @param overrides
7554
+ * @returns
7555
+ */
7556
+ async makeAsync(overrides = {}) {
7557
+ this.ensureConfigured();
7558
+ const attributes = await this.buildAttributesAsync(overrides);
7559
+ const model = new this.model(attributes);
7560
+ await this.runCallbacks(this.afterMakingCallbacks, model);
7561
+ return model;
7562
+ }
7563
+ /**
7564
+ * Create multiple model instances without saving them to the database.
7565
+ *
7566
+ * @param amount
7567
+ * @param overrides
7568
+ * @returns
7569
+ */
7570
+ makeMany(amount = this.amount, overrides = {}) {
7571
+ const total = Math.max(1, Math.floor(amount));
7572
+ return Array.from({ length: total }, () => this.make(overrides));
7573
+ }
7574
+ /**
7575
+ * Create multiple model instances from async factory definitions without
7576
+ * saving them to the database.
7577
+ *
7578
+ * @param amount
7579
+ * @param overrides
7580
+ * @returns
7581
+ */
7582
+ async makeManyAsync(amount = this.amount, overrides = {}) {
7583
+ const total = Math.max(1, Math.floor(amount));
7584
+ const models = [];
7585
+ for (let index = 0; index < total; index++) models.push(await this.makeAsync(overrides));
7586
+ return models;
7587
+ }
7588
+ /**
7589
+ * Create a new model instance and save it to the database.
7590
+ *
7591
+ * @param overrides
7592
+ * @returns
7593
+ */
7594
+ async create(overrides = {}) {
7595
+ return await this.createPersisted(overrides);
7596
+ }
7597
+ /**
7598
+ * Create multiple model instances and save them to the database.
7599
+ *
7600
+ * @param amount
7601
+ * @param overrides
7602
+ * @returns
7603
+ */
7604
+ async createMany(amount = this.amount, overrides = {}) {
7605
+ this.ensureConfigured();
7606
+ const total = Math.max(1, Math.floor(amount));
7607
+ const models = [];
7608
+ for (let index = 0; index < total; index++) models.push(await this.create(overrides));
7609
+ return models;
7610
+ }
7611
+ /**
7612
+ * Create related models through a has-one or has-many relationship.
7613
+ *
7614
+ * @param factory
7615
+ * @param relationship
7616
+ * @returns
7617
+ */
7618
+ has(factory, relationship) {
7619
+ this.ensureConfigured();
7620
+ this.hasRelations.push({
7621
+ factory,
7622
+ relationship
7623
+ });
7624
+ return this;
7625
+ }
7626
+ /**
7627
+ * Associate the created model with a parent model or factory.
7628
+ *
7629
+ * @param related
7630
+ * @param relationship
7631
+ * @returns
7632
+ */
7633
+ for(related, relationship) {
7634
+ this.ensureConfigured();
7635
+ this.forRelations.push({
7636
+ related,
7637
+ relationship
7638
+ });
7639
+ return this;
7640
+ }
7641
+ /**
7642
+ * Create or reuse related models and attach them through a many-to-many relationship.
7643
+ *
7644
+ * @param related
7645
+ * @param pivot
7646
+ * @param relationship
7647
+ * @returns
7648
+ */
7649
+ hasAttached(related, pivot = {}, relationship) {
7650
+ this.ensureConfigured();
7651
+ this.attachedRelations.push({
7652
+ related,
7653
+ pivot,
7654
+ relationship
7655
+ });
7656
+ return this;
7657
+ }
7658
+ /**
7659
+ * Reuse existing models when resolving factory-backed relationships.
7660
+ *
7661
+ * @param models
7662
+ * @returns
7663
+ */
7664
+ recycle(models) {
7665
+ this.ensureConfigured();
7666
+ (Array.isArray(models) ? models : "all" in models ? models.all() : [models]).forEach((model) => {
7667
+ const constructor = model.constructor;
7668
+ const existing = this.recyclePool.get(constructor) ?? [];
7669
+ if (!existing.includes(model)) existing.push(model);
7670
+ this.recyclePool.set(constructor, existing);
7671
+ });
7672
+ return this;
7673
+ }
7674
+ /**
7675
+ * Get the model contgructor
7676
+ *
7677
+ * @returns
7678
+ */
7679
+ getModelConstructor() {
7680
+ return this.model;
7681
+ }
7682
+ /**
7683
+ * Build the attributes for a model instance, applying the factory
7684
+ * definition and any defined states, and merging in any overrides.
7685
+ *
7686
+ * @param overrides
7687
+ * @returns
7688
+ */
7689
+ buildAttributes(overrides) {
7690
+ const sequence = this.sequence;
7691
+ this.sequence += 1;
7692
+ let resolved = this.definition(sequence);
7693
+ if (ModelFactory.isPromiseLike(resolved)) {
7694
+ this.sequence = sequence;
7695
+ throw new Error("This factory has an async definition. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
7696
+ }
7697
+ for (const state of this.states) {
7698
+ resolved = state(resolved, sequence);
7699
+ if (ModelFactory.isPromiseLike(resolved)) {
7700
+ this.sequence = sequence;
7701
+ throw new Error("This factory has an async state. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
7702
+ }
7703
+ }
7704
+ const attributes = {
7705
+ ...resolved,
7706
+ ...overrides
7707
+ };
7708
+ return this.resolveAttributesSync(this.applyBelongsToRelationshipsSync(attributes));
7709
+ }
7710
+ /**
7711
+ * Build attributes for async and sync factory definitions.
7712
+ *
7713
+ * @param overrides
7714
+ * @returns
7715
+ */
7716
+ async buildAttributesAsync(overrides) {
7717
+ const sequence = this.sequence;
7718
+ this.sequence += 1;
7719
+ let resolved = await this.definition(sequence);
7720
+ for (const state of this.states) resolved = await state(resolved, sequence);
7721
+ const attributes = {
7722
+ ...resolved,
7723
+ ...overrides
7724
+ };
7725
+ return await this.resolveAttributesAsync(await this.applyBelongsToRelationships(attributes));
7726
+ }
7727
+ ensureConfigured() {
7728
+ if (this.configured) return;
7729
+ this.configured = true;
7730
+ this.configure();
7731
+ }
7732
+ resolveAttributesSync(attributes) {
7733
+ const resolved = {};
7734
+ for (const [key, value] of Object.entries(attributes)) {
7735
+ if (ModelFactory.isFactory(value)) throw new Error("This factory definition creates a related model. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
7736
+ const next = typeof value === "function" ? value(resolved) : value;
7737
+ if (ModelFactory.isPromiseLike(next)) throw new Error("This factory has an async attribute resolver. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
7738
+ resolved[key] = next;
7739
+ }
7740
+ return resolved;
7741
+ }
7742
+ async resolveAttributesAsync(attributes) {
7743
+ const resolved = {};
7744
+ for (const [key, value] of Object.entries(attributes)) {
7745
+ if (ModelFactory.isFactory(value)) {
7746
+ resolved[key] = await this.resolveFactoryKey(value);
7747
+ continue;
7748
+ }
7749
+ resolved[key] = typeof value === "function" ? await value(resolved) : value;
7750
+ }
7751
+ return resolved;
7752
+ }
7753
+ applyBelongsToRelationshipsSync(attributes) {
7754
+ return this.forRelations.reduce((resolved, relation) => {
7755
+ if (relation.related instanceof Model) return this.mergeBelongsToAttribute(resolved, relation.related, relation.relationship);
7756
+ throw new Error("This factory creates a parent model. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.");
7757
+ }, attributes);
7758
+ }
7759
+ async applyBelongsToRelationships(attributes) {
7760
+ let resolved = attributes;
7761
+ for (const relation of this.forRelations) {
7762
+ const related = relation.related instanceof Model ? relation.related : await this.resolveFactoryModel(relation.related);
7763
+ resolved = this.mergeBelongsToAttribute(resolved, related, relation.relationship);
7764
+ }
7765
+ return resolved;
7766
+ }
7767
+ mergeBelongsToAttribute(attributes, related, relationship) {
7768
+ const relationName = relationship ?? `${str(related.constructor.name).camel().singular()}`;
7769
+ const metadata = this.model.getRelationMetadata?.(relationName);
7770
+ if (metadata?.type !== "belongsTo" || !metadata.foreignKey || !metadata.ownerKey) throw new Error(`Factory relationship [${relationName}] is not a belongsTo relation on [${this.model.name}].`);
7771
+ return {
7772
+ ...attributes,
7773
+ [metadata.foreignKey]: related.getAttribute(metadata.ownerKey)
7774
+ };
7775
+ }
7776
+ async createPersisted(overrides, persist) {
7777
+ const model = await this.makeAsync(overrides);
7778
+ const persisted = persist ? await persist(model) : await this.saveModel(model);
7779
+ await this.createHasRelations(persisted);
7780
+ await this.createAttachedRelations(persisted);
7781
+ await this.runCallbacks(this.afterCreatingCallbacks, persisted);
7782
+ return persisted;
7783
+ }
7784
+ async saveModel(model) {
7785
+ const saveable = model;
7786
+ const constructor = model?.constructor;
7787
+ const primaryKey = constructor.getPrimaryKey?.() ?? "id";
7788
+ if (saveable.getAttribute?.(primaryKey) != null && constructor.query && saveable.getRawAttributes) return await constructor.query().create(saveable.getRawAttributes());
7789
+ if (typeof saveable.save !== "function") throw new Error("Factory model does not support save().");
7790
+ return await saveable.save();
7791
+ }
7792
+ async createHasRelations(model) {
7793
+ for (const definition of this.hasRelations) {
7794
+ const relationship = definition.relationship ?? `${str(definition.factory.getModelConstructor().name).camel().plural()}`;
7795
+ const relation = this.resolveRelation(model, relationship);
7796
+ definition.factory.inheritRecyclePool(this.recyclePool);
7797
+ for (let index = 0; index < definition.factory.amount; index++) await definition.factory.createPersisted({}, async (related) => await relation.save(related));
7798
+ }
7799
+ }
7800
+ async createAttachedRelations(model) {
7801
+ for (const definition of this.attachedRelations) {
7802
+ const factory = definition.related instanceof ModelFactory ? definition.related : null;
7803
+ const relatedModels = factory ? await factory.inheritRecyclePool(this.recyclePool).createMany() : Array.isArray(definition.related) ? definition.related : [definition.related];
7804
+ const relatedName = factory?.getModelConstructor().name ?? relatedModels[0]?.constructor.name;
7805
+ const relationship = definition.relationship ?? `${str(relatedName ?? "").camel().plural()}`;
7806
+ const relation = this.resolveRelation(model, relationship);
7807
+ if (typeof relation.attach !== "function") throw new Error(`Factory relationship [${relationship}] does not support attach().`);
7808
+ await relation.attach(relatedModels, definition.pivot);
7809
+ }
7810
+ }
7811
+ resolveRelation(model, relationship) {
7812
+ const resolver = model[relationship];
7813
+ if (typeof resolver !== "function") throw new Error(`Factory relationship [${relationship}] is not defined on [${this.model.name}].`);
7814
+ return resolver.call(model);
7815
+ }
7816
+ async resolveFactoryKey(factory) {
7817
+ const model = await this.resolveFactoryModel(factory);
7818
+ const primaryKey = model.constructor.getPrimaryKey?.() ?? "id";
7819
+ return model.getAttribute(primaryKey);
7820
+ }
7821
+ async resolveFactoryModel(factory) {
7822
+ factory.inheritRecyclePool(this.recyclePool);
7823
+ return factory.takeRecycledModel() ?? await factory.create();
7824
+ }
7825
+ inheritRecyclePool(pool) {
7826
+ pool.forEach((models, constructor) => {
7827
+ const existing = this.recyclePool.get(constructor) ?? [];
7828
+ const inherited = models.filter((model) => !existing.includes(model));
7829
+ this.recyclePool.set(constructor, [...existing, ...inherited]);
7830
+ });
7831
+ return this;
7832
+ }
7833
+ takeRecycledModel() {
7834
+ const constructor = this.model;
7835
+ const models = this.recyclePool.get(constructor);
7836
+ if (!models || models.length === 0) return null;
7837
+ const offset = this.recycleOffsets.get(constructor) ?? 0;
7838
+ this.recycleOffsets.set(constructor, offset + 1);
7839
+ return models[offset % models.length] ?? null;
7840
+ }
7841
+ runCallbacksSync(callbacks, model, callbackName) {
7842
+ callbacks.forEach((callback) => {
7843
+ const result = callback(model);
7844
+ if (ModelFactory.isPromiseLike(result)) throw new Error(`Factory ${callbackName} callback is async. Use makeAsync(), makeManyAsync(), create(), or createMany() instead.`);
7845
+ });
7846
+ }
7847
+ async runCallbacks(callbacks, model) {
7848
+ for (const callback of callbacks) await callback(model);
7849
+ }
7850
+ static isPromiseLike(value) {
7851
+ return typeof value?.then === "function";
7852
+ }
7853
+ static isFactory(value) {
7854
+ return value instanceof ModelFactory;
7855
+ }
7856
+ };
7857
+ /**
7858
+ * A helper class for defining factories using an inline definition
7859
+ * function, without needing to create a separate factory class.
7860
+ *
7861
+ * @template TModel
7862
+ * @template TAttributes
7863
+ * @author Legacy (3m1n3nc3)
7864
+ * @since 0.1.0
7865
+ */
7866
+ var InlineFactory = class extends ModelFactory {
7867
+ constructor(model, resolver) {
7868
+ super();
7869
+ this.resolver = resolver;
7870
+ this.model = model;
7871
+ }
7872
+ definition(sequence) {
7873
+ return this.resolver(sequence);
7874
+ }
7875
+ };
7876
+ /**
7877
+ * Define a factory for a given model using an inline definition function.
7878
+ *
7879
+ * @template TModel The type of model the factory creates.
7880
+ * @template TAttributes The type of attributes used to create the model.
7881
+ * @param model The model constructor.
7882
+ * @param definition The factory definition function.
7883
+ * @returns A new instance of the model factory.
7884
+ */
7885
+ const defineFactory = (model, definition) => {
7886
+ return new InlineFactory(model, definition);
7887
+ };
7888
+
7889
+ //#endregion
7890
+ //#region src/DB.ts
7891
+ const defaultSoftDeleteConfig = {
7892
+ enabled: false,
7893
+ column: "deletedAt"
7894
+ };
7895
+ var DB = class DB {
7896
+ constructor(adapter) {
7897
+ this.scopedAdapter = adapter;
7898
+ }
7899
+ static setAdapter(adapter) {
7900
+ this.adapter = adapter;
7901
+ }
7902
+ static getAdapter() {
7903
+ const runtimeAdapter = getRuntimeAdapter();
7904
+ if (runtimeAdapter) return runtimeAdapter;
7905
+ if (this.adapter) return this.adapter;
7906
+ return getRuntimeCompatibilityAdapter();
7907
+ }
7908
+ getAdapter() {
7909
+ return this.scopedAdapter ?? DB.getAdapter();
7910
+ }
7911
+ static table(table, options = {}) {
7912
+ return new DB().table(table, options);
7913
+ }
7914
+ table(table, options = {}) {
7915
+ return DB.createTableModel(table, options, this.getAdapter()).query();
7916
+ }
7917
+ static async raw(sql, bindings = []) {
7918
+ return await new DB().raw(sql, bindings);
7919
+ }
7920
+ async raw(sql, bindings = []) {
7921
+ const adapter = this.getAdapter();
7922
+ if (!adapter) throw new ArkormException("Raw queries require a configured database adapter.", {
7923
+ code: "ADAPTER_NOT_CONFIGURED",
7924
+ operation: "db.raw"
7925
+ });
7926
+ if (!adapter.rawQuery) throw new UnsupportedAdapterFeatureException("Raw queries are not supported by the current adapter.", {
7927
+ operation: "db.raw",
7928
+ meta: { feature: "rawQuery" }
7929
+ });
7930
+ const rows = await adapter.rawQuery({
7931
+ sql,
7932
+ bindings
7933
+ });
7934
+ return ArkormCollection.make(rows);
7935
+ }
7936
+ static async transaction(callback, context) {
7937
+ return await new DB().transaction(callback, context);
7938
+ }
7939
+ async transaction(callback, context) {
7940
+ const adapter = this.getAdapter();
7941
+ if (!adapter) throw new ArkormException("DB transactions require a configured database adapter.", {
7942
+ code: "ADAPTER_NOT_CONFIGURED",
7943
+ operation: "db.transaction"
7944
+ });
7945
+ return await adapter.transaction(async (transactionAdapter) => {
7946
+ return await callback(new DB(transactionAdapter));
7947
+ }, context);
7948
+ }
7949
+ static createTableModel(table, options, adapter) {
7950
+ const primaryKey = options.primaryKey ?? "id";
7951
+ const resolvedAdapter = options.adapter ?? adapter ?? DB.getAdapter();
7952
+ const persistedMetadata = DB.resolvePersistedTableMetadata(table, options, resolvedAdapter);
7953
+ const columns = {
7954
+ ...persistedMetadata.columns,
7955
+ ...options.columns ?? {}
7956
+ };
7957
+ const softDelete = options.softDelete ?? defaultSoftDeleteConfig;
7958
+ const primaryKeyGeneration = options.primaryKeyGeneration ? { ...options.primaryKeyGeneration } : persistedMetadata.primaryKeyGeneration?.column === primaryKey ? {
7959
+ strategy: persistedMetadata.primaryKeyGeneration.strategy,
7960
+ prismaDefault: persistedMetadata.primaryKeyGeneration.prismaDefault,
7961
+ databaseDefault: persistedMetadata.primaryKeyGeneration.databaseDefault,
7962
+ runtimeFactory: persistedMetadata.primaryKeyGeneration.runtimeFactory
7963
+ } : void 0;
7964
+ const timestampColumns = options.timestampColumns?.map((column) => ({ ...column })) ?? persistedMetadata.timestampColumns?.map((column) => ({ ...column }));
7965
+ const buildMetadata = () => {
7966
+ return {
7967
+ table,
7968
+ primaryKey,
7969
+ columns: { ...columns },
7970
+ softDelete: { ...softDelete },
7971
+ primaryKeyGeneration,
7972
+ timestampColumns
7973
+ };
7974
+ };
7975
+ const modelStatic = {
7976
+ query: () => new QueryBuilder(modelStatic, modelStatic.getAdapter()),
7977
+ hydrate: (attributes) => ({ ...attributes }),
7978
+ hydrateMany: (attributes) => attributes.map((attribute) => ({ ...attribute })),
7979
+ hydrateRetrieved: async (attributes) => ({ ...attributes }),
7980
+ hydrateManyRetrieved: async (attributes) => attributes.map((attribute) => ({ ...attribute })),
7981
+ getAdapter: () => resolvedAdapter,
7982
+ getColumnMap: () => ({ ...columns }),
7983
+ getColumnName: (attribute) => columns[attribute] ?? attribute,
7984
+ getModelMetadata: () => buildMetadata(),
7985
+ getPrimaryKey: () => primaryKey,
7986
+ getRelationMetadata: () => null,
7987
+ setAdapter: () => {},
7988
+ getSoftDeleteConfig: () => ({ ...softDelete }),
7989
+ getTable: () => table
7990
+ };
7991
+ return modelStatic;
7992
+ }
7993
+ static resolvePersistedTableMetadata(table, options, adapter) {
7994
+ if (options.persistedMetadata === false) return {
7995
+ columns: {},
7996
+ enums: {}
7997
+ };
7998
+ const persistedMetadataOptions = typeof options.persistedMetadata === "object" ? options.persistedMetadata : {};
7999
+ return getPersistedTableMetadata(table, {
8000
+ cwd: persistedMetadataOptions.cwd,
8001
+ configuredPath: persistedMetadataOptions.configuredPath,
8002
+ features: resolvePersistedMetadataFeatures(getUserConfig("features")),
8003
+ strict: persistedMetadataOptions.strict ?? (Boolean(adapter) && !(adapter instanceof PrismaDatabaseAdapter))
8004
+ });
8005
+ }
8006
+ };
8007
+
7727
8008
  //#endregion
7728
8009
  //#region src/PivotModel.ts
7729
8010
  /**
@@ -7742,4 +8023,4 @@ var PivotModel = class extends Model {
7742
8023
  };
7743
8024
 
7744
8025
  //#endregion
7745
- export { Arkorm, ArkormCollection, ArkormException, Arkormx, Attribute, CliApp, DB, EnumBuilder, ForeignKeyBuilder, InitCommand, InlineFactory, KyselyDatabaseAdapter, LengthAwarePaginator, MIGRATION_BRAND, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, MigrateFreshCommand, MigrateRollbackCommand, Migration, MigrationHistoryCommand, MissingDelegateException, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_ENUM_MEMBER_REGEX, PRISMA_ENUM_REGEX, PRISMA_MODEL_REGEX, Paginator, PivotModel, PrimaryKeyGenerationPlanner, PrismaDatabaseAdapter, QueryBuilder, QueryConstraintException, QueryExecutionException, RelationResolutionException, RuntimeModuleLoader, SEEDER_BRAND, SchemaBuilder, ScopeNotDefinedException, SeedCommand, Seeder, TableBuilder, URLDriver, UniqueConstraintResolutionException, UnsupportedAdapterFeatureException, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationRollbackToDatabase, applyMigrationRollbackToPrismaSchema, applyMigrationToDatabase, applyMigrationToPrismaSchema, applyOperationsToPersistedColumnMappingsState, applyOperationsToPrismaSchema, bindAdapterToModels, buildEnumBlock, buildFieldLine, buildIndexLine, buildInverseRelationLine, buildMigrationIdentity, buildMigrationRunId, buildMigrationSource, buildModelBlock, buildRelationLine, computeMigrationChecksum, configureArkormRuntime, createEmptyAppliedMigrationsState, createEmptyPersistedColumnMappingsState, createKyselyAdapter, createMigrationTimestamp, createPrismaAdapter, createPrismaCompatibilityAdapter, createPrismaDatabaseAdapter, createPrismaDelegateMap, defineConfig, defineFactory, deleteAppliedMigrationsStateFromStore, deletePersistedColumnMappingsState, deriveCollectionFieldName, deriveInverseRelationAlias, deriveRelationAlias, deriveRelationFieldName, deriveSingularFieldName, emitRuntimeDebugEvent, ensureArkormConfigLoading, escapeRegex, findAppliedMigration, findEnumBlock, findModelBlock, formatDefaultValue, formatEnumDefaultValue, formatRelationAction, generateMigrationFile, getActiveTransactionAdapter, getActiveTransactionClient, getDefaultStubsPath, getLastMigrationRun, getLatestAppliedMigrations, getMigrationPlan, getPersistedColumnMap, getPersistedEnumMap, getPersistedEnumTsType, getPersistedPrimaryKeyGeneration, getPersistedTableMetadata, getPersistedTimestampColumns, getRegisteredFactories, getRegisteredMigrations, getRegisteredModels, getRegisteredPaths, getRegisteredSeeders, getRuntimeAdapter, getRuntimeClient, getRuntimeCompatibilityAdapter, getRuntimeDebugHandler, getRuntimePaginationCurrentPageResolver, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, isMigrationApplied, isQuerySchemaLike, isTransactionCapableClient, loadArkormConfig, loadFactoriesFrom, loadMigrationsFrom, loadModelsFrom, loadSeedersFrom, markMigrationApplied, markMigrationRun, pad, readAppliedMigrationsState, readAppliedMigrationsStateFromStore, readPersistedColumnMappingsState, rebuildPersistedColumnMappingsState, registerFactories, registerMigrations, registerModels, registerPaths, registerSeeders, removeAppliedMigration, resetArkormRuntimeForTests, resetPersistedColumnMappingsCache, resetRuntimeRegistryForTests, resolveCast, resolveColumnMappingsFilePath, resolveEnumName, resolveMigrationClassName, resolveMigrationStateFilePath, resolvePersistedMetadataFeatures, resolvePrismaType, resolveRuntimeCompatibilityQuerySchema, resolveRuntimeCompatibilityQuerySchemaOrThrow, runArkormTransaction, runMigrationWithPrisma, runPrismaCommand, stripPrismaSchemaModelsAndEnums, supportsDatabaseCreation, supportsDatabaseMigrationExecution, supportsDatabaseMigrationState, supportsDatabaseReset, syncPersistedColumnMappingsFromState, toMigrationFileSlug, toModelName, validatePersistedMetadataFeaturesForMigrations, writeAppliedMigrationsState, writeAppliedMigrationsStateToStore, writePersistedColumnMappingsState };
8026
+ export { Arkorm, ArkormCollection, ArkormException, Arkormx, Attribute, CliApp, DB, EnumBuilder, ForeignKeyBuilder, InitCommand, InlineFactory, KyselyDatabaseAdapter, LengthAwarePaginator, MIGRATION_BRAND, MakeFactoryCommand, MakeMigrationCommand, MakeModelCommand, MakeSeederCommand, MigrateCommand, MigrateFreshCommand, MigrateRollbackCommand, Migration, MigrationHistoryCommand, MissingDelegateException, Model, ModelFactory, ModelNotFoundException, ModelsSyncCommand, PRISMA_ENUM_MEMBER_REGEX, PRISMA_ENUM_REGEX, PRISMA_MODEL_REGEX, Paginator, PivotModel, PrimaryKeyGenerationPlanner, PrismaDatabaseAdapter, QueryBuilder, QueryConstraintException, QueryExecutionException, RelationResolutionException, RuntimeModuleLoader, SEEDER_BRAND, SchemaBuilder, ScopeNotDefinedException, SeedCommand, Seeder, TableBuilder, URLDriver, UniqueConstraintResolutionException, UnsupportedAdapterFeatureException, applyAlterTableOperation, applyCreateTableOperation, applyDropTableOperation, applyMigrationRollbackToDatabase, applyMigrationRollbackToPrismaSchema, applyMigrationToDatabase, applyMigrationToPrismaSchema, applyOperationsToPersistedColumnMappingsState, applyOperationsToPrismaSchema, bindAdapterToModels, buildEnumBlock, buildFieldLine, buildIndexLine, buildInverseRelationLine, buildMigrationIdentity, buildMigrationRunId, buildMigrationSource, buildModelBlock, buildPrimaryKeyLine, buildRelationLine, buildUniqueConstraintLine, computeMigrationChecksum, configureArkormRuntime, createEmptyAppliedMigrationsState, createEmptyPersistedColumnMappingsState, createKyselyAdapter, createMigrationTimestamp, createPrismaAdapter, createPrismaCompatibilityAdapter, createPrismaDatabaseAdapter, createPrismaDelegateMap, defineConfig, defineFactory, deleteAppliedMigrationsStateFromStore, deletePersistedColumnMappingsState, deriveCollectionFieldName, deriveInverseRelationAlias, deriveRelationAlias, deriveRelationFieldName, deriveSingularFieldName, emitRuntimeDebugEvent, ensureArkormConfigLoading, escapeRegex, findAppliedMigration, findEnumBlock, findModelBlock, formatDefaultValue, formatEnumDefaultValue, formatRelationAction, generateMigrationFile, getActiveTransactionAdapter, getActiveTransactionClient, getDefaultStubsPath, getLastMigrationRun, getLatestAppliedMigrations, getMigrationPlan, getPersistedColumnMap, getPersistedEnumMap, getPersistedEnumTsType, getPersistedPrimaryKeyGeneration, getPersistedTableMetadata, getPersistedTimestampColumns, getRegisteredFactories, getRegisteredMigrations, getRegisteredModels, getRegisteredPaths, getRegisteredSeeders, getRuntimeAdapter, getRuntimeClient, getRuntimeCompatibilityAdapter, getRuntimeDebugHandler, getRuntimePaginationCurrentPageResolver, getRuntimePaginationURLDriverFactory, getRuntimePrismaClient, getUserConfig, inferDelegateName, isDelegateLike, isMigrationApplied, isQuerySchemaLike, isTransactionCapableClient, loadArkormConfig, loadFactoriesFrom, loadMigrationsFrom, loadModelsFrom, loadSeedersFrom, markMigrationApplied, markMigrationRun, pad, readAppliedMigrationsState, readAppliedMigrationsStateFromStore, readPersistedColumnMappingsState, rebuildPersistedColumnMappingsState, registerFactories, registerMigrations, registerModels, registerPaths, registerSeeders, removeAppliedMigration, resetArkormRuntimeForTests, resetPersistedColumnMappingsCache, resetRuntimeRegistryForTests, resolveCast, resolveColumnMappingsFilePath, resolveEnumName, resolveMigrationClassName, resolveMigrationStateFilePath, resolvePersistedMetadataFeatures, resolvePrismaType, resolveRuntimeCompatibilityQuerySchema, resolveRuntimeCompatibilityQuerySchemaOrThrow, runArkormTransaction, runMigrationWithPrisma, runPrismaCommand, stripPrismaSchemaModelsAndEnums, supportsDatabaseCreation, supportsDatabaseMigrationExecution, supportsDatabaseMigrationState, supportsDatabaseReset, syncPersistedColumnMappingsFromState, toMigrationFileSlug, toModelName, validatePersistedMetadataFeaturesForMigrations, writeAppliedMigrationsState, writeAppliedMigrationsStateToStore, writePersistedColumnMappingsState };