arkormx 0.1.6 → 0.1.8

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/cli.mjs CHANGED
@@ -1,16 +1,16 @@
1
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{spawnSync as ee}from"node:child_process";import{str as b}from"@h3ravel/support";import{fileURLToPath as x,pathToFileURL as te}from"url";import{Logger as ne}from"@h3ravel/shared";import{Command as S,Kernel as C}from"@h3ravel/musket";import{pathToFileURL as w}from"node:url";var T=class extends Error{constructor(e){super(e),this.name=`ArkormException`}},E=class{},D=class{columns=[];dropColumnNames=[];indexes=[];latestColumnName;id(e=`id`){return this.column(e,`id`,{primary:!0})}uuid(e,t={}){return this.column(e,`uuid`,t)}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}nullable(e){let t=this.resolveColumn(e);return t.nullable=!0,this}before(e,t){let n=this.resolveColumn(t);return n.before=e,this}map(e,t){let n=this.resolveColumn(t);return n.map=e,this}index(e,t){let n=Array.isArray(e)?e:typeof e==`string`?[e]:[this.resolveColumn().name];return this.indexes.push({columns:[...n],name:t}),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}getIndexes(){return this.indexes.map(e=>({...e,columns:[...e.columns]}))}column(e,t,n){return this.columns.push({name:e,type:t,map:n.map,nullable:n.nullable,unique:n.unique,primary:n.primary,before:n.before,default:n.default}),this.latestColumnName=e,this}resolveColumn(e){let t=e??this.latestColumnName;if(!t)throw Error(`No column available for this operation.`);let n=this.columns.find(e=>e.name===t);if(!n)throw Error(`Column [${t}] was not found in the table definition.`);return n}},re=class{operations=[];createTable(e,t){let n=new D;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns(),indexes:n.getIndexes()}),this}alterTable(e,t){let n=new D;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns(),addIndexes:n.getIndexes()}),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})),indexes:e.indexes.map(e=>({...e,columns:[...e.columns]}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns],addIndexes:e.addIndexes.map(e=>({...e,columns:[...e.columns]}))}:{...e})}};const O=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,k=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(``)},A=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ie=e=>e.type===`id`?`Int`:e.type===`uuid`||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`})`}},j=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=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,o=ae(e.default)??(e.type===`uuid`&&e.primary?`@default(uuid())`:void 0),s=o?` ${o}`:``;return` ${e.name} ${t}${n}${i}${r}${s}${a}`},M=e=>` @@index([${e.columns.join(`, `)}]${typeof e.name==`string`&&e.name.trim().length>0?`, name: "${e.name.replace(/"/g,`\\"`)}"`:``})`,oe=e=>{let t=k(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(j),i=[...(e.indexes??[]).map(M),...n?[` @@map("${b(e.table).snake()}")`]:[]];return`model ${t} {\n${(i.length>0?[...r,``,...i]:r).join(`
3
- `)}\n}`},N=(e,t)=>{let n=[...e.matchAll(O)],r=RegExp(`@@map\\("${A(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()===k(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},P=(e,t)=>{if(N(e,t.table))throw new T(`Prisma model for table [${t.table}] already exists.`);let n=oe(t);return`${e.trimEnd()}\n\n${n}\n`},se=(e,t)=>{let n=N(e,t.table);if(!n)throw new T(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
4
- `);return t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${A(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}}),t.addColumns.forEach(e=>{let t=j(e),n=RegExp(`^\\s*${A(e.name)}\\s+`);if(i.some(e=>n.test(e)))return;let r=Math.max(1,i.length-1),a=typeof e.before==`string`&&e.before.length>0?i.findIndex(t=>RegExp(`^\\s*${A(e.before)}\\s+`).test(t)):-1,o=a>0?a:r;i.splice(o,0,t)}),(t.addIndexes??[]).forEach(e=>{let t=M(e);if(i.some(e=>e.trim()===t.trim()))return;let n=Math.max(1,i.length-1);i.splice(n,0,t)}),r=i.join(`
5
- `),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},ce=(e,t)=>{let n=N(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?`
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{spawnSync as ee}from"node:child_process";import{str as b}from"@h3ravel/support";import{fileURLToPath as te,pathToFileURL as ne}from"url";import{Logger as x}from"@h3ravel/shared";import{Command as S,Kernel as C}from"@h3ravel/musket";import{pathToFileURL as w}from"node:url";var T=class extends Error{constructor(e){super(e),this.name=`ArkormException`}},E=class{},D=class{columns=[];dropColumnNames=[];indexes=[];latestColumnName;primary(e,t){let n=typeof e==`string`?{columnName:e,...t??{}}:e??{},r=this.resolveColumn(n.columnName);return r.primary=!0,typeof n.autoIncrement==`boolean`&&(r.autoIncrement=n.autoIncrement),Object.prototype.hasOwnProperty.call(n,`default`)&&(r.default=n.default),this}id(e=`id`,t=`id`){return this.column(e,t,{primary:!0})}uuid(e,t={}){return this.column(e,`uuid`,t)}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}nullable(e){let t=this.resolveColumn(e);return t.nullable=!0,this}after(e,t){let n=this.resolveColumn(t);return n.after=e,this}map(e,t){let n=this.resolveColumn(t);return n.map=e,this}index(e,t){let n=Array.isArray(e)?e:typeof e==`string`?[e]:[this.resolveColumn().name];return this.indexes.push({columns:[...n],name:t}),this}getColumns(){return this.columns.map(e=>({...e}))}getDropColumns(){return[...this.dropColumnNames]}getIndexes(){return this.indexes.map(e=>({...e,columns:[...e.columns]}))}column(e,t,n){return this.columns.push({name:e,type:t,map:n.map,nullable:n.nullable,unique:n.unique,primary:n.primary,autoIncrement:n.autoIncrement,after:n.after,default:n.default}),this.latestColumnName=e,this}resolveColumn(e){let t=e??this.latestColumnName;if(!t)throw Error(`No column available for this operation.`);let n=this.columns.find(e=>e.name===t);if(!n)throw Error(`Column [${t}] was not found in the table definition.`);return n}},re=class{operations=[];createTable(e,t){let n=new D;return t(n),this.operations.push({type:`createTable`,table:e,columns:n.getColumns(),indexes:n.getIndexes()}),this}alterTable(e,t){let n=new D;return t(n),this.operations.push({type:`alterTable`,table:e,addColumns:n.getColumns(),dropColumns:n.getDropColumns(),addIndexes:n.getIndexes()}),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})),indexes:e.indexes.map(e=>({...e,columns:[...e.columns]}))}:e.type===`alterTable`?{...e,addColumns:e.addColumns.map(e=>({...e})),dropColumns:[...e.dropColumns],addIndexes:e.addIndexes.map(e=>({...e,columns:[...e.columns]}))}:{...e})}};const ie=/model\s+(\w+)\s*\{[\s\S]*?\n\}/g,O=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(``)},k=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ae=e=>e.type===`id`?`Int`:e.type===`uuid`||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`,A=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`){let t=e.primary===!1?``:` @id`,n=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,r=A(e.default),i=e.autoIncrement??e.primary!==!1,a=r?` ${r}`:i&&t?` @default(autoincrement())`:``;return` ${e.name} Int${t}${a}${n}`}let t=ae(e),n=e.nullable?`?`:``,r=e.unique?` @unique`:``,i=e.primary?` @id`:``,a=typeof e.map==`string`&&e.map.trim().length>0?` @map("${e.map.replace(/"/g,`\\"`)}")`:``,o=A(e.default)??(e.type===`uuid`&&e.primary?`@default(uuid())`:void 0),s=o?` ${o}`:``;return` ${e.name} ${t}${n}${i}${r}${s}${a}`},M=e=>` @@index([${e.columns.join(`, `)}]${typeof e.name==`string`&&e.name.trim().length>0?`, name: "${e.name.replace(/"/g,`\\"`)}"`:``})`,N=e=>{let t=O(e.table),n=e.table!==t.toLowerCase(),r=e.columns.map(j),i=[...(e.indexes??[]).map(M),...n?[` @@map("${b(e.table).snake()}")`]:[]];return`model ${t} {\n${(i.length>0?[...r,``,...i]:r).join(`
3
+ `)}\n}`},P=(e,t)=>{let n=[...e.matchAll(ie)],r=RegExp(`@@map\\("${k(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()===O(t).toLowerCase())return{modelName:i,block:n,start:a,end:o}}return null},F=(e,t)=>{if(P(e,t.table))throw new T(`Prisma model for table [${t.table}] already exists.`);let n=N(t);return`${e.trimEnd()}\n\n${n}\n`},oe=(e,t)=>{let n=P(e,t.table);if(!n)throw new T(`Prisma model for table [${t.table}] was not found.`);let r=n.block,i=r.split(`
4
+ `);return t.dropColumns.forEach(e=>{let t=RegExp(`^\\s*${k(e)}\\s+`);for(let e=0;e<i.length;e+=1)if(t.test(i[e])){i.splice(e,1);return}}),t.addColumns.forEach(e=>{let t=j(e),n=RegExp(`^\\s*${k(e.name)}\\s+`);if(i.some(e=>n.test(e)))return;let r=Math.max(1,i.length-1),a=typeof e.after==`string`&&e.after.length>0?i.findIndex(t=>RegExp(`^\\s*${k(e.after)}\\s+`).test(t)):-1,o=a>0?Math.min(a+1,r):r;i.splice(o,0,t)}),(t.addIndexes??[]).forEach(e=>{let t=M(e);if(i.some(e=>e.trim()===t.trim()))return;let n=Math.max(1,i.length-1);i.splice(n,0,t)}),r=i.join(`
5
+ `),`${e.slice(0,n.start)}${r}${e.slice(n.end)}`},se=(e,t)=>{let n=P(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?`
6
6
 
7
- `:``}${i}`},F=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?P(e,t):t.type===`alterTable`?se(e,t):ce(e,t),e),I=(e,t)=>{let n=ee(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
7
+ `:``}${i}`},ce=(e,t)=>t.reduce((e,t)=>t.type===`createTable`?F(e,t):t.type===`alterTable`?oe(e,t):se(e,t),e),I=(e,t)=>{let n=ee(`npx`,[`prisma`,...e],{cwd:t,encoding:`utf-8`});if(n.status===0)return;let r=[n.stdout,n.stderr].filter(Boolean).join(`
8
8
  `).trim();throw new T(r?`Prisma command failed: prisma ${e.join(` `)}\n${r}`:`Prisma command failed: prisma ${e.join(` `)}`)},L=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`},R=e=>String(e).padStart(2,`0`),z=(e=new Date)=>`${e.getFullYear()}${R(e.getMonth()+1)}${R(e.getDate())}${R(e.getHours())}${R(e.getMinutes())}${R(e.getSeconds())}`,B=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``)||`migration`,V=(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(`
9
9
  `):[`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(`
10
- `),H=(e,t={})=>{let n=z(new Date),r=B(e),i=L(e),a=t.extension??`ts`,o=t.directory??v(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=v(o,s),l=V(i,a);if(t.write??!0){if(p(o)||m(o,{recursive:!0}),p(c))throw new T(`Migration file already exists: ${c}`);_(c,l)}return{fileName:s,filePath:c,className:i,content:l}},U=async(e,t=`up`)=>{let n=e instanceof E?e:new e,r=new re;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},W=async(e,t={})=>{let n=t.schemaPath??v(process.cwd(),`prisma`,`schema.prisma`);if(!p(n))throw new T(`Prisma schema file not found: ${n}`);let r=h(n,`utf-8`),i=await U(e,`up`),a=F(r,i);return(t.write??!0)&&_(n,a),{schema:a,schemaPath:n,operations:i}},G=()=>{let e=s.dirname(x(import.meta.url));for(;;){let n=s.join(e,`package.json`),r=s.join(e,`stubs`);if(t(n)&&t(r))return r;let i=s.dirname(e);if(i===e)break;e=i}return s.join(process.cwd(),`stubs`)},K={paths:{stubs:G(),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`},q={...K,paths:{...K.paths??{}}};let J=!1,Y;const le=e=>{let t=K.paths??{},n=q.paths??{},r=Object.entries(e??{}).reduce((e,[t,n])=>(typeof n==`string`&&n.trim().length>0&&(e[t]=n),e),{});return{...t,...n,...r}},X=e=>e?q[e]:q,ue=(e,t={})=>{let n={...q,prisma:e,paths:le(t.paths)};t.pagination!==void 0&&(n.pagination=t.pagination),t.outputExt!==void 0&&(n.outputExt=t.outputExt),Object.assign(q,{...n}),n.pagination?.urlDriver},Z=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(ue(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),J=!0)},de=e=>import(`${te(e).href}?arkorm_runtime=${Date.now()}`),fe=()=>{let e=f(import.meta.url),n=[s.join(process.cwd(),`arkormx.config.cjs`)];for(let r of n)if(t(r))try{return Z(e(r)),!0}catch{continue}return!1},pe=async()=>{if(!J){if(Y)return await Y;fe()||(Y=(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{Z(await de(n));return}catch{continue}J=!0})(),await Y)}},Q=()=>G();pe();var $=class{command;config={};constructor(){this.config=X()}getConfig=X;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,ne.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`,Q()),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=H(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=N(a,n),c=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(a);return s||c?{path:i,updated:!1}:(o(i,P(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(`
10
+ `),H=(e,t={})=>{let n=z(new Date),r=B(e),i=L(e),a=t.extension??`ts`,o=t.directory??v(process.cwd(),`database`,`migrations`),s=`${n}_${r}.${a}`,c=v(o,s),l=V(i,a);if(t.write??!0){if(p(o)||m(o,{recursive:!0}),p(c))throw new T(`Migration file already exists: ${c}`);_(c,l)}return{fileName:s,filePath:c,className:i,content:l}},U=async(e,t=`up`)=>{let n=e instanceof E?e:new e,r=new re;return t===`up`?await n.up(r):await n.down(r),r.getOperations()},W=async(e,t={})=>{let n=t.schemaPath??v(process.cwd(),`prisma`,`schema.prisma`);if(!p(n))throw new T(`Prisma schema file not found: ${n}`);let r=h(n,`utf-8`),i=await U(e,`up`),a=ce(r,i);return(t.write??!0)&&_(n,a),{schema:a,schemaPath:n,operations:i}},G=()=>{let e=s.dirname(te(import.meta.url));for(;;){let n=s.join(e,`package.json`),r=s.join(e,`stubs`);if(t(n)&&t(r))return r;let i=s.dirname(e);if(i===e)break;e=i}return s.join(process.cwd(),`stubs`)},K={paths:{stubs:G(),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`},q={...K,paths:{...K.paths??{}}};let J=!1,Y;const le=e=>{let t=K.paths??{},n=q.paths??{},r=Object.entries(e??{}).reduce((e,[t,n])=>(typeof n==`string`&&n.trim().length>0&&(e[t]=n),e),{});return{...t,...n,...r}},X=e=>e?q[e]:q,ue=(e,t={})=>{let n={...q,prisma:e,paths:le(t.paths)};t.pagination!==void 0&&(n.pagination=t.pagination),t.outputExt!==void 0&&(n.outputExt=t.outputExt),Object.assign(q,{...n}),n.pagination?.urlDriver},Z=e=>{let t=e?.default??e;!t||typeof t!=`object`||!t.prisma||(ue(t.prisma,{pagination:t.pagination,paths:t.paths,outputExt:t.outputExt}),J=!0)},de=e=>import(`${ne(e).href}?arkorm_runtime=${Date.now()}`),fe=()=>{let e=f(import.meta.url),n=[s.join(process.cwd(),`arkormx.config.cjs`)];for(let r of n)if(t(r))try{return Z(e(r)),!0}catch{continue}return!1},pe=async()=>{if(!J){if(Y)return await Y;fe()||(Y=(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{Z(await de(n));return}catch{continue}J=!0})(),await Y)}},Q=()=>G();pe();var me=class{command;config={};constructor(){this.config=X()}getConfig=X;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,x.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`,Q()),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=H(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=P(a,n),c=RegExp(`model\\s+${e}\\s*\\{`,`m`).test(a);return s||c?{path:i,updated:!1}:(o(i,F(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(`
11
11
  `).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(`
12
12
  `),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(`
13
- `);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}}},me=class extends S{signature=`init
13
+ `);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}}},$=class extends S{signature=`init
14
14
  {--force : Force overwrite if config file already exists (existing file will be backed up) }
15
15
  `;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}=X(`paths`)??{},a=typeof i==`string`&&i.trim().length>0?i:Q(),s=v(a,`arkormx.config.stub`),c=v(a,`arkorm.config.stub`),l=t(s)?s:c;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`)),t(l)||(this.error(`Error: Missing config stub at ${s} (or ${c})`),process.exit(1)),o(n,r(l,`utf-8`)),this.success(`Arkormˣ initialized successfully!`)}},he=class extends S{signature=`make:factory
16
16
  {name : Name of the factory to create}
@@ -48,4 +48,4 @@ import{copyFileSync as e,existsSync as t,mkdirSync as n,readFileSync as r,readdi
48
48
  ███ ███ ████▄ ██ ▄█▀ ▄███▄ ████▄ ███▄███▄
49
49
  ███▀▀███ ██ ▀▀ ████ ██ ██ ██ ▀▀ ██ ██ ██
50
50
  ███ ███ ██ ██ ▀█▄ ▀███▀ ██ ██ ██ ██
51
- `;const we=new $;await C.init(we,{logo:Ce,name:`Arkormˣ CLI`,baseCommands:[me,_e,he,ve,ge,be,Se,ye],exceptionHandler(e){throw e}});export{};
51
+ `;const we=new me;await C.init(we,{logo:Ce,name:`Arkormˣ CLI`,baseCommands:[$,_e,he,ve,ge,be,Se,ye],exceptionHandler(e){throw e}});export{};