arkormx 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # Arkormˣ
2
+
3
+ [![NPM Downloads](https://img.shields.io/npm/dt/arkormx.svg)](https://www.npmjs.com/package/arkormx)
4
+ [![npm version](https://img.shields.io/npm/v/arkormx.svg)](https://www.npmjs.com/package/arkormx)
5
+ [![License](https://img.shields.io/npm/l/arkormx.svg)](https://github.com/arcstack-hq/arkormx/blob/main/LICENSE)
6
+ [![CI](https://github.com/arcstack-hq/arkormx/actions/workflows/ci.yml/badge.svg)](https://github.com/arcstack-hq/arkormx/actions/workflows/ci.yml)
7
+ [![Deploy Docs](https://github.com/arcstack-hq/arkormx/actions/workflows/deploy-docs.yml/badge.svg)](https://github.com/arcstack-hq/arkormx/actions/workflows/deploy-docs.yml)
8
+
9
+ Arkormˣ is a framework-agnostic ORM designed to run anywhere Node.js runs. It brings a familiar model layer and fluent query builder on top of Prisma delegates, enabling clean, modern, and type-safe development.
10
+
11
+ ## Features
12
+
13
+ - Arkormˣ is built on top of Prisma, providing a familiar and powerful API for database interactions.
14
+ - Delegate-backed query execution with practical ORM ergonomics.
15
+ - End-to-end guides for setup, querying, relationships, migrations, and CLI usage.
16
+ - Full TypeScript support, providing strong typing and improved developer experience.
17
+ - Follows best practices for security, ensuring your data is protected.
18
+ - Open source and welcomes contributions from developers around the world.
19
+ - Intuitive API that feels familiar to users transitioning from Eloquent or other ORMs, making it easy to learn and adopt.
20
+
21
+ ## Getting Started
22
+
23
+ ### Installation
24
+
25
+ ```sh
26
+ pnpm add arkormx @prisma/client
27
+ pnpm add -D prisma
28
+ ```
29
+
30
+ ### Configuration
31
+
32
+ Create `arkormx.config.js` in your project root:
33
+
34
+ ```ts
35
+ import { defineConfig } from 'arkormx';
36
+ import { PrismaClient } from '@prisma/client';
37
+
38
+ export default defineConfig({
39
+ prisma: new PrismaClient(...),
40
+ });
41
+ ```
42
+
43
+ Or run the Arkormˣ CLI command `npx arkormx init` to initialize your project along with configuration.
44
+
45
+ ### Define a model
46
+
47
+ ```ts
48
+ import { Model } from 'arkormx';
49
+
50
+ export class User extends Model<'users'> {
51
+ protected static override delegate = 'users'; // not required if your model name matches the delegate name or the pluralized form of it
52
+ }
53
+ ```
54
+
55
+ ### Generate Prisma client
56
+
57
+ ```bash
58
+ pnpm prisma generate
59
+ ```
60
+
61
+ ### Run queries
62
+
63
+ ```ts
64
+ const users = await User.query()
65
+ .whereKey('isActive', true)
66
+ .latest()
67
+ .limit(10)
68
+ .get();
69
+ ```
70
+
71
+ ## Next steps
72
+
73
+ - [Setup](https://arkormx.toneflix.net/guide/setup)
74
+ - [Configuration](https://arkormx.dev/guide/configuration)
75
+ - [Typing](https://arkormx.dev/guide/typing)
76
+ - [Models](https://arkormx.dev/guide/models)
77
+ - [Query Builder](https://arkormx.dev/guide/query-builder)
78
+ - [Relationships](https://arkormx.dev/guide/relationships)
package/bin/index.mjs ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdirSync as i,rmSync as a,writeFileSync as o}from"fs";import s,{dirname as c,extname as l,join as u,relative as d}from"path";import{createRequire as f}from"module";import{existsSync as p,mkdirSync as m,readFileSync as h,readdirSync as g,writeFileSync as _}from"node:fs";import{join as v,resolve as y}from"node:path";import{str as b}from"@h3ravel/support";import{spawnSync as x}from"node:child_process";import{Command as S,Kernel as ee}from"@h3ravel/musket";import{fileURLToPath as C,pathToFileURL as w}from"url";import{pathToFileURL as T}from"node:url";import"@h3ravel/collect.js";import{Logger as E}from"@h3ravel/shared";var D=class extends Error{constructor(e){super(e),this.name=`ArkormException`}};const O={paths:{stubs:C(new URL(`../../stubs`,import.meta.url)),seeders:s.join(process.cwd(),`database`,`seeders`),models:s.join(process.cwd(),`src`,`models`),migrations:s.join(process.cwd(),`database`,`migrations`),factories:s.join(process.cwd(),`database`,`factories`),buildOutput:s.join(process.cwd(),`dist`)},outputExt:`ts`};let k=!1,A;const j=e=>e?O[e]:O,te=(e,t={})=>{Object.assign(O,{...t,prisma:e,paths:{...O.paths??{},...t.paths??{}}}),t.pagination?.urlDriver},M=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(Object.assign(O,t),te(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),k=!0)},ne=e=>import(`${w(e).href}?arkorm_runtime=${Date.now()}`),re=()=>{let e=f(import.meta.url),n=[s.join(process.cwd(),`arkormx.config.cjs`)];for(let r of n)if(t(r))try{return M(e(r)),!0}catch{continue}return!1};(async()=>{if(!k){if(A)return await A;re()||(A=(async()=>{let e=[s.join(process.cwd(),`arkormx.config.js`),s.join(process.cwd(),`arkormx.config.ts`)];for(let n of e)if(t(n))try{M(await ne(n));return}catch{continue}k=!0})(),await A)}})();var ie=class extends S{signature=`init
3
+ {--force : Force overwrite if config file already exists (existing file will be backed up) }
4
+ `;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let n=v(process.cwd(),`arkormx.config.js`),{stubs:i}=j(`paths`)??{},a=v(i??``,`arkormx.config.stub`);t(n)&&!this.option(`force`)&&(this.error(`Error: Arkormˣ has already been initialized. Use --force to reinitialize.`),process.exit(1)),this.app.ensureDirectory(n),t(n)&&this.option(`force`)&&e(n,n.replace(/\.js$/,`.backup.${Date.now()}.js`)),o(n,r(a,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},ae=class extends S{signature=`make:factory
5
+ {name : Name of the factory to create}
6
+ {--f|force : Overwrite existing file}
7
+ `;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},oe=class extends S{signature=`make:migration
8
+ {name : Name of the migration to create}
9
+ `;description=`Create a new migration class file`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeMigration(e);this.success(`Created migration: ${this.app.formatPathForLog(t.path)}`)}},N=class extends S{signature=`make:model
10
+ {name : Name of the model to create}
11
+ {--f|force : Overwrite existing files}
12
+ {--factory : Create and link a factory}
13
+ {--seeder : Create a seeder}
14
+ {--migration : Create a migration}
15
+ {--all : Create and link factory, seeder, and migration}
16
+ `;description=`Create a new model and optional linked resources`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeModel(e,this.options());this.success(`Created files:`),[[`Model`,t.model.path],[`Prisma schema ${t.prisma.updated?`(updated)`:`(already up to date)`}`,t.prisma.path],t.factory?[`Factory`,t.factory.path]:``,t.seeder?[`Seeder`,t.seeder.path]:``,t.migration?[`Migration`,t.migration.path]:``].filter(Boolean).map(([e,t])=>this.success(this.app.splitLogger(e,t)))}},P=class extends S{signature=`make:seeder
17
+ {name : Name of the seeder to create}
18
+ {--f|force : Overwrite existing file}
19
+ `;description=`Create a new seeder class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeSeeder(e,this.options());this.success(`Created seeder: ${this.app.formatPathForLog(t.path)}`)}},F=class{},I=class extends S{signature=`migrate
20
+ {name? : Migration class or file name}
21
+ {--all : Run all migrations from the configured migrations directory}
22
+ {--deploy : Use prisma migrate deploy instead of migrate dev}
23
+ {--skip-generate : Skip prisma generate}
24
+ {--skip-migrate : Skip prisma migrate command}
25
+ {--schema= : Explicit prisma schema path}
26
+ {--migration-name= : Name for prisma migrate dev}
27
+ `;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??v(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?y(String(this.option(`schema`))):v(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await ge(e,{schemaPath:n,write:!0});this.option(`skip-generate`)||Z([`generate`],process.cwd()),this.option(`skip-migrate`)||(this.option(`deploy`)?Z([`migrate`,`deploy`],process.cwd()):Z([`migrate`,`dev`,`--name`,this.option(`migration-name`)?String(this.option(`migration-name`)):`arkorm_cli_${Date.now()}`],process.cwd())),this.success(`Applied ${r.length} migration(s).`),r.forEach(([e,t])=>this.success(this.app.splitLogger(`Migrated`,t)))}async loadAllMigrations(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).sort((e,t)=>e.localeCompare(t)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>(await this.loadMigrationClassesFromFile(e)).map(t=>[t,e])))).flat()}async loadNamedMigration(e,t){if(!t)return[[void 0,``]];let n=t.replace(/Migration$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Migration.ts`,`${n}Migration.js`,`${n}Migration.mjs`,`${n}Migration.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[[void 0,t]];let i=this.app.resolveRuntimeScriptPath(r);return(await this.loadMigrationClassesFromFile(i)).map(e=>[e,i])}async loadMigrationClassesFromFile(e){let t=await import(`${T(y(e)).href}?arkorm_migrate=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof F:!1)}},L=class extends S{signature=`models:sync
28
+ {--schema= : Path to prisma schema file}
29
+ {--models= : Path to models directory}
30
+ `;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?y(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?y(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},R=class e{async call(...t){await e.runSeeders(...t)}static toSeederInstance(t){return t instanceof e?t:new t}static async runSeeders(...e){let t=e.reduce((e,t)=>Array.isArray(t)?[...e,...t]:(e.push(t),e),[]);for(let e of t)await this.toSeederInstance(e).run()}},z=class extends S{signature=`seed
31
+ {name? : Seeder class or file name}
32
+ {--all : Run all seeders in the configured seeders directory}
33
+ `;description=`Run one or more seeders`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.seeders??v(process.cwd(),`database`,`seeders`),t=this.app.resolveRuntimeDirectoryPath(e);if(!p(t))return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`all`)?await this.loadAllSeeders(t):await this.loadNamedSeeder(t,this.argument(`name`)??`DatabaseSeeder`);if(n.length===0)return void this.error(`ERROR: No seeder classes found to run.`);for(let e of n)await new e().run();this.success(`Database seeding completed`),n.forEach(e=>this.success(this.app.splitLogger(`Seeded`,e.name)))}async loadAllSeeders(e){let t=g(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).map(t=>this.app.resolveRuntimeScriptPath(v(e,t)));return(await Promise.all(t.map(async e=>await this.loadSeederClassesFromFile(e)))).flat()}async loadNamedSeeder(e,t){let n=t.replace(/Seeder$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Seeder.ts`,`${n}Seeder.js`,`${n}Seeder.mjs`,`${n}Seeder.cjs`].map(t=>v(e,t)).find(e=>p(e));if(!r)return[];let i=this.app.resolveRuntimeScriptPath(r);return await this.loadSeederClassesFromFile(i)}async loadSeederClassesFromFile(e){let t=await import(`${T(y(e)).href}?arkorm_seed=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof R:!1)}},B=String.raw`
34
+ __/^^^^^^^^^^^^^^^^\__
35
+ ▄▄▄/ \▄▄
36
+ ▄██▀▀██▄ ▄▄
37
+ ███ ███ ████▄ ██ ▄█▀ ▄███▄ ████▄ ███▄███▄
38
+ ███▀▀███ ██ ▀▀ ████ ██ ██ ██ ▀▀ ██ ██ ██
39
+ ███ ███ ██ ██ ▀█▄ ▀███▀ ██ ██ ██ ██
40
+ `,V=class{columns=[];dropColumnNames=[];id(e=`id`){return this.column(e,`id`,{primary:!0})}string(e,t={}){return this.column(e,`string`,t)}text(e,t={}){return this.column(e,`text`,t)}integer(e,t={}){return this.column(e,`integer`,t)}bigInteger(e,t={}){return this.column(e,`bigInteger`,t)}float(e,t={}){return this.column(e,`float`,t)}boolean(e,t={}){return this.column(e,`boolean`,t)}json(e,t={}){return this.column(e,`json`,t)}date(e,t={}){return this.column(e,`date`,t)}morphs(e,t=!1){return this.string(`${e}Type`,{nullable:t}),this.integer(`${e}Id`,{nullable:t}),this}nullableMorphs(e){return this.morphs(e,!0)}timestamp(e,t={}){return this.column(e,`timestamp`,t)}timestamps(){return this.timestamp(`createdAt`,{nullable:!1}),this.timestamp(`updatedAt`,{nullable:!1}),this}softDeletes(e=`deletedAt`){return this.timestamp(e,{nullable:!0}),this}dropColumn(e){return this.dropColumnNames.push(e),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}column(e,t,n){return this.columns.push({name:e,type:t,nullable:n.nullable,unique:n.unique,primary:n.primary,default:n.default}),this}},H=class{operations=[];createTable(e,t){let n=new V;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns()}),this}alterTable(e,t){let n=new V;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns()}),this}dropTable(e){return this.operations.push({type:`dropTable`,table:e}),this}getOperations(){return this.operations.map(e=>e.type===`createTable`?{...e,columns:e.columns.map(e=>({...e}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns]}:{...e})}};const U=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,W=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim(),n=(t.endsWith(`s`)&&t.length>1?t.slice(0,-1):t).split(/\s+/g).filter(Boolean);return n.length===0?`GeneratedModel`:n.map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)},G=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),K=e=>e.type===`id`?`Int`:e.type===`string`||e.type===`text`?`String`:e.type===`integer`?`Int`:e.type===`bigInteger`?`BigInt`:e.type===`float`?`Float`:e.type===`boolean`?`Boolean`:e.type===`json`?`Json`:`DateTime`,q=e=>{if(e!=null){if(typeof e==`string`)return`@default("${e.replace(/"/g,`\\"`)}")`;if(typeof e==`number`||typeof e==`bigint`)return`@default(${e})`;if(typeof e==`boolean`)return`@default(${e?`true`:`false`})`}},J=e=>{if(e.type===`id`)return` ${e.name} Int @id @default(autoincrement())`;let t=K(e),n=e.nullable?`?`:``,r=e.unique?` @unique`:``,i=e.primary?` @id`:``,a=q(e.default),o=a?` ${a}`:``;return` ${e.name} ${t}${n}${i}${r}${o}`},se=e=>{let t=W(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(J),i=n?`\n\n @@map("${b(e.table).snake()}")`:``;return`model ${t} {\n${r.join(`
41
+ `)}${i}\n}`},Y=(e,t)=>{let n=[...e.matchAll(U)],r=RegExp(`@@map\\("${G(t)}"\\)`);for(let e of n){let n=e[0],i=e[1],a=e.index??0,o=a+n.length;if(r.test(n)||i.toLowerCase()===t.toLowerCase()||i.toLowerCase()===W(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},X=(e,t)=>{if(Y(e,t.table))throw new D(`Prisma model for table [${t.table}] already exists.`);let n=se(t);return`${e.trimEnd()}\n\n${n}\n`},ce=(e,t)=>{let n=Y(e,t.table);if(!n)throw new D(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
42
+ `);t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${G(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}});let a=Math.max(1,i.length-1);return t.addColumns.forEach(e=>{let t=J(e),n=RegExp(`^\\s*${G(e.name)}\\s+`);i.some(e=>n.test(e))||i.splice(a,0,t)}),r=i.join(`
43
+ `),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},le=(e,t)=>{let n=Y(e,t.table);if(!n)return e;let r=e.slice(0,n.start).trimEnd(),i=e.slice(n.end).trimStart();return`${r}${r&&i?`
44
+
45
+ `:``}${i}`},ue=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?X(e,t):t.type===`alterTable`?ce(e,t):le(e,t),e),Z=(e,t)=>{let n=x(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
46
+ `).trim();throw new D(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},de=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim();return t?`${t.split(/\s+/g).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)}Migration`:`GeneratedMigration`},Q=e=>String(e).padStart(2,`0`),fe=(e=new Date)=>`${e.getFullYear()}${Q(e.getMonth()+1)}${Q(e.getDate())}${Q(e.getHours())}${Q(e.getMinutes())}${Q(e.getSeconds())}`,pe=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`migration`,$=(e,t=`ts`)=>t===`js`?[`import { Migration } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async up (schema) {`,` }`,``,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async down (schema) {`,` }`,`}`,``].join(`
47
+ `):[`import { Migration, SchemaBuilder } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` public async up (schema: SchemaBuilder): Promise<void> {`,` }`,``,` public async down (schema: SchemaBuilder): Promise<void> {`,` }`,`}`,``].join(`
48
+ `),me=(e,t={})=>{let n=fe(new Date),r=pe(e),i=de(e),a=t.extension??`ts`,o=t.directory??v(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=v(o,s),l=$(i,a);if(t.write??!0){if(p(o)||m(o,{recursive:!0}),p(c))throw new D(`Migration file already exists: ${c}`);_(c,l)}return{fileName:s,filePath:c,className:i,content:l}},he=async(e,t=`up`)=>{let n=e instanceof F?e:new e,r=new H;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},ge=async(e,t={})=>{let n=t.schemaPath??v(process.cwd(),`prisma`,`schema.prisma`);if(!p(n))throw new D(`Prisma schema file not found: ${n}`);let r=h(n,`utf-8`),i=await he(e,`up`),a=ue(r,i);return(t.write??!0)&&_(n,a),{schema:a,schemaPath:n,operations:i}},_e=new class{command;config={};constructor(){this.config=j()}getConfig=j;ensureDirectory(e){let r=c(e);t(r)||n(r,{recursive:!0})}formatPathForLog(e){let t=d(process.cwd(),e);return t?t.startsWith(`..`)?e:t:`.`}splitLogger(e,t){return t=t.includes(process.cwd())?this.formatPathForLog(t):t,E.twoColumnDetail(e+` `,` `+t,!1).join(``)}hasTypeScriptInstalled(){try{return f(import.meta.url).resolve(`typescript`,{paths:[process.cwd()]}),!0}catch{return!1}}resolveOutputExt(){let e=this.getConfig(`outputExt`)===`js`?`js`:`ts`;return e===`ts`&&!this.hasTypeScriptInstalled()?`js`:e}stripKnownSourceExtension(e){return e.replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}resolveRuntimeDirectoryPath(e){if(t(e))return e;let{buildOutput:n}=this.getConfig(`paths`)||{};if(typeof n!=`string`||n.trim().length===0)return e;let r=d(process.cwd(),e);if(!r||r.startsWith(`..`))return e;let i=u(n,r);return t(i)?i:e}resolveRuntimeScriptPath(e){let n=l(e).toLowerCase(),r=n===`.ts`||n===`.mts`||n===`.cts`,i=[];if(r){let t=e.slice(0,-n.length);i.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}let{buildOutput:a}=this.getConfig(`paths`)??{};if(typeof a==`string`&&a.trim().length>0){let t=d(process.cwd(),e);if(t&&!t.startsWith(`..`)){let e=u(a,t),n=l(e).toLowerCase();if(n===`.ts`||n===`.mts`||n===`.cts`){let t=e.slice(0,-n.length);i.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}else i.push(e)}}return i.find(e=>t(e))||e}generateFile(e,n,i,s){t(n)&&!s?.force?(this.command.error(`Error: ${this.formatPathForLog(n)} already exists.`),process.exit(1)):t(n)&&s?.force&&a(n);let c=r(e,`utf-8`);for(let[e,t]of Object.entries(i))c=c.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(n),o(n,c),n}resolveConfigPath(e,t){let{[e]:n}=this.getConfig(`paths`)??{};return typeof n==`string`&&n.trim().length>0?n:t}resolveStubPath(e){return u(this.resolveConfigPath(`stubs`,u(process.cwd(),`stubs`)),e)}makeFactory(e,t={}){let n=b(e.replace(/Factory$/,``)).pascal(),r=`${n}Factory`,i=t.modelName?b(t.modelName).pascal():n,a=this.resolveOutputExt(),o=u(this.resolveConfigPath(`factories`,u(process.cwd(),`database`,`factories`)),`${r}.${a}`),s=u(this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`)),`${i}.${a}`),l=t.modelImportPath??`./${this.stripKnownSourceExtension(d(c(o),s).replace(/\\/g,`/`))}${a===`js`?`.js`:``}`,f=this.resolveStubPath(a===`js`?`factory.js.stub`:`factory.stub`);return{name:r,path:this.generateFile(f,o,{FactoryName:r,ModelName:i.toString(),ModelImportPath:l.startsWith(`.`)?l:`./${l}`},t)}}makeSeeder(e,t={}){let n=`${b(e.replace(/Seeder$/,``)).pascal()}Seeder`,r=this.resolveOutputExt(),i=u(this.resolveConfigPath(`seeders`,u(process.cwd(),`database`,`seeders`)),`${n}.${r}`),a=this.resolveStubPath(r===`js`?`seeder.js.stub`:`seeder.stub`);return{name:n,path:this.generateFile(a,i,{SeederName:n},t)}}makeMigration(e){let t=me(e,{directory:this.resolveConfigPath(`migrations`,u(process.cwd(),`database`,`migrations`)),extension:this.resolveOutputExt()});return{name:t.className,path:t.filePath}}makeModel(e,t={}){let n=b(e.replace(/Model$/,``)).pascal().toString(),r=`${n}`,i=b(n).camel().plural().toString(),a=this.resolveOutputExt(),o=u(this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`)),`${r}.${a}`),s=t.all||t.factory,l=t.all||t.seeder,f=t.all||t.migration,p=`${n}Factory`,m=u(this.resolveConfigPath(`factories`,u(process.cwd(),`database`,`factories`)),`${p}.${a}`),h=`./${d(c(o),m).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`,g=this.resolveStubPath(a===`js`?`model.js.stub`:`model.stub`),_=this.generateFile(g,o,{ModelName:r,DelegateName:i,FactoryImport:s?`import { ${p} } from '${h}'\n`:``,FactoryLink:s?a===`js`?`\n static factoryClass = ${p}`:`\n protected static override factoryClass = ${p}`:``},t),v=this.ensurePrismaModelEntry(r,i),y={model:{name:r,path:_},prisma:v,factory:void 0,seeder:void 0,migration:void 0};return s&&(y.factory=this.makeFactory(n,{force:t.force,modelName:r,modelImportPath:`./${d(c(m),o).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`})),l&&(y.seeder=this.makeSeeder(n,{force:t.force})),f&&(y.migration=this.makeMigration(`create ${i} table`)),y}ensurePrismaModelEntry(e,n){let i=u(process.cwd(),`prisma`,`schema.prisma`);if(!t(i))return{path:i,updated:!1};let a=r(i,`utf-8`),s=Y(a,n),c=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(a);return s||c?{path:i,updated:!1}:(o(i,X(a,{type:`createTable`,table:n,columns:[{name:`id`,type:`id`,primary:!0}]})),{path:i,updated:!0})}prismaTypeToTs(e){return e===`Int`||e===`Float`||e===`Decimal`?`number`:e===`BigInt`?`bigint`:e===`String`?`string`:e===`Boolean`?`boolean`:e===`DateTime`?`Date`:e===`Json`?`Record<string, unknown>`:e===`Bytes`?`Buffer`:`unknown`}parsePrismaModels(e){let t=[],n=/model\s+(\w+)\s*\{([\s\S]*?)\n\}/g,r=new Set([`Int`,`Float`,`Decimal`,`BigInt`,`String`,`Boolean`,`DateTime`,`Json`,`Bytes`]);for(let i of e.matchAll(n)){let e=i[1],n=i[2],a=n.match(/@@map\("([^"]+)"\)/)?.[1]??`${e.charAt(0).toLowerCase()}${e.slice(1)}s`,o=[];n.split(`
49
+ `).forEach(e=>{let t=e.trim();if(!t||t.startsWith(`@@`)||t.startsWith(`//`))return;let n=t.match(/^(\w+)\s+([A-Za-z]+)(\?)?\b/);if(!n)return;let i=n[2];r.has(i)&&o.push({name:n[1],type:this.prismaTypeToTs(i),optional:!!n[3]})}),t.push({name:e,table:a,fields:o})}return t}syncModelDeclarations(e,t){let n=e.split(`
50
+ `),r=n.findIndex(e=>/export\s+class\s+\w+\s+extends\s+Model<.+>\s*\{/.test(e));if(r<0)return{content:e,updated:!1};let i=-1,a=0;for(let e=r;e<n.length;e+=1){let t=n[e];if(a+=(t.match(/\{/g)||[]).length,a-=(t.match(/\}/g)||[]).length,a===0){i=e;break}}if(i<0)return{content:e,updated:!1};let o=n.slice(r+1,i).filter(e=>!/^\s*declare\s+\w+\??:\s*[^\n]+$/.test(e)),s=[...t.map(e=>` ${e}`),...o],c=[...n.slice(0,r+1),...s,...n.slice(i)].join(`
51
+ `);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let n=e.schemaPath??u(process.cwd(),`prisma`,`schema.prisma`),a=e.modelsDir??this.resolveConfigPath(`models`,u(process.cwd(),`src`,`models`));if(!t(n))throw Error(`Prisma schema file not found: ${n}`);if(!t(a))throw Error(`Models directory not found: ${a}`);let s=r(n,`utf-8`),c=this.parsePrismaModels(s),l=i(a).filter(e=>e.endsWith(`.ts`)),d=[],f=[];return l.forEach(e=>{let t=u(a,e),n=r(t,`utf-8`),i=n.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!i){f.push(t);return}let s=i[1],l=i[2],p=c.find(e=>e.table===l)??c.find(e=>e.name===s);if(!p||p.fields.length===0){f.push(t);return}let m=p.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),h=this.syncModelDeclarations(n,m);if(!h.updated){f.push(t);return}o(t,h.content),d.push(t)}),{schemaPath:n,modelsDir:a,total:l.length,updated:d,skipped:f}}};await ee.init(_e,{logo:B,name:`Arkormˣ CLI`,baseCommands:[ie,N,ae,P,oe,L,z,I],exceptionHandler(e){throw e}});export{};
package/dist/index.cjs ADDED
@@ -0,0 +1,50 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`fs`),l=require(`path`);l=s(l);let u=require(`module`),d=require(`node:fs`),f=require(`node:path`),p=require(`@h3ravel/support`),m=require(`node:child_process`),h=require(`url`),ee=require(`@h3ravel/shared`),g=require(`@h3ravel/musket`),_=require(`node:url`),te=require(`@h3ravel/collect.js`);const ne={string:{get:e=>e==null?e:String(e),set:e=>e==null?e:String(e)},number:{get:e=>e==null?e:Number(e),set:e=>e==null?e:Number(e)},boolean:{get:e=>e==null?e:!!e,set:e=>e==null?e:!!e},date:{get:e=>e==null||e instanceof Date?e:new Date(String(e)),set:e=>e==null||e instanceof Date?e:new Date(String(e))},json:{get:e=>{if(e==null||typeof e!=`string`)return e;try{return JSON.parse(e)}catch{return e}},set:e=>e==null||typeof e==`string`?e:JSON.stringify(e)},array:{get:e=>{if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{return[e]}return e==null?e:[e]},set:e=>e==null||Array.isArray(e)?e:[e]}};function v(e){return typeof e==`string`?ne[e]:e}var y=class extends Error{constructor(e){super(e),this.name=`ArkormException`}};const re=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,b=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim(),n=(t.endsWith(`s`)&&t.length>1?t.slice(0,-1):t).split(/\s+/g).filter(Boolean);return n.length===0?`GeneratedModel`:n.map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)},x=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ie=e=>e.type===`id`?`Int`:e.type===`string`||e.type===`text`?`String`:e.type===`integer`?`Int`:e.type===`bigInteger`?`BigInt`:e.type===`float`?`Float`:e.type===`boolean`?`Boolean`:e.type===`json`?`Json`:`DateTime`,ae=e=>{if(e!=null){if(typeof e==`string`)return`@default("${e.replace(/"/g,`\\"`)}")`;if(typeof e==`number`||typeof e==`bigint`)return`@default(${e})`;if(typeof e==`boolean`)return`@default(${e?`true`:`false`})`}},S=e=>{if(e.type===`id`)return` ${e.name} Int @id @default(autoincrement())`;let t=ie(e),n=e.nullable?`?`:``,r=e.unique?` @unique`:``,i=e.primary?` @id`:``,a=ae(e.default),o=a?` ${a}`:``;return` ${e.name} ${t}${n}${i}${r}${o}`},oe=e=>{let t=b(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(S),i=n?`\n\n @@map("${(0,p.str)(e.table).snake()}")`:``;return`model ${t} {\n${r.join(`
2
+ `)}${i}\n}`},C=(e,t)=>{let n=[...e.matchAll(re)],r=RegExp(`@@map\\("${x(t)}"\\)`);for(let e of n){let n=e[0],i=e[1],a=e.index??0,o=a+n.length;if(r.test(n)||i.toLowerCase()===t.toLowerCase()||i.toLowerCase()===b(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},w=(e,t)=>{if(C(e,t.table))throw new y(`Prisma model for table [${t.table}] already exists.`);let n=oe(t);return`${e.trimEnd()}\n\n${n}\n`},se=(e,t)=>{let n=C(e,t.table);if(!n)throw new y(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
3
+ `);t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${x(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}});let a=Math.max(1,i.length-1);return t.addColumns.forEach(e=>{let t=S(e),n=RegExp(`^\\s*${x(e.name)}\\s+`);i.some(e=>n.test(e))||i.splice(a,0,t)}),r=i.join(`
4
+ `),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},T=(e,t)=>{let n=C(e,t.table);if(!n)return e;let r=e.slice(0,n.start).trimEnd(),i=e.slice(n.end).trimStart();return`${r}${r&&i?`
5
+
6
+ `:``}${i}`},ce=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?w(e,t):t.type===`alterTable`?se(e,t):T(e,t),e),E=(e,t)=>{let n=(0,m.spawnSync)(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
7
+ `).trim();throw new y(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},le=e=>{let t=e.replace(/[^a-zA-Z0-9]+/g,` `).trim();return t?`${t.split(/\s+/g).map(e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`).join(``)}Migration`:`GeneratedMigration`},D=e=>String(e).padStart(2,`0`),O=(e=new Date)=>`${e.getFullYear()}${D(e.getMonth()+1)}${D(e.getDate())}${D(e.getHours())}${D(e.getMinutes())}${D(e.getSeconds())}`,k=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`migration`,ue=(e,t=`ts`)=>t===`js`?[`import { Migration } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async up (schema) {`,` }`,``,` /**`,` * @param {import('arkormx').SchemaBuilder} schema`,` * @returns {Promise<void>}`,` */`,` async down (schema) {`,` }`,`}`,``].join(`
8
+ `):[`import { Migration, SchemaBuilder } from 'arkormx'`,``,`export default class ${e} extends Migration {`,` public async up (schema: SchemaBuilder): Promise<void> {`,` }`,``,` public async down (schema: SchemaBuilder): Promise<void> {`,` }`,`}`,``].join(`
9
+ `),de=(e,t={})=>{let n=O(new Date),r=k(e),i=le(e),a=t.extension??`ts`,o=t.directory??(0,f.join)(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=(0,f.join)(o,s),l=ue(i,a);if(t.write??!0){if((0,d.existsSync)(o)||(0,d.mkdirSync)(o,{recursive:!0}),(0,d.existsSync)(c))throw new y(`Migration file already exists: ${c}`);(0,d.writeFileSync)(c,l)}return{fileName:s,filePath:c,className:i,content:l}},fe=async(e,t=`up`)=>{let n=e instanceof G?e:new e,r=new Me;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},A=async(e,t={})=>{let n=t.schemaPath??(0,f.join)(process.cwd(),`prisma`,`schema.prisma`);if(!(0,d.existsSync)(n))throw new y(`Prisma schema file not found: ${n}`);let r=(0,d.readFileSync)(n,`utf-8`),i=await fe(e,`up`),a=ce(r,i);return(t.write??!0)&&(0,d.writeFileSync)(n,a),{schema:a,schemaPath:n,operations:i}},pe=async(e,t={})=>{let n=t.cwd??process.cwd(),r=await A(e,{schemaPath:t.schemaPath??(0,f.join)(n,`prisma`,`schema.prisma`),write:t.write}),i=t.runGenerate??!0,a=t.runMigrate??!0,o=t.migrateMode??`dev`;return i&&E([`generate`],n),a&&E(o===`deploy`?[`migrate`,`deploy`]:[`migrate`,`dev`,`--name`,t.migrationName??`arkorm_${O()}`],n),{schemaPath:r.schemaPath,operations:r.operations}},me={paths:{stubs:(0,h.fileURLToPath)(new URL(`../../stubs`,require(`url`).pathToFileURL(__filename).href)),seeders:l.default.join(process.cwd(),`database`,`seeders`),models:l.default.join(process.cwd(),`src`,`models`),migrations:l.default.join(process.cwd(),`database`,`migrations`),factories:l.default.join(process.cwd(),`database`,`factories`),buildOutput:l.default.join(process.cwd(),`dist`)},outputExt:`ts`},j={...me};let M=!1,N,P,F;const he=e=>e,I=e=>e?j[e]:j,L=(e,t={})=>{Object.assign(j,{...t,prisma:e,paths:{...j.paths??{},...t.paths??{}}}),P=e,F=t.pagination?.urlDriver},ge=()=>{Object.assign(j,{...me}),M=!1,N=void 0,P=void 0,F=void 0},_e=e=>{if(!e)return;let t=typeof e==`function`?e():e;if(!(!t||typeof t!=`object`))return t},R=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(Object.assign(j,t),L(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),M=!0)},ve=e=>import(`${(0,h.pathToFileURL)(e).href}?arkorm_runtime=${Date.now()}`),z=()=>{let e=(0,u.createRequire)(e(`url`).pathToFileURL(__filename).href),t=[l.default.join(process.cwd(),`arkormx.config.cjs`)];for(let n of t)if((0,c.existsSync)(n))try{return R(e(n)),!0}catch{continue}return!1},B=async()=>{if(!M){if(N)return await N;z()||(N=(async()=>{let e=[l.default.join(process.cwd(),`arkormx.config.js`),l.default.join(process.cwd(),`arkormx.config.ts`)];for(let t of e)if((0,c.existsSync)(t))try{R(await ve(t));return}catch{continue}M=!0})(),await N)}},V=()=>{M||N||B()},H=()=>(M||z(),_e(P)),U=()=>(M||z(),F),W=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return[`findMany`,`findFirst`,`create`,`update`,`delete`,`count`].every(e=>typeof t[e]==`function`)};B();var ye=class{command;config={};constructor(){this.config=I()}getConfig=I;ensureDirectory(e){let t=(0,l.dirname)(e);(0,c.existsSync)(t)||(0,c.mkdirSync)(t,{recursive:!0})}formatPathForLog(e){let t=(0,l.relative)(process.cwd(),e);return t?t.startsWith(`..`)?e:t:`.`}splitLogger(e,t){return t=t.includes(process.cwd())?this.formatPathForLog(t):t,ee.Logger.twoColumnDetail(e+` `,` `+t,!1).join(``)}hasTypeScriptInstalled(){try{return(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve(`typescript`,{paths:[process.cwd()]}),!0}catch{return!1}}resolveOutputExt(){let e=this.getConfig(`outputExt`)===`js`?`js`:`ts`;return e===`ts`&&!this.hasTypeScriptInstalled()?`js`:e}stripKnownSourceExtension(e){return e.replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}resolveRuntimeDirectoryPath(e){if((0,c.existsSync)(e))return e;let{buildOutput:t}=this.getConfig(`paths`)||{};if(typeof t!=`string`||t.trim().length===0)return e;let n=(0,l.relative)(process.cwd(),e);if(!n||n.startsWith(`..`))return e;let r=(0,l.join)(t,n);return(0,c.existsSync)(r)?r:e}resolveRuntimeScriptPath(e){let t=(0,l.extname)(e).toLowerCase(),n=t===`.ts`||t===`.mts`||t===`.cts`,r=[];if(n){let n=e.slice(0,-t.length);r.push(`${n}.js`,`${n}.cjs`,`${n}.mjs`)}let{buildOutput:i}=this.getConfig(`paths`)??{};if(typeof i==`string`&&i.trim().length>0){let t=(0,l.relative)(process.cwd(),e);if(t&&!t.startsWith(`..`)){let e=(0,l.join)(i,t),n=(0,l.extname)(e).toLowerCase();if(n===`.ts`||n===`.mts`||n===`.cts`){let t=e.slice(0,-n.length);r.push(`${t}.js`,`${t}.cjs`,`${t}.mjs`)}else r.push(e)}}return r.find(e=>(0,c.existsSync)(e))||e}generateFile(e,t,n,r){(0,c.existsSync)(t)&&!r?.force?(this.command.error(`Error: ${this.formatPathForLog(t)} already exists.`),process.exit(1)):(0,c.existsSync)(t)&&r?.force&&(0,c.rmSync)(t);let i=(0,c.readFileSync)(e,`utf-8`);for(let[e,t]of Object.entries(n))i=i.replace(RegExp(`{{${e}}}`,`g`),t);return this.ensureDirectory(t),(0,c.writeFileSync)(t,i),t}resolveConfigPath(e,t){let{[e]:n}=this.getConfig(`paths`)??{};return typeof n==`string`&&n.trim().length>0?n:t}resolveStubPath(e){return(0,l.join)(this.resolveConfigPath(`stubs`,(0,l.join)(process.cwd(),`stubs`)),e)}makeFactory(e,t={}){let n=(0,p.str)(e.replace(/Factory$/,``)).pascal(),r=`${n}Factory`,i=t.modelName?(0,p.str)(t.modelName).pascal():n,a=this.resolveOutputExt(),o=(0,l.join)(this.resolveConfigPath(`factories`,(0,l.join)(process.cwd(),`database`,`factories`)),`${r}.${a}`),s=(0,l.join)(this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`)),`${i}.${a}`),c=t.modelImportPath??`./${this.stripKnownSourceExtension((0,l.relative)((0,l.dirname)(o),s).replace(/\\/g,`/`))}${a===`js`?`.js`:``}`,u=this.resolveStubPath(a===`js`?`factory.js.stub`:`factory.stub`);return{name:r,path:this.generateFile(u,o,{FactoryName:r,ModelName:i.toString(),ModelImportPath:c.startsWith(`.`)?c:`./${c}`},t)}}makeSeeder(e,t={}){let n=`${(0,p.str)(e.replace(/Seeder$/,``)).pascal()}Seeder`,r=this.resolveOutputExt(),i=(0,l.join)(this.resolveConfigPath(`seeders`,(0,l.join)(process.cwd(),`database`,`seeders`)),`${n}.${r}`),a=this.resolveStubPath(r===`js`?`seeder.js.stub`:`seeder.stub`);return{name:n,path:this.generateFile(a,i,{SeederName:n},t)}}makeMigration(e){let t=de(e,{directory:this.resolveConfigPath(`migrations`,(0,l.join)(process.cwd(),`database`,`migrations`)),extension:this.resolveOutputExt()});return{name:t.className,path:t.filePath}}makeModel(e,t={}){let n=(0,p.str)(e.replace(/Model$/,``)).pascal().toString(),r=`${n}`,i=(0,p.str)(n).camel().plural().toString(),a=this.resolveOutputExt(),o=(0,l.join)(this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`)),`${r}.${a}`),s=t.all||t.factory,c=t.all||t.seeder,u=t.all||t.migration,d=`${n}Factory`,f=(0,l.join)(this.resolveConfigPath(`factories`,(0,l.join)(process.cwd(),`database`,`factories`)),`${d}.${a}`),m=`./${(0,l.relative)((0,l.dirname)(o),f).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`,h=this.resolveStubPath(a===`js`?`model.js.stub`:`model.stub`),ee=this.generateFile(h,o,{ModelName:r,DelegateName:i,FactoryImport:s?`import { ${d} } from '${m}'\n`:``,FactoryLink:s?a===`js`?`\n static factoryClass = ${d}`:`\n protected static override factoryClass = ${d}`:``},t),g=this.ensurePrismaModelEntry(r,i),_={model:{name:r,path:ee},prisma:g,factory:void 0,seeder:void 0,migration:void 0};return s&&(_.factory=this.makeFactory(n,{force:t.force,modelName:r,modelImportPath:`./${(0,l.relative)((0,l.dirname)(f),o).replace(/\\/g,`/`).replace(/\.(ts|tsx|mts|cts|js|mjs|cjs)$/i,``)}${a===`js`?`.js`:``}`})),c&&(_.seeder=this.makeSeeder(n,{force:t.force})),u&&(_.migration=this.makeMigration(`create ${i} table`)),_}ensurePrismaModelEntry(e,t){let n=(0,l.join)(process.cwd(),`prisma`,`schema.prisma`);if(!(0,c.existsSync)(n))return{path:n,updated:!1};let r=(0,c.readFileSync)(n,`utf-8`),i=C(r,t),a=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(r);return i||a?{path:n,updated:!1}:((0,c.writeFileSync)(n,w(r,{type:`createTable`,table:t,columns:[{name:`id`,type:`id`,primary:!0}]})),{path:n,updated:!0})}prismaTypeToTs(e){return e===`Int`||e===`Float`||e===`Decimal`?`number`:e===`BigInt`?`bigint`:e===`String`?`string`:e===`Boolean`?`boolean`:e===`DateTime`?`Date`:e===`Json`?`Record<string, unknown>`:e===`Bytes`?`Buffer`:`unknown`}parsePrismaModels(e){let t=[],n=/model\s+(\w+)\s*\{([\s\S]*?)\n\}/g,r=new Set([`Int`,`Float`,`Decimal`,`BigInt`,`String`,`Boolean`,`DateTime`,`Json`,`Bytes`]);for(let i of e.matchAll(n)){let e=i[1],n=i[2],a=n.match(/@@map\("([^"]+)"\)/)?.[1]??`${e.charAt(0).toLowerCase()}${e.slice(1)}s`,o=[];n.split(`
10
+ `).forEach(e=>{let t=e.trim();if(!t||t.startsWith(`@@`)||t.startsWith(`//`))return;let n=t.match(/^(\w+)\s+([A-Za-z]+)(\?)?\b/);if(!n)return;let i=n[2];r.has(i)&&o.push({name:n[1],type:this.prismaTypeToTs(i),optional:!!n[3]})}),t.push({name:e,table:a,fields:o})}return t}syncModelDeclarations(e,t){let n=e.split(`
11
+ `),r=n.findIndex(e=>/export\s+class\s+\w+\s+extends\s+Model<.+>\s*\{/.test(e));if(r<0)return{content:e,updated:!1};let i=-1,a=0;for(let e=r;e<n.length;e+=1){let t=n[e];if(a+=(t.match(/\{/g)||[]).length,a-=(t.match(/\}/g)||[]).length,a===0){i=e;break}}if(i<0)return{content:e,updated:!1};let o=n.slice(r+1,i).filter(e=>!/^\s*declare\s+\w+\??:\s*[^\n]+$/.test(e)),s=[...t.map(e=>` ${e}`),...o],c=[...n.slice(0,r+1),...s,...n.slice(i)].join(`
12
+ `);return{content:c,updated:c!==e}}syncModelsFromPrisma(e={}){let t=e.schemaPath??(0,l.join)(process.cwd(),`prisma`,`schema.prisma`),n=e.modelsDir??this.resolveConfigPath(`models`,(0,l.join)(process.cwd(),`src`,`models`));if(!(0,c.existsSync)(t))throw Error(`Prisma schema file not found: ${t}`);if(!(0,c.existsSync)(n))throw Error(`Models directory not found: ${n}`);let r=(0,c.readFileSync)(t,`utf-8`),i=this.parsePrismaModels(r),a=(0,c.readdirSync)(n).filter(e=>e.endsWith(`.ts`)),o=[],s=[];return a.forEach(e=>{let t=(0,l.join)(n,e),r=(0,c.readFileSync)(t,`utf-8`),a=r.match(/export\s+class\s+(\w+)\s+extends\s+Model<'([^']+)'>/);if(!a){s.push(t);return}let u=a[1],d=a[2],f=i.find(e=>e.table===d)??i.find(e=>e.name===u);if(!f||f.fields.length===0){s.push(t);return}let p=f.fields.map(e=>`declare ${e.name}${e.optional?`?`:``}: ${e.type}`),m=this.syncModelDeclarations(r,p);if(!m.updated){s.push(t);return}(0,c.writeFileSync)(t,m.content),o.push(t)}),{schemaPath:t,modelsDir:n,total:a.length,updated:o,skipped:s}}},be=class extends g.Command{signature=`init
13
+ {--force : Force overwrite if config file already exists (existing file will be backed up) }
14
+ `;description=`Initialize Arkormˣ by creating a default config file in the current directory`;async handle(){this.app.command=this;let e=(0,f.join)(process.cwd(),`arkormx.config.js`),{stubs:t}=I(`paths`)??{},n=(0,f.join)(t??``,`arkormx.config.stub`);(0,c.existsSync)(e)&&!this.option(`force`)&&(this.error(`Error: Arkormˣ has already been initialized. Use --force to reinitialize.`),process.exit(1)),this.app.ensureDirectory(e),(0,c.existsSync)(e)&&this.option(`force`)&&(0,c.copyFileSync)(e,e.replace(/\.js$/,`.backup.${Date.now()}.js`)),(0,c.writeFileSync)(e,(0,c.readFileSync)(n,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},xe=class extends g.Command{signature=`make:factory
15
+ {name : Name of the factory to create}
16
+ {--f|force : Overwrite existing file}
17
+ `;description=`Create a new model factory class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeFactory(e,{force:this.option(`force`)});this.success(`Created factory: ${this.app.formatPathForLog(t.path)}`)}},Se=class extends g.Command{signature=`make:migration
18
+ {name : Name of the migration to create}
19
+ `;description=`Create a new migration class file`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeMigration(e);this.success(`Created migration: ${this.app.formatPathForLog(t.path)}`)}},Ce=class extends g.Command{signature=`make:model
20
+ {name : Name of the model to create}
21
+ {--f|force : Overwrite existing files}
22
+ {--factory : Create and link a factory}
23
+ {--seeder : Create a seeder}
24
+ {--migration : Create a migration}
25
+ {--all : Create and link factory, seeder, and migration}
26
+ `;description=`Create a new model and optional linked resources`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeModel(e,this.options());this.success(`Created files:`),[[`Model`,t.model.path],[`Prisma schema ${t.prisma.updated?`(updated)`:`(already up to date)`}`,t.prisma.path],t.factory?[`Factory`,t.factory.path]:``,t.seeder?[`Seeder`,t.seeder.path]:``,t.migration?[`Migration`,t.migration.path]:``].filter(Boolean).map(([e,t])=>this.success(this.app.splitLogger(e,t)))}},we=class extends g.Command{signature=`make:seeder
27
+ {name : Name of the seeder to create}
28
+ {--f|force : Overwrite existing file}
29
+ `;description=`Create a new seeder class`;async handle(){this.app.command=this;let e=this.argument(`name`);if(!e)return void this.error(`Error: Name argument is required.`);let t=this.app.makeSeeder(e,this.options());this.success(`Created seeder: ${this.app.formatPathForLog(t.path)}`)}},G=class{},Te=class extends g.Command{signature=`migrate
30
+ {name? : Migration class or file name}
31
+ {--all : Run all migrations from the configured migrations directory}
32
+ {--deploy : Use prisma migrate deploy instead of migrate dev}
33
+ {--skip-generate : Skip prisma generate}
34
+ {--skip-migrate : Skip prisma migrate command}
35
+ {--schema= : Explicit prisma schema path}
36
+ {--migration-name= : Name for prisma migrate dev}
37
+ `;description=`Apply migration classes to schema.prisma and run Prisma workflow`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.migrations??(0,f.join)(process.cwd(),`database`,`migrations`),t=this.app.resolveRuntimeDirectoryPath(e);if(!(0,d.existsSync)(t))return void this.error(`Error: Migrations directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`schema`)?(0,f.resolve)(String(this.option(`schema`))):(0,f.join)(process.cwd(),`prisma`,`schema.prisma`),r=this.option(`all`)?await this.loadAllMigrations(t):(await this.loadNamedMigration(t,this.argument(`name`))).filter(([e])=>e!==void 0);if(r.length===0)return void this.error(`Error: No migration classes found to run.`);for(let[e]of r)await A(e,{schemaPath:n,write:!0});this.option(`skip-generate`)||E([`generate`],process.cwd()),this.option(`skip-migrate`)||(this.option(`deploy`)?E([`migrate`,`deploy`],process.cwd()):E([`migrate`,`dev`,`--name`,this.option(`migration-name`)?String(this.option(`migration-name`)):`arkorm_cli_${Date.now()}`],process.cwd())),this.success(`Applied ${r.length} migration(s).`),r.forEach(([e,t])=>this.success(this.app.splitLogger(`Migrated`,t)))}async loadAllMigrations(e){let t=(0,d.readdirSync)(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).sort((e,t)=>e.localeCompare(t)).map(t=>this.app.resolveRuntimeScriptPath((0,f.join)(e,t)));return(await Promise.all(t.map(async e=>(await this.loadMigrationClassesFromFile(e)).map(t=>[t,e])))).flat()}async loadNamedMigration(e,t){if(!t)return[[void 0,``]];let n=t.replace(/Migration$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Migration.ts`,`${n}Migration.js`,`${n}Migration.mjs`,`${n}Migration.cjs`].map(t=>(0,f.join)(e,t)).find(e=>(0,d.existsSync)(e));if(!r)return[[void 0,t]];let i=this.app.resolveRuntimeScriptPath(r);return(await this.loadMigrationClassesFromFile(i)).map(e=>[e,i])}async loadMigrationClassesFromFile(e){let t=await import(`${(0,_.pathToFileURL)((0,f.resolve)(e)).href}?arkorm_migrate=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof G:!1)}},Ee=class extends g.Command{signature=`models:sync
38
+ {--schema= : Path to prisma schema file}
39
+ {--models= : Path to models directory}
40
+ `;description=`Sync model declare attributes from prisma schema for all model files`;async handle(){this.app.command=this;let e=this.app.syncModelsFromPrisma({schemaPath:this.option(`schema`)?(0,f.resolve)(String(this.option(`schema`))):void 0,modelsDir:this.option(`models`)?(0,f.resolve)(String(this.option(`models`))):void 0}),t=e.updated.length===0?[this.app.splitLogger(`Updated`,`none`)]:e.updated.map(e=>this.app.splitLogger(`Updated`,e));this.success(`SUCCESS: Model sync completed with the following results:`),[this.app.splitLogger(`Schema`,e.schemaPath),this.app.splitLogger(`Models`,e.modelsDir),this.app.splitLogger(`Processed`,String(e.total)),...t,this.app.splitLogger(`Skipped`,String(e.skipped.length))].map(e=>this.success(e))}},De=class e{async call(...t){await e.runSeeders(...t)}static toSeederInstance(t){return t instanceof e?t:new t}static async runSeeders(...e){let t=e.reduce((e,t)=>Array.isArray(t)?[...e,...t]:(e.push(t),e),[]);for(let e of t)await this.toSeederInstance(e).run()}},Oe=class extends g.Command{signature=`seed
41
+ {name? : Seeder class or file name}
42
+ {--all : Run all seeders in the configured seeders directory}
43
+ `;description=`Run one or more seeders`;async handle(){this.app.command=this;let e=this.app.getConfig(`paths`)?.seeders??(0,f.join)(process.cwd(),`database`,`seeders`),t=this.app.resolveRuntimeDirectoryPath(e);if(!(0,d.existsSync)(t))return void this.error(`ERROR: Seeders directory not found: ${this.app.formatPathForLog(e)}`);let n=this.option(`all`)?await this.loadAllSeeders(t):await this.loadNamedSeeder(t,this.argument(`name`)??`DatabaseSeeder`);if(n.length===0)return void this.error(`ERROR: No seeder classes found to run.`);for(let e of n)await new e().run();this.success(`Database seeding completed`),n.forEach(e=>this.success(this.app.splitLogger(`Seeded`,e.name)))}async loadAllSeeders(e){let t=(0,d.readdirSync)(e).filter(e=>/\.(ts|js|mjs|cjs)$/i.test(e)).map(t=>this.app.resolveRuntimeScriptPath((0,f.join)(e,t)));return(await Promise.all(t.map(async e=>await this.loadSeederClassesFromFile(e)))).flat()}async loadNamedSeeder(e,t){let n=t.replace(/Seeder$/,``),r=[`${t}.ts`,`${t}.js`,`${t}.mjs`,`${t}.cjs`,`${n}Seeder.ts`,`${n}Seeder.js`,`${n}Seeder.mjs`,`${n}Seeder.cjs`].map(t=>(0,f.join)(e,t)).find(e=>(0,d.existsSync)(e));if(!r)return[];let i=this.app.resolveRuntimeScriptPath(r);return await this.loadSeederClassesFromFile(i)}async loadSeederClassesFromFile(e){let t=await import(`${(0,_.pathToFileURL)((0,f.resolve)(e)).href}?arkorm_seed=${Date.now()}`);return Object.values(t).filter(e=>typeof e==`function`?e.prototype instanceof De:!1)}};String.raw`
44
+ __/^^^^^^^^^^^^^^^^\__
45
+ ▄▄▄/ \▄▄
46
+ ▄██▀▀██▄ ▄▄
47
+ ███ ███ ████▄ ██ ▄█▀ ▄███▄ ████▄ ███▄███▄
48
+ ███▀▀███ ██ ▀▀ ████ ██ ██ ██ ▀▀ ██ ██ ██
49
+ ███ ███ ██ ██ ▀█▄ ▀███▀ ██ ██ ██ ██
50
+ `;var K=class extends te.Collection{},ke=class{amount=1;sequence=0;states=[];count(e){return this.amount=Math.max(1,Math.floor(e)),this}state(e){return this.states.push(e),this}make(e={}){let t=this.buildAttributes(e);return new this.model(t)}makeMany(e=this.amount,t={}){let n=Math.max(1,Math.floor(e));return Array.from({length:n},()=>this.make(t))}async create(e={}){let t=this.make(e);if(typeof t.save!=`function`)throw Error(`Factory model does not support save().`);return await t.save()}async createMany(e=this.amount,t={}){let n=this.makeMany(e,t);return await Promise.all(n.map(async e=>{if(typeof e.save!=`function`)throw Error(`Factory model does not support save().`);return await e.save()}))}buildAttributes(e){let t=this.sequence;this.sequence+=1;let n=this.definition(t);for(let e of this.states)n=e(n,t);return{...n,...e}}},Ae=class extends ke{model;constructor(e,t){super(),this.resolver=t,this.model=e}definition(e){return this.resolver(e)}};const je=(e,t)=>new Ae(e,t);var q=class{columns=[];dropColumnNames=[];id(e=`id`){return this.column(e,`id`,{primary:!0})}string(e,t={}){return this.column(e,`string`,t)}text(e,t={}){return this.column(e,`text`,t)}integer(e,t={}){return this.column(e,`integer`,t)}bigInteger(e,t={}){return this.column(e,`bigInteger`,t)}float(e,t={}){return this.column(e,`float`,t)}boolean(e,t={}){return this.column(e,`boolean`,t)}json(e,t={}){return this.column(e,`json`,t)}date(e,t={}){return this.column(e,`date`,t)}morphs(e,t=!1){return this.string(`${e}Type`,{nullable:t}),this.integer(`${e}Id`,{nullable:t}),this}nullableMorphs(e){return this.morphs(e,!0)}timestamp(e,t={}){return this.column(e,`timestamp`,t)}timestamps(){return this.timestamp(`createdAt`,{nullable:!1}),this.timestamp(`updatedAt`,{nullable:!1}),this}softDeletes(e=`deletedAt`){return this.timestamp(e,{nullable:!0}),this}dropColumn(e){return this.dropColumnNames.push(e),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}column(e,t,n){return this.columns.push({name:e,type:t,nullable:n.nullable,unique:n.unique,primary:n.primary,default:n.default}),this}},Me=class{operations=[];createTable(e,t){let n=new q;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns()}),this}alterTable(e,t){let n=new q;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns()}),this}dropTable(e){return this.operations.push({type:`dropTable`,table:e}),this}getOperations(){return this.operations.map(e=>e.type===`createTable`?{...e,columns:e.columns.map(e=>({...e}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns]}:{...e})}},J=class extends y{constructor(e=`No query results for the given model.`){super(e),this.name=`ModelNotFoundException`}};function Y(e){return Object.entries(e).reduce((e,[t,n])=>(W(n)&&(e[t]=n),e),{})}function Ne(e){return Y(e)}function Pe(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}s`}var X=class{constraint=null;constrain(e){if(!this.constraint)return this.constraint=e,this;let t=this.constraint;return this.constraint=n=>{let r=t(n)??n;return e(r)??r},this}where(e){return this.constrain(t=>t.where(e))}whereKey(e,t){return this.constrain(n=>n.whereKey(e,t))}whereIn(e,t){return this.constrain(n=>n.whereIn(e,t))}orderBy(e){return this.constrain(t=>t.orderBy(e))}include(e){return this.constrain(t=>t.include(e))}with(e){return this.constrain(t=>t.with(e))}select(e){return this.constrain(t=>t.select(e))}skip(e){return this.constrain(t=>t.skip(e))}take(e){return this.constrain(t=>t.take(e))}withTrashed(){return this.constrain(e=>e.withTrashed())}onlyTrashed(){return this.constrain(e=>e.onlyTrashed())}withoutTrashed(){return this.constrain(e=>e.withoutTrashed())}scope(e,...t){return this.constrain(n=>n.scope(e,...t))}applyConstraint(e){return this.constraint?this.constraint(e)??e:e}async get(){return this.getResults()}async first(){let e=await this.getResults();return e instanceof K?e.all()[0]??null:e}},Fe=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.foreignPivotKey]:e}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:t}})).get()}},Ie=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.ownerKey=r}async getResults(){let e=this.parent.getAttribute(this.foreignKey);return this.applyConstraint(this.related.query().where({[this.ownerKey]:e})).first()}},Le=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).get()}},Re=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[this.firstKey]:e}})).map(e=>e[this.secondLocalKey]);return this.applyConstraint(this.related.query().where({[this.secondKey]:{in:t}})).get()}},ze=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.foreignKey=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey);return this.applyConstraint(this.related.query().where({[this.foreignKey]:e})).first()}},Be=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.firstKey=r,this.secondKey=i,this.localKey=a,this.secondLocalKey=o}async getResults(){let e=this.parent.getAttribute(this.localKey),t=await this.related.getDelegate(this.throughDelegate).findFirst({where:{[this.firstKey]:e}});return t?this.applyConstraint(this.related.query().where({[this.secondKey]:t[this.secondLocalKey]})).first():null}},Ve=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).get()}},He=class extends X{constructor(e,t,n,r){super(),this.parent=e,this.related=t,this.morphName=n,this.localKey=r}async getResults(){let e=this.parent.getAttribute(this.localKey),t=this.parent.constructor.name;return this.applyConstraint(this.related.query().where({[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t})).first()}},Ue=class extends X{constructor(e,t,n,r,i,a,o){super(),this.parent=e,this.related=t,this.throughDelegate=n,this.morphName=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o}async getResults(){let e=this.parent.getAttribute(this.parentKey),t=this.parent.constructor.name,n=(await this.related.getDelegate(this.throughDelegate).findMany({where:{[`${this.morphName}Id`]:e,[`${this.morphName}Type`]:t}})).map(e=>e[this.relatedPivotKey]);return this.applyConstraint(this.related.query().where({[this.relatedKey]:{in:n}})).get()}},Z=class e{static DEFAULT_PAGE_NAME=`page`;path;query;fragment;pageName;constructor(t={}){this.path=t.path??`/`,this.query=t.query??{},this.fragment=t.fragment??``,this.pageName=t.pageName??e.DEFAULT_PAGE_NAME}getPageName(){return this.pageName}url(e){let t=Math.max(1,e),[n,r=``]=this.path.split(`?`),i=new URLSearchParams(r);Object.entries(this.query).forEach(([e,t])=>{if(t==null){i.delete(e);return}i.set(e,String(t))}),i.set(this.pageName,String(t));let a=i.toString(),o=this.fragment.replace(/^#/,``);return!a&&!o?n:o?a?`${n}?${a}#${o}`:`${n}#${o}`:`${n}?${a}`}},Q=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=Math.max(1,Math.ceil(t/n)),o=t===0?null:(r-1)*n+1,s=t===0?null:Math.min(r*n,t);this.data=e;let c=U();this.urlDriver=c?c(i):new Z(i),this.meta={total:t,perPage:n,currentPage:r,lastPage:a,from:o,to:s}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.currentPage>=this.meta.lastPage?null:this.url(this.meta.currentPage+1)}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}firstPageUrl(){return this.url(1)}lastPageUrl(){return this.url(this.meta.lastPage)}toJSON(){return{data:this.data,meta:this.meta,links:{first:this.firstPageUrl(),last:this.lastPageUrl(),prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},$=class{data;meta;urlDriver;constructor(e,t,n,r,i={}){let a=e.all().length,o=a===0?null:(n-1)*t+1,s=a===0?null:(o??1)+a-1;this.data=e;let c=U();this.urlDriver=c?c(i):new Z(i),this.meta={perPage:t,currentPage:n,from:o,to:s,hasMorePages:r}}getPageName(){return this.urlDriver.getPageName()}url(e){return this.urlDriver.url(e)}nextPageUrl(){return this.meta.hasMorePages?this.url(this.meta.currentPage+1):null}previousPageUrl(){return this.meta.currentPage<=1?null:this.url(this.meta.currentPage-1)}toJSON(){return{data:this.data,meta:this.meta,links:{prev:this.previousPageUrl(),next:this.nextPageUrl()}}}},We=class e{args={};eagerLoads={};includeTrashed=!1;onlyTrashedRecords=!1;randomOrderEnabled=!1;relationFilters=[];relationAggregates=[];constructor(e,t){this.delegate=e,this.model=t}where(e){return this.addLogicalWhere(`AND`,e)}orWhere(e){return this.addLogicalWhere(`OR`,e)}whereNot(e){return this.where({NOT:e})}orWhereNot(e){return this.orWhere({NOT:e})}whereNull(e){return this.where({[e]:null})}whereNotNull(e){return this.where({[e]:{not:null}})}whereBetween(e,t){let[n,r]=t;return this.where({[e]:{gte:n,lte:r}})}whereDate(e,t){let n=this.coerceDate(t),r=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),this.where({[e]:{gte:r,lt:i}})}whereMonth(e,t,n=new Date().getUTCFullYear()){let r=Math.min(12,Math.max(1,t)),i=new Date(Date.UTC(n,r-1,1)),a=new Date(Date.UTC(n,r,1));return this.where({[e]:{gte:i,lt:a}})}whereYear(e,t){let n=new Date(Date.UTC(t,0,1)),r=new Date(Date.UTC(t+1,0,1));return this.where({[e]:{gte:n,lt:r}})}whereKeyNot(e,t){return this.where({[e]:{not:t}})}orWhereIn(e,t){return this.orWhere({[e]:{in:t}})}whereNotIn(e,t){return this.where({[e]:{notIn:t}})}orWhereNotIn(e,t){return this.orWhere({[e]:{notIn:t}})}async firstWhere(e,t,n){let r=n!==void 0,i=r?t:`=`,a=r?n:t;return this.clone().where(this.buildComparisonWhere(e,i,a)).first()}addLogicalWhere(e,t){return this.args.where?(this.args.where={[e]:[this.args.where,t]},this):(this.args.where=t,this)}buildComparisonWhere(e,t,n){return t===`=`?{[e]:n}:t===`!=`?{[e]:{not:n}}:t===`>`?{[e]:{gt:n}}:t===`>=`?{[e]:{gte:n}}:t===`<`?{[e]:{lt:n}}:{[e]:{lte:n}}}coerceDate(e){let t=e instanceof Date?new Date(e.getTime()):new Date(e);if(Number.isNaN(t.getTime()))throw new y(`Invalid date value for date-based query helper.`);return t}whereKey(e,t){return this.where({[e]:t})}whereIn(e,t){return this.where({[e]:{in:t}})}orderBy(e){return this.randomOrderEnabled=!1,this.args.orderBy=e,this}inRandomOrder(){return this.randomOrderEnabled=!0,this}reorder(e,t=`asc`){return this.args.orderBy=void 0,this.randomOrderEnabled=!1,e?this.orderBy({[e]:t}):this}latest(e=`createdAt`){return this.orderBy({[e]:`desc`})}oldest(e=`createdAt`){return this.orderBy({[e]:`asc`})}include(e){return this.args.include=e,this}with(e){let t=this.normalizeWith(e),n=Object.keys(t);return this.args.include={...this.args.include||{},...n.reduce((e,t)=>(e[t]=!0,e),{})},Object.entries(t).forEach(([e,t])=>{this.eagerLoads[e]=t}),this}has(e,t=`>=`,n=1,r){return this.relationFilters.push({relation:e,callback:r,operator:t,count:n,boolean:`AND`}),this}orHas(e,t=`>=`,n=1){return this.relationFilters.push({relation:e,operator:t,count:n,boolean:`OR`}),this}doesntHave(e,t){return this.has(e,`<`,1,t)}orDoesntHave(e){return this.orHas(e,`<`,1)}whereHas(e,t,n=`>=`,r=1){return this.has(e,n,r,t)}orWhereHas(e,t,n=`>=`,r=1){return this.relationFilters.push({relation:e,callback:t,operator:n,count:r,boolean:`OR`}),this}whereDoesntHave(e,t){return this.whereHas(e,t,`<`,1)}orWhereDoesntHave(e,t){return this.orWhereHas(e,t,`<`,1)}withCount(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`count`,relation:e})}),this}withExists(e){return(Array.isArray(e)?e:[e]).forEach(e=>{this.relationAggregates.push({type:`exists`,relation:e})}),this}withSum(e,t){return this.relationAggregates.push({type:`sum`,relation:e,column:t}),this}withAvg(e,t){return this.relationAggregates.push({type:`avg`,relation:e,column:t}),this}withMin(e,t){return this.relationAggregates.push({type:`min`,relation:e,column:t}),this}withMax(e,t){return this.relationAggregates.push({type:`max`,relation:e,column:t}),this}withTrashed(){return this.includeTrashed=!0,this.onlyTrashedRecords=!1,this}onlyTrashed(){return this.onlyTrashedRecords=!0,this.includeTrashed=!1,this}withoutTrashed(){return this.includeTrashed=!1,this.onlyTrashedRecords=!1,this}scope(e,...t){let n=`scope${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=this.model.prototype?.[n];if(typeof r!=`function`)throw new y(`Scope [${e}] is not defined.`);let i=r.call(void 0,this,...t);return i&&i!==this?i:this}when(e,t,n){let r=typeof e==`function`?e():e;return r?t(this,r):n?n(this,r):this}unless(e,t,n){let r=typeof e==`function`?e():e;return r?n?n(this,r):this:t(this,r)}tap(e){return e(this),this}pipe(e){return e(this)}select(e){return this.args.select=e,this}skip(e){return this.args.skip=e,this}offset(e){return this.skip(e)}take(e){return this.args.take=e,this}limit(e){return this.take(e)}forPage(e,t=15){let n=Math.max(1,e),r=Math.max(1,t);return this.skip((n-1)*r).take(r)}async get(){let e=new WeakMap,t=await this.delegate.findMany(this.buildFindArgs()),n=this.randomOrderEnabled?this.shuffleRows(t):t,r=this.model.hydrateMany(n),i=r;if(this.hasRelationFilters())if(this.hasOrRelationFilters()&&this.args.where){let t=new Set(r.map(e=>this.getModelId(e)).filter(e=>e!=null)),n=await this.delegate.findMany({...this.args,where:this.buildSoftDeleteOnlyWhere()}),a=this.model.hydrateMany(n);i=await this.filterModelsByRelationConstraints(a,e,t)}else i=await this.filterModelsByRelationConstraints(r,e);return this.hasRelationAggregates()&&await this.applyRelationAggregates(i,e),await Promise.all(i.map(async e=>{await e.load(this.eagerLoads)})),new K(i)}async first(){if(this.hasRelationFilters()||this.hasRelationAggregates())return(await this.get()).all()[0]??null;if(this.randomOrderEnabled){let e=await this.delegate.findMany(this.buildFindArgs());if(e.length===0)return null;let t=this.shuffleRows(e)[0];if(!t)return null;let n=this.model.hydrate(t);return await n.load(this.eagerLoads),n}let e=await this.delegate.findFirst(this.buildFindArgs());if(!e)return null;let t=this.model.hydrate(e);return await t.load(this.eagerLoads),t}async firstOrFail(){let e=await this.first();if(!e)throw new J(`Record not found.`);return e}async find(e,t=`id`){return this.where({[t]:e}).first()}async findOr(e,t,n){let r=typeof t==`string`?t:`id`,i=typeof t==`function`?t:n;if(!i)throw new y(`findOr requires a fallback callback.`);return await this.find(e,r)||i()}async value(e){let t=await this.delegate.findFirst(this.buildFindArgs());return t?t[e]??null:null}async valueOrFail(e){let t=await this.value(e);if(t==null)throw new J(`Record not found.`);return t}async pluck(e,t){let n=await this.delegate.findMany(this.buildFindArgs());return t?new K(n.sort((e,n)=>String(e[t]).localeCompare(String(n[t]))).map(t=>t[e])):new K(n.map(t=>t[e]))}async create(e){let t=await this.delegate.create({data:e});return this.model.hydrate(t)}async update(e){let t=this.buildWhere();if(!t)throw new y(`Update requires a where clause.`);let n=await this.resolveUniqueWhere(t),r=await this.delegate.update({where:n,data:e});return this.model.hydrate(r)}async delete(){let e=this.buildWhere();if(!e)throw new y(`Delete requires a where clause.`);let t=await this.resolveUniqueWhere(e),n=await this.delegate.delete({where:t});return this.model.hydrate(n)}async count(){return this.hasRelationFilters()?(await this.get()).all().length:this.delegate.count({where:this.buildWhere()})}async exists(){return this.hasRelationFilters()?await this.count()>0:await this.delegate.findFirst(this.buildFindArgs())!=null}async doesntExist(){return!await this.exists()}async existsOr(e){return await this.exists()?!0:e()}async doesntExistOr(e){return await this.doesntExist()?!0:e()}async min(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t<e?t:e)}async max(e){let t=await this.delegate.findMany(this.buildFindArgs());if(t.length===0)return null;let n=t.map(t=>t[e]).filter(e=>e!=null);return n.length===0?null:n.reduce((e,t)=>t>e?t:e)}async sum(e){return(await this.delegate.findMany(this.buildFindArgs())).reduce((t,n)=>{let r=n[e],i=typeof r==`number`?r:Number(r);return Number.isFinite(i)?t+i:t},0)}async avg(e){let t=(await this.delegate.findMany(this.buildFindArgs())).map(t=>{let n=t[e];return typeof n==`number`?n:Number(n)}).filter(e=>Number.isFinite(e));return t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length}whereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new y(`Raw where clauses are not supported by the current adapter.`);return this.args.where=n.applyRawWhere(this.buildWhere(),e,t),this}orWhereRaw(e,t=[]){let n=this.delegate;if(typeof n.applyRawWhere!=`function`)throw new y(`Raw where clauses are not supported by the current adapter.`);let r=n.applyRawWhere(void 0,e,t);return this.orWhere(r)}async paginate(e=1,t=15,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,e),i=Math.max(1,t),a=(await this.get()).all(),o=(r-1)*i;return new Q(new K(a.slice(o,o+i)),a.length,i,r,n)}let r=Math.max(1,e),i=Math.max(1,t),a=await this.count();return new Q(await this.clone().skip((r-1)*i).take(i).get(),a,i,r,n)}async simplePaginate(e=15,t=1,n={}){if(this.hasRelationFilters()||this.hasRelationAggregates()){let r=Math.max(1,t),i=Math.max(1,e),a=(await this.get()).all(),o=(r-1)*i,s=a.slice(o,o+i),c=o+i<a.length;return new $(new K(s),i,r,c,n)}let r=Math.max(1,t),i=Math.max(1,e),a=await this.clone().skip((r-1)*i).take(i+1).get(),o=a.all().length>i;return new $(o?new K(a.all().slice(0,i)):a,i,r,o,n)}clone(){let t=new e(this.delegate,this.model);return t.args.where=this.args.where,t.args.include=this.args.include,t.args.orderBy=this.args.orderBy,t.args.select=this.args.select,t.args.skip=this.args.skip,t.args.take=this.args.take,t.includeTrashed=this.includeTrashed,t.onlyTrashedRecords=this.onlyTrashedRecords,t.randomOrderEnabled=this.randomOrderEnabled,this.relationFilters.forEach(e=>{t.relationFilters.push({...e})}),this.relationAggregates.forEach(e=>{t.relationAggregates.push({...e})}),Object.entries(this.eagerLoads).forEach(([e,n])=>{t.eagerLoads[e]=n}),t}normalizeWith(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}buildWhere(){let e=this.model.getSoftDeleteConfig();if(!e.enabled||this.includeTrashed)return this.args.where;let t=this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null};return this.args.where?{AND:[this.args.where,t]}:t}buildFindArgs(){return{...this.args,where:this.buildWhere()}}async resolveUniqueWhere(e){if(this.isUniqueWhere(e))return e;let t=await this.delegate.findFirst({where:e});if(!t)throw new y(`Record not found for update/delete operation.`);let n=t;if(!Object.prototype.hasOwnProperty.call(n,`id`))throw new y(`Unable to resolve a unique identifier for update/delete operation. Include an id in the query constraints.`);return{id:n.id}}isUniqueWhere(e){return Object.keys(e).length===1&&Object.prototype.hasOwnProperty.call(e,`id`)}shuffleRows(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}hasRelationFilters(){return this.relationFilters.length>0}hasOrRelationFilters(){return this.relationFilters.some(e=>e.boolean===`OR`)}hasRelationAggregates(){return this.relationAggregates.length>0}async filterModelsByRelationConstraints(e,t,n){return(await Promise.all(e.map(async e=>{let r=null;n&&(r=n.has(this.getModelId(e)));for(let n of this.relationFilters){let i=await this.resolveRelatedCount(e,n.relation,t,n.callback),a=this.compareCount(i,n.operator,n.count);r=r==null?a:n.boolean===`AND`?r&&a:r||a}return{model:e,passes:r??!0}}))).filter(e=>e.passes).map(e=>e.model)}getModelId(e){let t=e;if(typeof t.getAttribute!=`function`)return null;let n=t.getAttribute(`id`);return typeof n==`number`||typeof n==`string`?n:null}buildSoftDeleteOnlyWhere(){let e=this.model.getSoftDeleteConfig();if(e.enabled&&!this.includeTrashed)return this.onlyTrashedRecords?{[e.column]:{not:null}}:{[e.column]:null}}async applyRelationAggregates(e,t){let n=t??new WeakMap;await Promise.all(e.map(async e=>{for(let t of this.relationAggregates){let r=await this.resolveRelatedResults(e,t.relation,n),i=Array.isArray(r)?r:r?[r]:[],a=this.buildAggregateAttributeKey(t);if(t.type===`count`){this.assignAggregate(e,a,i.length);continue}if(t.type===`exists`){this.assignAggregate(e,a,i.length>0);continue}let o=i.map(e=>e.getAttribute(t.column)).filter(e=>e!=null);if(t.type===`sum`){let t=o.reduce((e,t)=>{let n=typeof t==`number`?t:Number(t);return Number.isFinite(n)?e+n:e},0);this.assignAggregate(e,a,t);continue}if(t.type===`avg`){let t=o.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)),n=t.length===0?null:t.reduce((e,t)=>e+t,0)/t.length;this.assignAggregate(e,a,n);continue}if(t.type===`min`){let t=o.length===0?null:o.reduce((e,t)=>t<e?t:e);this.assignAggregate(e,a,t);continue}let s=o.length===0?null:o.reduce((e,t)=>t>e?t:e);this.assignAggregate(e,a,s)}}))}async resolveRelatedCount(e,t,n,r){let i=await this.resolveRelatedResults(e,t,n,r);return Array.isArray(i)?i.length:i?1:0}async resolveRelatedResults(e,t,n,r){let i=e,a=r??`__none__`,o=n.get(i);o||(o=new Map,n.set(i,o));let s=o.get(t);s||(s=new Map,o.set(t,s));let c=s.get(a);if(c)return await c;let l=(async()=>{let n=e[t];if(typeof n!=`function`)throw new y(`Relation [${t}] is not defined on the model.`);let i=n.call(e);if(r&&typeof i.constrain==`function`&&i.constrain(e=>r(e)??e),typeof i.get==`function`){let e=await i.get();return e instanceof K?e.all():e}if(typeof i.getResults==`function`){let e=await i.getResults();return e instanceof K?e.all():e}throw new y(`Relation [${t}] does not support result resolution.`)})();return s.set(a,l),await l}compareCount(e,t,n){return t===`>=`?e>=n:t===`>`?e>n:t===`=`?e===n:t===`!=`?e!==n:t===`<=`?e<=n:e<n}buildAggregateAttributeKey(e){let t=e.relation;if(e.type===`count`)return`${t}Count`;if(e.type===`exists`)return`${t}Exists`;let n=e.column?`${e.column.charAt(0).toUpperCase()}${e.column.slice(1)}`:``;return`${t}${`${e.type.charAt(0).toUpperCase()}${e.type.slice(1)}`}${n}`}assignAggregate(e,t,n){let r=e;if(typeof r.setAttribute==`function`){r.setAttribute(t,n);return}e[t]=n}},Ge=class e{static factoryClass;static client;static delegate;static softDeletes=!1;static deletedAtColumn=`deletedAt`;static globalScopes={};static eventListeners={};casts={};hidden=[];visible=[];appends=[];attributes;constructor(e={}){return this.attributes={},this.fill(e),new Proxy(this,{get:(e,t,n)=>typeof t!=`string`||t in e?Reflect.get(e,t,n):e.getAttribute(t),set:(e,t,n,r)=>typeof t!=`string`||t in e?Reflect.set(e,t,n,r):(e.setAttribute(t,n),!0)})}static setClient(e){this.client=e}static setFactory(e){this.factoryClass=e}static factory(e){let t=this.factoryClass;if(!t)throw new y(`Factory is not configured for model [${this.name}].`);let n=new t;return typeof e==`number`&&n.count(e),n}static addGlobalScope(e,t){this.ensureOwnGlobalScopes(),this.globalScopes[e]=t}static removeGlobalScope(e){this.ensureOwnGlobalScopes(),delete this.globalScopes[e]}static clearGlobalScopes(){this.globalScopes={}}static on(e,t){this.ensureOwnEventListeners(),this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e]?.push(t)}static off(e,t){if(this.ensureOwnEventListeners(),!t){delete this.eventListeners[e];return}this.eventListeners[e]=(this.eventListeners[e]||[]).filter(e=>e!==t)}static clearEventListeners(){this.eventListeners={}}static getDelegate(e){V();let t=e||this.delegate||`${(0,p.str)(this.name).camel().plural()}`,n=[t,`${(0,p.str)(t).camel()}`,`${(0,p.str)(t).singular()}`,`${(0,p.str)(t).camel().singular()}`],r=H(),i=n.map(e=>this.client?.[e]??r?.[e]).find(e=>W(e));if(!i)throw new y(`Database delegate [${t}] is not configured.`);return i}static query(){let e=new We(this.getDelegate(),this),t=this;return t.ensureOwnGlobalScopes(),Object.values(t.globalScopes).forEach(t=>{let n=t(e);n&&n!==e&&(e=n)}),e}static withTrashed(){return this.query().withTrashed()}static onlyTrashed(){return this.query().onlyTrashed()}static scope(e,...t){return this.query().scope(e,...t)}static getSoftDeleteConfig(){return{enabled:this.softDeletes,column:this.deletedAtColumn}}static hydrate(e){return new this(e)}static hydrateMany(e){return e.map(e=>new this(e))}fill(e){return Object.entries(e).forEach(([e,t])=>{this.setAttribute(e,t)}),this}getAttribute(e){let t=this.resolveGetMutator(e),n=this.casts[e],r=this.attributes[e];return n&&(r=v(n).get(r)),t?t.call(this,r):r}setAttribute(e,t){let n=this.resolveSetMutator(e),r=this.casts[e],i=t;return n&&(i=n.call(this,i)),r&&(i=v(r).set(i)),this.attributes[e]=i,this}async save(){let t=this.getAttribute(`id`),n=this.getRawAttributes(),r=this.constructor;if(t==null){await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`creating`,this);let t=await r.query().create(n);return this.fill(t.getRawAttributes()),await e.dispatchEvent(r,`created`,this),await e.dispatchEvent(r,`saved`,this),this}await e.dispatchEvent(r,`saving`,this),await e.dispatchEvent(r,`updating`,this);let i=await r.query().where({id:t}).update(n);return this.fill(i.getRawAttributes()),await e.dispatchEvent(r,`updated`,this),await e.dispatchEvent(r,`saved`,this),this}async delete(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`deleting`,this);let r=n.getSoftDeleteConfig();if(r.enabled){let i=await n.query().where({id:t}).update({[r.column]:new Date});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}let i=await n.query().where({id:t}).delete();return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),this}async forceDelete(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot force delete a model without an id.`);let n=this.constructor;await e.dispatchEvent(n,`forceDeleting`,this),await e.dispatchEvent(n,`deleting`,this);let r=await n.query().withTrashed().where({id:t}).delete();return this.fill(r.getRawAttributes()),await e.dispatchEvent(n,`deleted`,this),await e.dispatchEvent(n,`forceDeleted`,this),this}async restore(){let t=this.getAttribute(`id`);if(t==null)throw new y(`Cannot restore a model without an id.`);let n=this.constructor,r=n.getSoftDeleteConfig();if(!r.enabled)return this;await e.dispatchEvent(n,`restoring`,this);let i=await n.query().withTrashed().where({id:t}).update({[r.column]:null});return this.fill(i.getRawAttributes()),await e.dispatchEvent(n,`restored`,this),this}async load(e){let t=this.normalizeRelationMap(e);return await Promise.all(Object.entries(t).map(async([e,t])=>{let n=this[e];if(typeof n!=`function`)return;let r=n.call(this);t&&r.constrain(t);let i=await r.getResults();this.attributes[e]=i})),this}getRawAttributes(){return{...this.attributes}}toObject(){let e=(this.visible.length>0?this.visible:Object.keys(this.attributes).filter(e=>!this.hidden.includes(e))).reduce((e,t)=>{let n=this.getAttribute(t);return n instanceof Date&&(n=n.toISOString()),e[t]=n,e},{});return this.appends.forEach(t=>{e[t]=this.getAttribute(t)}),e}toJSON(){return this.toObject()}hasOne(e,t,n=`id`){return new ze(this,e,t,n)}hasMany(e,t,n=`id`){return new Le(this,e,t,n)}belongsTo(e,t,n=`id`){return new Ie(this,e,t,n)}belongsToMany(e,t,n,r,i=`id`,a=`id`){return new Fe(this,e,t,n,r,i,a)}hasOneThrough(e,t,n,r,i=`id`,a=`id`){return new Be(this,e,t,n,r,i,a)}hasManyThrough(e,t,n,r,i=`id`,a=`id`){return new Re(this,e,t,n,r,i,a)}morphOne(e,t,n=`id`){return new He(this,e,t,n)}morphMany(e,t,n=`id`){return new Ve(this,e,t,n)}morphToMany(e,t,n,r,i=`id`,a=`id`){return new Ue(this,e,t,n,r,i,a)}resolveGetMutator(e){let t=`get${(0,p.str)(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}resolveSetMutator(e){let t=`set${(0,p.str)(e).studly()}Attribute`,n=this[t];return typeof n==`function`?n:null}static ensureOwnGlobalScopes(){Object.prototype.hasOwnProperty.call(this,`globalScopes`)||(this.globalScopes={...this.globalScopes||{}})}static ensureOwnEventListeners(){Object.prototype.hasOwnProperty.call(this,`eventListeners`)||(this.eventListeners={...this.eventListeners||{}})}static async dispatchEvent(e,t,n){e.ensureOwnEventListeners();let r=e.eventListeners[t]||[];for(let e of r)await e(n)}normalizeRelationMap(e){return typeof e==`string`?{[e]:void 0}:Array.isArray(e)?e.reduce((e,t)=>(e[t]=void 0,e),{}):e}};exports.ArkormCollection=K,exports.ArkormException=y,exports.CliApp=ye,exports.InitCommand=be,exports.InlineFactory=Ae,exports.LengthAwarePaginator=Q,exports.MakeFactoryCommand=xe,exports.MakeMigrationCommand=Se,exports.MakeModelCommand=Ce,exports.MakeSeederCommand=we,exports.MigrateCommand=Te,exports.Migration=G,exports.Model=Ge,exports.ModelFactory=ke,exports.ModelNotFoundException=J,exports.ModelsSyncCommand=Ee,exports.PRISMA_MODEL_REGEX=re,exports.Paginator=$,exports.QueryBuilder=We,exports.SchemaBuilder=Me,exports.SeedCommand=Oe,exports.Seeder=De,exports.TableBuilder=q,exports.URLDriver=Z,exports.applyAlterTableOperation=se,exports.applyCreateTableOperation=w,exports.applyDropTableOperation=T,exports.applyMigrationToPrismaSchema=A,exports.applyOperationsToPrismaSchema=ce,exports.buildFieldLine=S,exports.buildMigrationSource=ue,exports.buildModelBlock=oe,exports.configureArkormRuntime=L,exports.createMigrationTimestamp=O,exports.createPrismaAdapter=Y,exports.createPrismaDelegateMap=Ne,exports.defineConfig=he,exports.defineFactory=je,exports.ensureArkormConfigLoading=V,exports.escapeRegex=x,exports.findModelBlock=C,exports.formatDefaultValue=ae,exports.generateMigrationFile=de,exports.getMigrationPlan=fe,exports.getRuntimePaginationURLDriverFactory=U,exports.getRuntimePrismaClient=H,exports.getUserConfig=I,exports.inferDelegateName=Pe,exports.isDelegateLike=W,exports.loadArkormConfig=B,exports.pad=D,exports.resetArkormRuntimeForTests=ge,exports.resolveCast=v,exports.resolveMigrationClassName=le,exports.resolvePrismaType=ie,exports.runMigrationWithPrisma=pe,exports.runPrismaCommand=E,exports.toMigrationFileSlug=k,exports.toModelName=b;