@h3ravel/arquebus 0.3.0 → 0.3.2

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.
Files changed (34) hide show
  1. package/README.md +1 -1
  2. package/bin/index.cjs +4419 -1
  3. package/bin/index.d.cts +1 -1
  4. package/bin/index.d.ts +1 -1
  5. package/bin/index.js +4384 -1
  6. package/dist/browser/index.cjs +1269 -1
  7. package/dist/browser/index.d.cts +1222 -1202
  8. package/dist/browser/index.d.ts +1222 -1202
  9. package/dist/browser/index.js +1217 -1
  10. package/dist/index.cjs +4181 -1
  11. package/dist/index.d.cts +1306 -1280
  12. package/dist/index.d.ts +1306 -1280
  13. package/dist/index.js +4116 -1
  14. package/dist/migrations/chunk-PECeCxCb.js +15 -0
  15. package/dist/migrations/index.cjs +4064 -1
  16. package/dist/migrations/index.d.cts +1250 -1243
  17. package/dist/migrations/index.d.ts +1247 -1243
  18. package/dist/migrations/index.js +3994 -1
  19. package/package.json +3 -3
  20. package/bin/cli.cjs +0 -4942
  21. package/bin/cli.d.cts +0 -18
  22. package/bin/cli.d.ts +0 -18
  23. package/bin/cli.js +0 -4907
  24. package/bin/utils.js +0 -141
  25. /package/{bin → dist}/migrations/stubs/migration-js.stub +0 -0
  26. /package/{bin → dist}/migrations/stubs/migration-ts.stub +0 -0
  27. /package/{bin → dist}/migrations/stubs/migration.create-js.stub +0 -0
  28. /package/{bin → dist}/migrations/stubs/migration.create-ts.stub +0 -0
  29. /package/{bin → dist}/migrations/stubs/migration.update-js.stub +0 -0
  30. /package/{bin → dist}/migrations/stubs/migration.update-ts.stub +0 -0
  31. /package/{bin → dist}/stubs/arquebus.config-js.stub +0 -0
  32. /package/{bin → dist}/stubs/arquebus.config-ts.stub +0 -0
  33. /package/{bin → dist}/stubs/model-js.stub +0 -0
  34. /package/{bin → dist}/stubs/model-ts.stub +0 -0
package/bin/index.js CHANGED
@@ -1,2 +1,4385 @@
1
1
  #!/usr/bin/env node
2
- import{program as t,Argument as e,Option as s}from"commander";import i,{mkdir as r,readFile as n,writeFile as a,access as o}from"fs/promises";import h from"chalk";import c from"escalade/sync";import u,{dirname as l}from"path";import g from"resolve-from";import{omit as d,isEqual as y,trim as m,assign as p,diff as f,isArray as w,pick as b,isEmpty as C,flat as v,set as P,get as K,camel as N,snake as R,isString as A}from"radashi";import x from"dayjs/plugin/advancedFormat.js";import T from"dayjs";import S from"knex";import D,{collect as q,Collection as E}from"collect.js";import M from"pluralize";import{existsSync as k,readFileSync as _}from"fs";import{fileURLToPath as F}from"url";import{config as I}from"dotenv";var O=Object.defineProperty,Q=u.join,j=class{static textFormat(t,e){return String(t).split(":").map((t,s,i)=>0==s&&i.length>1?e(" "+t+": "):t).join("")}static output(){return{success:(t,e=!1)=>{console.log(h.green("✓"),this.textFormat(t,h.bgGreen),"\n"),e&&process.exit(0)},info:(t,e=!1)=>{console.log(h.blue("ℹ"),this.textFormat(t,h.bgBlue),"\n"),e&&process.exit(0)},error:(t,e=!0)=>{t instanceof Error?(t.message&&console.error(h.red("✖"),this.textFormat(t.message,h.bgRed)),console.error(h.red(`${t.detail?`${t.detail}\n`:""}${t.stack}`),"\n")):console.error(h.red("✖"),this.textFormat(t,h.bgRed),"\n"),e&&process.exit(1)},quiet:()=>{process.exit(0)}}}static findModulePkg(t,e){const s=t.replace(/\\/g,"/").split("/");let i="";s.length>0&&"@"===s[0][0]&&(i+=s.shift()+"/"),i+=s.shift();const r=u.join(i,"package.json"),n=g.silent(e??process.cwd(),r);if(n)return u.join(u.dirname(n),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[Q(t,i)]:[...e.getPaths(),Q(t,s)]}static twoColumnDetail(t,e){const s=/\x1b\[\d+m/g,i=Math.min(process.stdout.columns,100),r=Math.max(i-t.replace(s,"").length-e.replace(s,"").length-10,0);return console.log(t,h.gray(".".repeat(r)),e)}static async fileExists(t){try{return await o(t),!0}catch{return!1}}static findUpConfig(t,e,s){return c(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},W=class t{static CREATE_PATTERNS=[/^create_(\w+)_table$/,/^create_(\w+)$/];static CHANGE_PATTERNS=[/.+_(to|from|in)_(\w+)_table$/,/.+_(to|from|in)_(\w+)$/];static guess(e){for(const s of t.CREATE_PATTERNS){const t=e.match(s);if(t)return[t[1],!0]}for(const s of t.CHANGE_PATTERNS){const t=e.match(s);if(t)return[t[2],!1]}return[]}},$=class{resolver;table;connection=null;constructor(t,e){this.resolver=t,this.table=e}async getRan(){return await this.getTable().orderBy("batch","asc").orderBy("migration","asc").pluck("migration")}async getMigrations(t){const e=this.getTable().where("batch",">=","1");return await e.orderBy("batch","desc").orderBy("migration","desc").take(t).get()}async getMigrationsByBatch(t){return await this.getTable().where("batch",t).orderBy("migration","desc").get()}async getLast(){const t=this.getTable().where("batch",await this.getLastBatchNumber());return await t.orderBy("migration","desc").get()}async getMigrationBatches(){const t=await this.getTable().select("batch","migration").orderBy("batch","asc").orderBy("migration","asc").get(),e={};return t.map(t=>{e[t.migration]=t.batch}),e}async log(t,e){await this.getTable().insert({migration:t,batch:e})}async delete(t){await this.getTable().where("migration",t.migration).delete()}async getNextBatchNumber(){return await this.getLastBatchNumber()+1}async getLastBatchNumber(){return await this.getTable().max("batch")}async createRepository(){const t=this.getConnection().schema;await t.createTable(this.table,function(t){t.increments("id"),t.string("migration"),t.integer("batch")})}repositoryExists(){return this.getConnection().schema.hasTable(this.table)}async deleteRepository(){const t=this.getConnection().schema;await t.drop(this.table)}getTable(){return this.getConnection().table(this.table)}getConnection(){return this.resolver.connection(this.connection)}setSource(t){this.connection=t}};async function B(t){const e=await i.readdir(t),s=[];for(const r of e){const e=`${t}/${r}`,n=await i.stat(e);if(n.isFile())s.push(e);else if(n.isDirectory()){const t=await B(e);s.push(...t)}}return s}var L=class{events=null;repository;files;resolver;connection;paths=[];output=null;constructor(t,e=null,s=null,i=null){this.repository=t,this.files=s,this.resolver=e,this.events=i}async run(t=[],e={}){const s=await this.getMigrationFiles(t),i=await this.repository.getRan(),r=this.pendingMigrations(s,i);return await this.runPending(r,e),r}pendingMigrations(t,e){return Object.values(t).filter(t=>!e.includes(this.getMigrationName(t)))}async runPending(t,e={}){if(0===t.length)return void this.write("Nothing to migrate");let s=await this.repository.getNextBatchNumber();const i=e.pretend||!1,r=e.step||!1;this.write("Running migrations.");for(const e of t)await this.runUp(e,s,i),r&&s++}async runUp(t,e,s){const i=await this.resolvePath(t),r=this.getMigrationName(t);await this.writeTask(r,()=>this.runMigration(i,"up")),await this.repository.log(r,e)}async runDown(t,e,s){const i=await this.resolvePath(t),r=this.getMigrationName(t);await this.writeTask(r,()=>this.runMigration(i,"down")),await this.repository.delete(e)}async rollback(t=[],e={}){const s=await this.getMigrationsForRollback(e);return 0===s.length?(this.write("Nothing to rollback."),[]):await this.rollbackMigrations(s,t,e)}async getMigrationsForRollback(t){return t.step&&t.step>0?await this.repository.getMigrations(t.step):t.batch&&t.batch>0?await this.repository.getMigrationsByBatch(t.batch):await this.repository.getLast()}async rollbackMigrations(t,e,s){const i=[],r=await this.getMigrationFiles(e);this.write("Rolling back migrations.");for(const e of t){const t=r[e.migration];t?(i.push(t),await this.runDown(t,e,s.pretend||!1)):this.writeTwoColumns(e.migration,h.yellow("Migration not found"))}return i}reset(t=[],e=!1){return this.repository.getRan().then(t=>t.reverse()),[]}resetMigrations(t,e,s=!1){return this.rollbackMigrations(t,e,{pretend:s})}async runMigration(t,e){const s=this.resolveConnection(t.getConnection()),i=async s=>{"function"==typeof t[e]&&await this.runMethod(s,t,e)};t.withinTransaction?await s.transaction(i):await i(s)}async runMethod(t,e,s){await(e[s]?.(t.schema,t))}async resolvePath(t){try{return new((await import(t)).default)}catch{}return new class{}}getMigrationClass(t){return t.split("_").slice(4).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}async getMigrationFiles(t){const e=[];for(const s of t)s.endsWith(".js")||s.endsWith(".ts")?e.push(s):e.push(...await B(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return u.basename(t).replace(".js","")}path(t){this.paths=Array.from(new Set([...this.paths,t]))}getPaths(){return this.paths}getConnection(){return this.connection}resolveConnection(t){return this.resolver.connection(t||this.connection)}getRepository(){return this.repository}repositoryExists(){return this.repository.repositoryExists()}async hasRunAnyMigrations(){const t=await this.repository.getRan();return await this.repositoryExists()&&t.length>0}deleteRepository(){this.repository.deleteRepository()}setOutput(t){return this.output=t,this}write(...t){this.output&&console.log(...t)}writeTwoColumns(t,...e){const s=e.join(" "),i=/\x1b\[\d+m/g,r=Math.min(process.stdout.columns,100),n=Math.max(r-t.replace(i,"").length-s.replace(i,"").length-10,0);this.write(t,h.gray(".".repeat(n)),s)}async writeTask(t,e){const s=process.hrtime();let i=!1;try{i=await(e||(()=>!0))()}finally{const e=process.hrtime(s),r=(1e9*e[0]+e[1])/1e6;this.writeTwoColumns(h.green(t),h.gray(`${Math.floor(r)}ms`),!1!==i?h.green("✔"):h.red("✘"))}}},H={};function U(t,...e){return e.reduce((t,e)=>"function"==typeof e&&e.prototype?class extends t{constructor(...t){super(...t),Object.getOwnPropertyNames(e.prototype).forEach(t=>{"constructor"!==t&&Object.defineProperty(this,t,Object.getOwnPropertyDescriptor(e.prototype,t))})}}:"function"==typeof e?e(t):t,t)}((t,e)=>{for(var s in e)O(t,s,{get:e[s],enumerable:!0})})(H,{compose:()=>U}),T.extend(x);var J=t=>N(`relation_${t}`),z=t=>N(`scope_${t}`),G=t=>N(`attribute_${t}`),V=t=>N(`get_${t}_attribute`),Y=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:Z}=H,X=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat(X(e)),[]):[t],tt=t=>m(R(t.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),et=class t{get;set;withCaching=!1;withObjectCaching=!0;constructor({get:t=null,set:e=null}){this.get=t,this.set=e}static make({get:e=null,set:s=null}){return new t({get:e,set:s})}static get(e){return new t({get:e})}static set(e){return new t({set:e})}withoutObjectCaching(){return this.withObjectCaching=!1,this}shouldCache(){return this.withCaching=!0,this}},st=class{query;parent;related;eagerKeysWereEmpty=!1;static constraints=!0;static selfJoinCount=0;constructor(t,e){this.query=t,this.parent=e,this.related=this.query.model}static extend(t){for(const e in t)this.prototype[e]=t[e]}static noConstraints(t){const e=this.constraints;this.constraints=!1;try{return t()}finally{this.constraints=e}}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:"string"==typeof e&&"function"==typeof t.query[e]?(...s)=>(t.query[e](...s),t.asProxy()):void 0}})}getRelated(){return this.related}getKeys(t,e){return t.map(t=>e?t.attributes[e]:t.getKey()).sort()}getRelationQuery(){return this.query}whereInEager(t,e,s,i=null){(i||this.query)[t](e,s),0===s.length&&(this.eagerKeysWereEmpty=!0)}whereInMethod(t,e){return"whereIn"}getEager(){return this.eagerKeysWereEmpty?this.query.getModel().newCollection():this.get()}async get(t=["*"]){return await this.query.get(t)}async first(t=["*"]){return await this.query.first(t)}async paginate(...t){return await this.query.paginate(...t)}async count(...t){return await this.query.clearSelect().count(...t)}toSql(){return this.query.toSql()}addConstraints(){}getRelationCountHash(t=!0){return"arquebus_reserved_"+(t?this.constructor.selfJoinCount++:this.constructor.selfJoinCount)}getRelationExistenceQuery(t,e,s=["*"]){return t.select(s).whereColumn(this.getQualifiedParentKeyName(),"=",this.getExistenceCompareKey())}getRelationExistenceCountQuery(t,e){const s=this.related.getConnection();return this.getRelationExistenceQuery(t,e,s.raw("count(*)"))}getQualifiedParentKeyName(){return this.parent.getQualifiedKeyName()}getExistenceCompareKey(){return this.getQualifiedForeignKeyName?.()}},it=t=>class extends t{_withDefault;withDefault(t=!0){return this._withDefault=t,this}getDefaultFor(t){if(!this._withDefault)return null;const e=this.newRelatedInstanceFor(t);if("function"==typeof this._withDefault)return this._withDefault(e,t)||e;if("object"==typeof this._withDefault)for(const t in this._withDefault)e.setAttribute(t,this._withDefault[t]);return e}},rt=class extends(Z(st,it)){foreignKey;ownerKey;child;relationName;constructor(t,e,s,i,r){return super(t,e),this.foreignKey=s,this.ownerKey=i,this.child=e,this.relationName=r,this.addConstraints(),this.asProxy()}async getResults(){if(null===this.child[this.foreignKey])return this.getDefaultFor(this.parent);return await this.query.first()||this.getDefaultFor(this.parent)}match(t,e,s){const i=this.foreignKey,r=this.ownerKey,n={};return e.map(t=>{const e=t.attributes[r];n[e]=t}),t.map(t=>{const e=t[i];void 0!==n[e]&&t.setRelation(s,n[e])}),t}getQualifiedForeignKeyName(){return this.child.qualifyColumn(this.foreignKey)}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery()._single.table===t.getQuery()._single.table?this.getRelationExistenceQueryForSelfRelation(t,e,s):t.select(s).whereColumn(this.getQualifiedForeignKeyName(),"=",t.qualifyColumn(this.ownerKey))}getRelationExistenceQueryForSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash();return t.select(s).from(t.getModel().getTable()+" as "+i),t.getModel().setTable(i),t.whereColumn(`${i}.${this.ownerKey}`,"=",this.getQualifiedForeignKeyName())}initRelation(t,e){return t.forEach(t=>{t.setRelation(e,this.getDefaultFor(t))}),t}addEagerConstraints(t){const e=`${this.related.getTable()}.${this.ownerKey}`;this.query.whereIn(e,this.getEagerModelKeys(t))}getEagerModelKeys(t){const e=[];return t.forEach(t=>{const s=t[this.foreignKey];null!=s&&e.push(s)}),e.sort(),[...new Set(e)]}associate(t){const e=t instanceof qt?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof qt?this.child.setRelation(this.relationName,t):this.child.unsetRelation(this.relationName),this.child}dissociate(){return this.child[this.foreignKey]=null,this.child.setRelation(this.relationName,null)}addConstraints(){if(this.constructor.constraints){const t=this.related.getTable();this.query.where(`${t}.${this.ownerKey}`,"=",this.child[this.foreignKey])}}newRelatedInstanceFor(t){return this.related.newInstance()}},nt=class t extends E{newConstructor(...t){return new(this.getConstructor())(...t)}getConstructor(){return this.constructor}async load(...t){if(this.isNotEmpty()){const e=this.first().constructor.query().with(...t),s=await e.eagerLoadRelations(this.items);return this.newConstructor(s)}return this}async loadAggregate(t,e,s=null){if(this.isEmpty())return this;const i=(await this.first().newModelQuery().whereIn(this.first().getKeyName(),this.modelKeys()).select(this.first().getKeyName()).withAggregate(t,e,s).get()).keyBy(this.first().getKeyName()),r=f(Object.keys(i.first().getAttributes()),[i.first().getKeyName()]);return this.each(t=>{const e=b(i.get(t.getKey()).getAttributes(),r);t.fill(e).syncOriginalAttributes(...r)}),this}loadCount(t){return this.loadAggregate(t,"*","count")}loadMax(t,e){return this.loadAggregate(t,e,"max")}loadMin(t,e){return this.loadAggregate(t,e,"min")}loadSum(t,e){return this.loadAggregate(t,e,"sum")}loadAvg(t,e){return this.loadAggregate(t,e,"avg")}mapThen(t){return Promise.all(this.map(t))}modelKeys(){return this.all().map(t=>t.getKey())}contains(t,e,s){return arguments.length>1?super.contains(t,s??e):t instanceof Mt?super.contains(e=>e.is(t)):super.contains(e=>e.getKey()==t)}diff(t){const e=new this.constructor,s=this.getDictionary(t);return this.items.map(t=>{void 0===s[t.getKey()]&&e.add(t)}),e}except(t){const e=d(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(C(t))return e;const s=this.getDictionary(t);for(const t of this.items)void 0!==s[t.getKey()]&&e.add(t);return e}unique(t,e=!1){return t?super.unique(t):new this.constructor(Object.values(this.getDictionary()))}find(t,e=null){return t instanceof Mt&&(t=t.getKey()),w(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(q(this.items).first(e=>e.getKey()==t),this.items.filter(e=>e.getKey()==t)[0]||e)}async fresh(...t){if(this.isEmpty())return new this.constructor;const e=this.first(),s=(await e.newQuery().with(...t).whereIn(e.getKeyName(),this.modelKeys()).get()).getDictionary();return this.filter(t=>t.exists&&void 0!==s[t.getKey()]).map(t=>s[t.getKey()])}makeVisible(t){return this.each(e=>{e.makeVisible(t)})}makeHidden(t){return this.each(e=>{e.makeHidden(t)})}append(t){return this.each(e=>{e.append(t)})}only(e){if(null===e)return new t(this.items);const s=b(this.getDictionary(),e);return new this.constructor(Object.values(s))}getDictionary(t){t=t||this.items;const e={};return t.map(t=>{e[t.getKey()]=t}),e}toQuery(){const t=this.first();if(!t)throw new Error("Unable to create query for empty collection.");const e=t.constructor.name;if(this.filter(t=>!(t instanceof e)).isNotEmpty())throw new Error("Unable to create query for collection with mixed types.");return t.newModelQuery().whereKey(this.modelKeys())}toData(){return this.all().map(t=>"function"==typeof t.toData?t.toData():t)}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}[Symbol.iterator]=()=>{const t=this.items,e=this.items.length;let s=0;return{next:()=>s<e?{value:t[s++],done:!1}:{done:!0}}}},at=t=>class extends t{newExistingPivot(t=[]){return this.newPivot(t,!0)}newPivot(t=[],e=!1){return this.related.newPivot(this.parent,t,this.getTable(),e,this.using).setPivotKeys(this.foreignPivotKey,this.relatedPivotKey)}async attach(t,e={},s=!0){this.using?await this.attachUsingCustomClass(t,e):await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(t),e))}async detach(t,e=!0){let s;if(this.using&&null!==t&&0==this.pivotWheres.length&&0==this.pivotWhereIns.length&&0==this.pivotWhereNulls.length)s=await this.detachUsingCustomClass(t);else{const e=this.newPivotQuery();if(null!==t){if(0==(t=this.parseIds(t)).length)return 0;e.whereIn(this.getQualifiedRelatedPivotKeyName(),t)}s=await e.delete()}return s}async sync(t,e=!0){let s,i={attached:[],detached:[],updated:[]};const r=await this.getCurrentlyAttachedPivots(),n=0===r.length?[]:r.map(t=>t.toData()).pluck(this.relatedPivotKey).all().map(t=>String(t)),a=f(n,Object.keys(s=this.formatRecordsList(this.parseIds(t))));return e&&a.length>0&&(await this.detach(a),i.detached=this.castKeys(a)),i=p(i,await this.attachNew(s,n,!1)),i}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(q(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(w(t)?t:Array.prototype.slice.call(t)),this}async attachNew(t,e,s=!0){const i={attached:[],updated:[]};for(const r in t){const n=t[r];e.includes(r)?Object.keys(n).length>0&&await this.updateExistingPivot(r,n,s)&&i.updated.push(this.castKey(r)):(await this.attach(r,n,s),i.attached.push(this.castKey(r)))}return i}async updateExistingPivot(t,e,s=!0){if(this.using&&this.pivotWheres.length>0&&this.pivotWhereInspivotWheres.length>0&&this.pivotWhereNullspivotWheres.length>0)return await this.updateExistingPivotUsingCustomClass(t,e,s);this.hasPivotColumn(this.updatedAt())&&(e=this.addTimestampsToAttachment(e,!0));return this.newPivotStatementForId(this.parseId(t)).update(this.castAttributes(e))}addTimestampsToAttachment(t,e=!1){let s=this.parent.freshTimestamp();if(this.using){s=(new this.using).fromDateTime(s)}return!e&&this.hasPivotColumn(this.createdAt())&&(t[this.createdAt()]=s),this.hasPivotColumn(this.updatedAt())&&(t[this.updatedAt()]=s),t}async updateExistingPivotUsingCustomClass(t,e,s){const i=await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey,this.parent[this.parentKey]).where(this.relatedPivotKey,this.parseId(t)).first(),r=!!i&&i.fill(e).isDirty();return r&&await i.save(),parseInt(r)}formatRecordsList(t){return q(t).mapWithKeys((t,e)=>(w(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||Et).fromRawAttributes(this.parent,t,this.getTable(),!0).setPivotKeys(this.foreignPivotKey,this.relatedPivotKey))}castKeys(t){return t.map(t=>this.castKey(t))}castKey(t){return this.getTypeSwapValue(this.related.getKeyType(),t)}getTypeSwapValue(t,e){switch(t.toLowerCase()){case"int":case"integer":return parseInt(e);case"real":case"float":case"double":return parseFloat(e);case"string":return String(e);default:return e}}newPivotQuery(){const t=this.newPivotStatement();return this.pivotWheres.map(e=>{t.where(...e)}),this.pivotWhereIns.map(e=>{t.whereIn(...e)}),this.pivotWhereNulls.map(e=>{t.whereNull(...e)}),t.where(this.getQualifiedForeignPivotKeyName(),this.parent[this.parentKey])}async detachUsingCustomClass(t){let e=0;for(const s in this.parseIds(t))e+=await this.newPivot({[this.foreignPivotKey]:this.parent[this.parentKey],[this.relatedPivotKey]:s},!0).delete();return e}newPivotStatement(){const t=this.parent.newQuery();return t.setTable(this.table),t}async attachUsingCustomClass(t,e){const s=this.formatAttachRecords(this.parseIds(t),e);await Promise.all(s.map(async t=>{await this.newPivot(t,!1).save()}))}formatAttachRecords(t,e){const s=[],i=this.hasPivotColumn(this.createdAt())||this.hasPivotColumn(this.updatedAt());for(const r in t){const n=t[r];s.push(this.formatAttachRecord(r,n,e,i))}return s}formatAttachRecord(t,e,s,i){const[r,n]=this.extractAttachIdAndAttributes(t,e,s);return p(this.baseAttachRecord(r,i),n)}baseAttachRecord(t,e){let s={};return s[this.relatedPivotKey]=t,s[this.foreignPivotKey]=this.parent[this.parentKey],e&&(s=this.addTimestampsToAttachment(s)),this.pivotValues.map(t=>{s[t.column]=t.value}),s}extractAttachIdAndAttributes(t,e,s){return w(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof qt?[t[this.relatedKey]]:t instanceof nt?t.pluck(this.relatedKey).all():w(t)?t:[t]}},ot=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},ht=class extends ot{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=w(e)?e:[e],this.message=`No query results for model [${t}]`,this.ids.length>0?this.message+=" "+this.ids.join(", "):this.message+=".",this}getModel(){return this.model}getIds(){return this.ids}},ct=class extends ot{},ut=class extends ot{},lt=class extends(Z(st,at)){table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;pivotColumns=[];pivotValues=[];pivotWheres=[];pivotWhereIns=[];pivotWhereNulls=[];accessor="pivot";using;pivotCreatedAt;pivotUpdatedAt;constructor(t,e,s,i,r,n,a){return super(t,e),this.table=s,this.foreignPivotKey=i,this.relatedPivotKey=r,this.parentKey=n,this.relatedKey=a,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,new nt([]))}),t}addConstraints(){this.performJoin(),this.constructor.constraints&&this.addWhereConstraints()}performJoin(t=null){return(t=t||this.query).join(this.getTable(),this.getQualifiedRelatedKeyName(),"=",this.qualifyPivotColumn(this.relatedPivotKey)),this}getTable(){return this.table}getQualifiedRelatedKeyName(){return this.related.qualifyColumn(this.relatedKey)}async getResults(){return null!==this.parent[this.parentKey]?await this.get():new nt([])}addWhereConstraints(){return this.query.where(this.getQualifiedForeignPivotKeyName(),"=",this.parent[this.parentKey]),this}async get(t){const e=this.query.applyScopes();t=e.query?._statements?.find(t=>"columns"==t.grouping)?[]:t;let s=await e.select(this.shouldSelect(t)).getModels();return this.hydratePivotRelation(s),s.length>0&&(s=await e.eagerLoadRelations(s)),new nt(s)}async first(t=["*"]){const e=await this.take(1).get(t);return e.count()>0?e.first():null}async firstOrFail(t=["*"]){const e=await this.first(t);if(null!==e)return e;throw(new ht).setModel(this.related.constructor)}async paginate(t=1,e=15,s=["*"]){return this.query.select(this.shouldSelect(s)),Y(await this.query.paginate(t,e),t=>{this.hydratePivotRelation(t.items())})}async chunk(t,e){return await this.prepareQueryBuilder().chunk(t,async(t,s)=>(this.hydratePivotRelation(t.all()),await e(t,s)))}setUsing(t){return this.using=t,this}as(t){return this.accessor=t,this}prepareQueryBuilder(){return this.query.select(this.shouldSelect())}hydratePivotRelation(t){t.map(t=>{t.setRelation(this.accessor,this.newExistingPivot(this.migratePivotAttributes(t)))})}migratePivotAttributes(t){const e={};for(const s in t.attributes){const i=t.attributes[s];s.startsWith("pivot_")&&(e[s.substring(6)]=i,t.attributes=d(t.attributes,[s]))}return e}withTimestamps(t=null,e=null){return this.pivotCreatedAt=t,this.pivotUpdatedAt=e,this.withPivot(this.createdAt(),this.updatedAt())}shouldSelect(t=["*"]){return y(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return q(t.concat(this.pivotColumns)).map(t=>this.qualifyPivotColumn(t)+" as pivot_"+t).unique().all()}qualifyPivotColumn(t){return t.includes(".")?t:this.getTable()+"."+t}match(t,e,s){const i=this.buildDictionary(e);return t.map(t=>{const e=t.getKey();void 0!==i[e]&&t.setRelation(s,i[e])}),t}buildDictionary(t){const e={};return t.map(t=>{const s=t[this.accessor][this.foreignPivotKey];void 0===e[s]&&(e[s]=new nt([])),e[s].push(t)}),e}addEagerConstraints(t){this.query.whereIn(this.getQualifiedForeignPivotKeyName(),this.getKeys(t,this.parentKey))}getQualifiedForeignPivotKeyName(){return this.qualifyPivotColumn(this.foreignPivotKey)}getQualifiedRelatedPivotKeyName(){return this.qualifyPivotColumn(this.relatedPivotKey)}wherePivot(t,e=null,s=null,i="and"){return this.pivotWheres.push(Array.prototype.slice.call(arguments)),this.where(this.qualifyPivotColumn(t),e,s,i)}wherePivotBetween(t,e,s="and",i=!1){return this.whereBetween(this.qualifyPivotColumn(t),e,s,i)}orWherePivotBetween(t,e){return this.wherePivotBetween(t,e,"or")}wherePivotNotBetween(t,e,s="and"){return this.wherePivotBetween(t,e,s,!0)}orWherePivotNotBetween(t,e){return this.wherePivotBetween(t,e,"or",!0)}wherePivotIn(t,e,s="and",i=!1){return this.whereIn(this.qualifyPivotColumn(t),e,s,i)}orWherePivot(t,e=null,s=null){return this.wherePivot(t,e,s,"or")}orWherePivotIn(t,e){return this.wherePivotIn(t,e,"or")}wherePivotNotIn(t,e,s="and"){return this.wherePivotIn(t,e,s,!0)}orWherePivotNotIn(t,e){return this.wherePivotNotIn(t,e,"or")}wherePivotNull(t,e="and",s=!1){return this.whereNull(this.qualifyPivotColumn(t),e,s)}wherePivotNotNull(t,e="and"){return this.wherePivotNull(t,e,!0)}orWherePivotNull(t,e=!1){return this.wherePivotNull(t,"or",e)}orWherePivotNotNull(t){return this.orWherePivotNull(t,!0)}orderByPivot(t,e="asc"){return this.orderBy(this.qualifyPivotColumn(t),e)}createdAt(){return this.pivotCreatedAt||this.parent.getCreatedAtColumn()}updatedAt(){return this.pivotUpdatedAt||this.parent.getUpdatedAtColumn()}getExistenceCompareKey(){return this.getQualifiedForeignPivotKeyName()}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery()._single.table==t.getQuery()._single.table?this.getRelationExistenceQueryForSelfJoin(t,e,s):(this.performJoin(t),super.getRelationExistenceQuery(t,e,s))}getRelationExistenceQueryForSelfJoin(t,e,s=["*"]){const i=this.getRelationCountHash();return t.select(s).from(this.related.getTable()+" as "+i),this.related.setTable(i),this.performJoin(t),super.getRelationExistenceQuery(t,e,s)}},gt=class{static formatter;_items;_total;_perPage;_lastPage;_currentPage;hasMore=!1;options={};static setFormatter(t){if("function"!=typeof t&&null!=t)throw new Error("Paginator formatter must be a function or null");this.formatter=t}constructor(t,e,s,i=1,r={}){this.options=r;for(const t in r){const e=r[t];this[t]=e}this._items=new nt([]),this._total=e,this._perPage=parseInt(String(s)),this._lastPage=Math.max(Math.ceil(e/s),1),this._currentPage=i,this.setItems(t)}setItems(t){this._items=t instanceof nt?t:new nt(t),this.hasMore=this._items.count()>this._perPage,this._items=this._items.slice(0,this._perPage)}firstItem(){return this.count()>0?(this._currentPage-1)*this._perPage+1:null}lastItem(){return this.count()>0?(this.firstItem()??0)+this.count()-1:null}hasMorePages(){return this._currentPage<this._lastPage}get(t){return this._items.get(t)}count(){return this._items.count()}items(){return this._items}map(t){return this._items.map(t)}currentPage(){return this._currentPage}onFirstPage(){return 1===this._currentPage}perPage(){return this._perPage}lastPage(){return this._lastPage}total(){return this._total}toData(){return this.constructor.formatter&&"function"==typeof this.constructor.formatter?this.constructor.formatter(this):{current_page:this._currentPage,data:this._items.toData(),per_page:this._perPage,total:this._total,last_page:this._lastPage,count:this.count()}}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}},dt=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},yt=class{},mt=class t extends yt{query;connection;model;actions;localMacros={};eagerLoad={};globalScopes={};onDeleteCallback;constructor(t){return super(),this.query=t,this.asProxy()}asProxy(){return new Proxy(this,{get(t,e){if(void 0!==t[e])return t[e];if(["select","from","where","orWhere","whereColumn","whereRaw","whereNot","orWhereNot","whereIn","orWhereIn","whereNotIn","orWhereNotIn","whereNull","orWhereNull","whereNotNull","orWhereNotNull","whereExists","orWhereExists","whereNotExists","orWhereNotExists","whereBetween","orWhereBetween","whereNotBetween","orWhereNotBetween","whereLike","orWhereLike","whereILike","orWhereILike","whereJsonObject","whereJsonPath","whereJsonSupersetOf","whereJsonSubsetOf","join","joinRaw","leftJoin","leftOuterJoin","rightJoin","rightOuterJoin","crossJoin","transacting","groupBy","groupByRaw","returning","having","havingRaw","havingBetween","limit","offset","orderBy","orderByRaw","union","insert","forUpdate","forShare","distinct","clearOrder","clear","clearSelect","clearWhere","clearHaving","clearGroup"].includes(e))return(...s)=>(t.query[e](...s),t.asProxy());if(["avg","max","min","sum","count"].includes(e))return s=>{const i=t.asProxy();return i.applyScopes(),s=s||"count"!==e?s:"*",i.query[e](s)};if("string"==typeof e){if(t.hasMacro(e)){const s=t.asProxy();return(...t)=>s.localMacros[e](s,...t)}if(t.hasNamedScope(e)){const s=t.asProxy();return(...t)=>(s.callNamedScope(e,t),s)}if(e.startsWith("where")){const s=R(e.substring(5));return(...e)=>(t.query.where(s,...e),t.asProxy())}}}})}orWhere(...t){if("function"==typeof t[0]){const e=t[0];return this.query.orWhere(t=>{this.query=t,e(this)}),this}return this.query.orWhere(...t),this}async chunk(t,e){let s,i=1;do{this.enforceOrderBy();const r=this.clone(),n=await r.forPage(i,t).get();if(s=n.count(),0==s)break;if(!1===await e(n,i))return!1;i++}while(s===t);return!0}enforceOrderBy(){0===this.query._statements.filter(t=>"order"===t.grouping).length&&this.orderBy(this.model.getQualifiedKeyName(),"asc")}clone(){const t=this.query.clone(),e=new this.constructor(t);return e.connection=this.connection,e.setModel(this.model),e.globalScopes={...this.globalScopes},e.localMacros={...this.localMacros},e.eagerLoad={...this.eagerLoad},e}forPage(t,e=15){return this.offset((t-1)*e).limit(e)}insert(...t){return this.query.insert(...t)}update(t){return this.applyScopes(),this.query.update(this.addUpdatedAtColumn(t))}increment(t,e=1,s={}){this.applyScopes();const i=this.model.getConnection();return this.query.update(this.addUpdatedAtColumn({...s,[t]:i.raw(`${t} + ${e}`)}))}decrement(t,e=1,s={}){this.applyScopes();const i=this.model.getConnection();return this.query.update(this.addUpdatedAtColumn({...s,[t]:i.raw(`${t} - ${e}`)}))}addUpdatedAtColumn(t){if(!this.model.usesTimestamps()||null===this.model.getUpdatedAtColumn())return t;const e=this.model.getUpdatedAtColumn();return t=p({[e]:this.model.freshTimestampString()},t)}delete(){return this.onDeleteCallback?this.onDeleteCallback(this):this.query.delete()}onDelete(t){this.onDeleteCallback=t}forceDelete(){return this.query.delete()}async create(t={}){return await Y(this.newModelInstance(t),async t=>{await t.save({client:this.query})})}newModelInstance(t={}){return this.model.newInstance(t).setConnection(this.model.getConnectionName())}getQuery(){return this.query}getModel(){return this.model}setModel(t){return this.model=t,"function"==typeof this.query?.client?.table?this.query=this.query.client.table(this.model.getTable()):this.query=this.query.table(this.model.getTable()),this}qualifyColumn(t){return this.model.qualifyColumn(t)}setTable(t){return this.query=this.query.table(t),this}applyScopes(){if(!this.globalScopes)return this;for(const t in this.globalScopes){const e=this.globalScopes[t];e instanceof dt?e.apply(this,this.getModel()):e(this)}return this}hasNamedScope(t){return this.model&&this.model.hasNamedScope(t)}callNamedScope(t,e){return this.model.callNamedScope(t,[this,...e])}callScope(t,e=[]){return t(this,...e)||this}scopes(t){return t.map(t=>{const e=z(t);"function"==typeof this.model[e]&&(this.globalScopes[t]=this.model[e])}),this}withGlobalScope(t,e){return this.globalScopes[t]=e,"function"==typeof e.extend&&e.extend(this),this}withoutGlobalScope(t){return"string"!=typeof t&&(t=t.constructor.name),this.globalScopes=d(this.globalScopes,[t]),this}macro(t,e){return this.localMacros[t]=e,this}hasMacro(t){return t in this.localMacros}getMacro(t){return this.localMacros[t]}with(...t){let e={};if("function"==typeof t[1]){const e=this.parseWithRelations({[t[0]]:t[1]});return this.eagerLoad=p(this.eagerLoad,e),this}const s=X(t);if(0===s.length)return this;for(const t of s){let s;"string"==typeof t?s={[t]:t=>t}:"object"==typeof t&&(s=t),e=p(e,s)}return this.eagerLoad=p(this.eagerLoad,this.parseWithRelations(e)),this}has(t,e=">=",s=1,i="and",r=null){if(A(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(J(t))}const n=t[this.canUseExistsForExistenceCheck(e,s)?"getRelationExistenceQuery":"getRelationExistenceCountQuery"](t.getRelated().newModelQuery(),this);return r&&r(n),this.addHasWhere(n,t,e,s,i)}orHas(t,e=">=",s=1){return this.has(t,e,s,"or")}doesntHave(t,e="and",s=null){return this.has(t,"<",1,e,s)}orDoesntHave(t){return this.doesntHave(t,"or")}whereHas(t,e=null,s=">=",i=1){return this.has(t,s,i,"and",e)}orWhereHas(t,e=null,s=">=",i=1){return this.has(t,s,i,"or",e)}whereRelation(t,...e){const s=e.shift();return this.whereHas(t,t=>{"function"==typeof s?s(t):t.where(s,...e)})}orWhereRelation(t,...e){const s=e.shift();return this.orWhereHas(t,function(t){"function"==typeof s?s(t):t.where(s,...e)})}hasNested(t,e=">=",s=1,i="and",r=null){t=t.split(".");const n="<"===e&&1===s;n&&(e=">=",s=1);const a=i=>(t.length>1?i.whereHas(t.shift(),a):i.has(t.shift(),e,s,"and",r),null);return this.has(t.shift(),n?"<":">=",1,i,a)}canUseExistsForExistenceCheck(t,e){return(">="===t||"<"===t)&&1===e}addHasWhere(t,e,s,i,r){return t.mergeConstraintsFrom(e.getQuery()),this.canUseExistsForExistenceCheck(s,i)?this.addWhereExistsQuery(t.getQuery(),r,"<"===s&&1===i):this.addWhereCountQuery(t.getQuery(),s,i,r)}addWhereExistsQuery(t,e="and",s=!1){const i=s?"NotExists":"Exists";return this["and"===e?"where"+i:"orWhere"+i](t.connector),this}addWhereCountQuery(t,e=">=",s=1,i="and"){const r=this.model.getConnection();return this.where(r.raw("("+t.toSQL().sql+")"),e,"number"==typeof s?r.raw(s):s,i)}withAggregate(t,e,s=null){if(0===t.length)return this;t=X([t]);let i={};for(const e of t){let t;"string"==typeof e?t={[e]:t=>t}:"object"==typeof e&&(t=e),i=p(i,t)}t=i;const r=this.model.getConnection();0===this.query._statements.filter(t=>"columns"==t.grouping).map(t=>t.value).flat().length&&this.query.select([this.query._single.table+".*"]);const n=this.parseWithRelations(t);for(let t in n){const i=n[t],a=t.split(" ");let o,h;3===a.length&&"as"===a[1].toLocaleLowerCase()&&([t,o]=[a[0],a[2]]);const c=this.getRelationWithoutConstraints(J(t));if(s){const t=this.query._single.table===c.query.query._single.table?`${c.getRelationCountHash(!1)}.${e}`:e,i="*"===e?e:c.getRelated().qualifyColumn(t);h="exists"===s?i:`${s}(${i})`}else h=e;const u=c.getRelationExistenceQuery(c.getRelated().newModelQuery(),this,r.raw(h));i(u),o=o||R(`${t} ${s} ${e}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===s?this.select(r.raw(`exists(${u.toSql().sql}) as ${o}`)):this.selectSub(s?u:u.limit(1),o)}return this}toSql(){const t=this.clone();return t.applyScopes(),t.query.toSQL()}mergeConstraintsFrom(t){return this}selectSub(t,e){const[s,i]=this.createSub(t),r=this.model.getConnection();return this.select(r.raw("("+s+") as "+e,i))}createSub(t){return this.parseSub(t)}parseSub(e){if(e instanceof t||e instanceof st)return[e.toSql().sql,e.toSql().bindings];if(A(e))return[e,[]];throw new Error("A subquery must be a query builder instance, a Closure, or a string.")}prependDatabaseNameIfCrossDatabaseQuery(t){if(t.query._single.table!==this.query._single.table){const e=t.query._single.table;t.query._single.table.startsWith(e)||t.query._single.table.contains(".")||t.from(e+"."+t.from)}return t}getRelationWithoutConstraints(t){return st.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate(X(t),"*","count")}withMax(t,e){return this.withAggregate(t,e,"max")}withMin(t,e){return this.withAggregate(t,e,"min")}withAvg(t,e){return this.withAggregate(t,e,"avg")}withSum(t,e){return this.withAggregate(t,e,"sum")}withExists(t){return this.withAggregate(t,"*","exists")}parseWithRelations(t){if(0===t.length)return[];let e={};const s=this.prepareNestedWithRelationships(t);for(const t in s)e=this.addNestedWiths(t,e),e[t]=s[t];return e}addNestedWiths(t,e){const s=[];return t.split(".").map(t=>{s.push(t);const i=s.join(".");void 0===e[i]&&(e[i]=()=>{})}),e}prepareNestedWithRelationships(t,e=""){let s={};""!==e&&(e+=".");for(const i in t){const r=t[i];if(A(r)||Number.isFinite(parseInt(r)))continue;const[n,a]=this.parseNameAndAttributeSelectionConstraint(i,r);s=Object.assign({},s,{[`${e}${n}`]:a},this.prepareNestedWithRelationships(r,`${e}${n}`)),t=d(t,[i])}for(const i in t){const r=t[i];let n=i,a=r;A(r)&&([n,a]=this.parseNameAndAttributeSelectionConstraint(r)),s[`${e}${n}`]=this.combineConstraints([a,s[`${e}${n}`]||(()=>{})])}return s}combineConstraints(t){return e=>(t.map(t=>{e=t(e)||e}),e)}parseNameAndAttributeSelectionConstraint(t,e){return t.includes(":")?this.createSelectWithConstraint(t):[t,e]}createSelectWithConstraint(t){return[t.split(":")[0],e=>{e.select(t.split(":")[1].split(",").map(t=>t.includes(".")?t:e instanceof lt?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[J(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new ct(e)}return this.model[J(t)]()}take(...t){return this.limit(...t)}skip(...t){return this.offset(...t)}async first(...t){this.applyScopes(),this.limit(1);let e=await this.getModels(t);return e.length>0&&(e=await this.eagerLoadRelations(e)),e[0]||null}async firstOrFail(...t){const e=await this.first(...t);if(null===e)throw(new ht).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(w(t[0])){if(e.count()!==t[0].length)throw(new ht).setModel(this.model.constructor.name,f(t[0],e.modelKeys()));return e}if(null===e)throw(new ht).setModel(this.model.constructor.name,t[0]);return e}async findOrNew(t,e=["*"]){const s=await this.find(t,e);return null!==s?s:this.newModelInstance()}async firstOrNew(t={},e={}){const s=await this.where(t).first();return null!==s?s:this.newModelInstance(p(t,e))}async firstOrCreate(t={},e={}){const s=await this.where(t).first();return null!==s?s:Y(this.newModelInstance(p(t,e)),async t=>{await t.save({client:this.query})})}async updateOrCreate(t,e={}){return await Y(await this.firstOrNew(t),async t=>{await t.fill(e).save({client:this.query})})}latest(t="id"){return null===t&&(t=this.model.getCreatedAtColumn()||"created_at"),this.query.orderBy(t,"desc"),this}oldest(t="id"){return null===t&&(t=this.model.getCreatedAtColumn()||"created_at"),this.query.orderBy(t,"asc"),this}async find(t,e){return w(t)||t instanceof nt?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof nt&&(t=t.modelKeys()),0===(t=w(t)?t:[t]).length?new nt([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new nt(e)}async destroy(t){if(t instanceof nt&&(t=t.modelKeys()),t instanceof E&&(t=t.all()),0===(t=w(t)?t:Array.prototype.slice.call(t)).length)return 0;const e=this.model.newInstance().getKeyName();let s=0;const i=await this.model.newModelQuery().whereIn(e,t).get();for(const t of i)await t.delete()&&s++;return s}async get(t=["*"]){this.applyScopes();let e=await this.getModels(t);return e.length>0&&(e=await this.eagerLoadRelations(e)),new nt(e)}async all(t=["*"]){return await this.model.newModelQuery().get(t)}async paginate(t=1,e=10){t=t||1,e=e||this?.model?.perPage||15,this.applyScopes();const s=this.query.clone(),i=await s.clearOrder().clearSelect().count(this.primaryKey);let r=[];if(i>0){const s=(t-1)*(e??10);this.take(e).skip(s),r=await this.getModels(),r.length>0&&(r=await this.eagerLoadRelations(r))}else r=[];return new gt(r,parseInt(i),e,t)}async getModels(...t){return(t=v(t)).length>0&&0==this.query._statements.filter(t=>"columns"==t.grouping).length&&"*"!==t[0]&&this.query.select(...t),this.hydrate(await this.query.get()).all()}getRelation(t){if("function"!=typeof this.model[J(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new ct(e)}const e=st.noConstraints(()=>this.model.newInstance(this.model.attributes)[J(t)]()),s=this.relationsNestedUnder(t);return Object.keys(s).length>0&&e.query.with(s),e.asProxy()}relationsNestedUnder(t){const e={};for(const s in this.eagerLoad){const i=this.eagerLoad[s];this.isNestedUnder(t,s)&&(e[s.substring((t+".").length)]=i)}return e}isNestedUnder(t,e){return e.includes(".")&&e.startsWith(t+".")}async eagerLoadRelation(t,e,s){const i=this.getRelation(e);return i.addEagerConstraints(t),s(i),i.match(i.initRelation(t,e),await i.get(),e)}async eagerLoadRelations(t){for(const e in this.eagerLoad){const s=this.eagerLoad[e];e.includes(".")||(t=await this.eagerLoadRelation(t,e,s))}return t}hydrate(t){return new nt(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},pt=class t{constructor(){if(this.constructor===t)throw new Error("CastsAttributes cannot be instantiated")}static get(t,e,s,i){throw new Error("get not implemented")}static set(t,e,s,i){throw new Error("set not implemented")}},ft=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=X(t);return this.appends=[...this.appends,...e],this}normalizeCastClassResponse(t,e){return"Object"===e?.constructor?.name?e:{[t]:e}}syncOriginal(){return this.original=this.getAttributes(),this}syncChanges(){return this.changes=this.getDirty(),this}syncOriginalAttribute(t){this.syncOriginalAttributes(t)}syncOriginalAttributes(...t){t=X(t);const e=this.getAttributes();for(const s of t)this.original[s]=e[s];return this}isDirty(...t){const e=this.getDirty();if(0===(t=X(t)).length)return Object.keys(e).length>0;for(const s of t)if(s in e)return!0;return!1}getDirty(){const t={},e=this.getAttributes();for(const s in e){const i=e[s];this.originalIsEquivalent(s)||(t[s]=i)}return t}originalIsEquivalent(t){if(void 0===this.original[t])return!1;return this.attributes[t]===this.original[t]}setAttributes(t){this.attributes={...t}}setRawAttributes(t,e=!1){return this.attributes=t,e&&this.syncOriginal(),this}getAttributes(){return{...this.attributes}}setAttribute(t,e){const s=N(`set_${t}_attribute`);if("function"==typeof this[s])return this[s](e),this;const i=G(t);if("function"==typeof this[i]){const s=this[i]().set||(e=>{this.attributes[t]=e});return this.attributes={...this.attributes,...this.normalizeCastClassResponse(t,s(e,this.attributes))},this}const r=this.getCasts()[t];return this.isCustomCast(r)&&"string"!=typeof r&&(e=r.set(this,t,e,this.attributes)??""),"json"===r&&(e=JSON.stringify(e)),"collection"===r&&(e=JSON.stringify(e)),null!==e&&this.isDateAttribute(t)&&(e=this.fromDateTime(e)),this.attributes[t]=e,this}getAttribute(t){if(!t)return;const e=V(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=G(t);if("function"==typeof this[s]){return this[s]().get(this.attributes[t],this.attributes)}return t in this.attributes?this.hasCast(t)?this.castAttribute(t,this.attributes[t]):this.getDates().includes(t)?this.asDateTime(this.attributes[t]):this.attributes[t]:t in this.relations?this.relations[t]:void 0}castAttribute(t,e){const s=this.getCastType(t);if(!s)return e;if(null===e)return e;switch(s){case"int":case"integer":return parseInt(e);case"real":case"float":case"double":return parseFloat(e);case"decimal":return this.asDecimal(e,s.split(":")[1]);case"string":return String(e);case"bool":case"boolean":return Boolean(e);case"object":case"json":try{return JSON.parse(e)}catch{return null}case"collection":try{return D(JSON.parse(e))}catch{return D([])}case"date":return this.asDate(e);case"datetime":case"custom_datetime":return this.asDateTime(e);case"timestamp":return this.asTimestamp(e)}return this.isCustomCast(s)?s.get(this,t,e,this.attributes):e}attributesToData(){let t={...this.attributes};for(const e in t)this.hidden.includes(e)&&(t=d(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=d(t,[e]));for(const e of this.getDates())void 0!==t[e]&&(t[e]=this.serializeDate(this.asDateTime(t[e])));const e=this.getCasts();for(const s in e){const i=e[s];s in t!=!1&&(t[s]=this.castAttribute(s,t[s]),s in t&&["date","datetime"].includes(String(i))&&(t[s]=this.serializeDate(t[s])),s in t&&this.isCustomDateTimeCast(i)&&(t[s]=T(t[s]).format(String(i).split(":")[1])))}for(const e of this.appends)t[e]=this.mutateAttribute(e,null);return t}mutateAttribute(t,e){if("function"==typeof this[V(t)])return this[V(t)](e);if("function"==typeof this[G(t)]){return this[G(t)]().get(t,this.attributes)}return t in this?this[t]:e}mutateAttributeForArray(t,e){}isDateAttribute(t){return this.getDates().includes(t)||this.isDateCastable(t)}serializeDate(t){return t?T(t).toISOString():null}getDates(){return this.usesTimestamps()?[this.getCreatedAtColumn(),this.getUpdatedAtColumn()]:[]}getCasts(){return this.getIncrementing()?{[this.getKeyName()]:this.getKeyType(),...this.casts}:this.casts}getCastType(t){const e=this.getCasts()[t];let s,i;return"string"==typeof e?s=e:new e instanceof pt&&(s=e.name),s&&void 0!==this.getConstructor().castTypeCache[s]?this.getConstructor().castTypeCache[s]:(i=this.isCustomDateTimeCast(e)?"custom_datetime":this.isDecimalCast(e)?"decimal":this.isCustomCast(e)?e:String(e).toLocaleLowerCase().trim(),this.getConstructor()[s]=i)}hasCast(t,e=[]){return t in this.casts&&(!((e=v(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return T(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof pt}isCustomDateTimeCast(t){return"string"==typeof t&&(t.startsWith("date:")||t.startsWith("datetime:"))}isDecimalCast(t){return"string"==typeof t&&t.startsWith("decimal:")}isDateCastable(t){return this.hasCast(t,["date","datetime"])}fromDateTime(t){return T(this.asDateTime(t)).format(this.getDateFormat())}getDateFormat(){return this.dateFormat||"YYYY-MM-DD HH:mm:ss"}asDecimal(t,e){return parseFloat(t).toFixed(e)}asDateTime(t){return null===t?null:t instanceof Date?t:"number"==typeof t?new Date(1e3*t):new Date(t)}asDate(t){const e=this.asDateTime(t);return T(e).startOf("day").toDate()}},wt=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof dt)return this.globalScopes=P(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof dt)return this.globalScopes=P(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new ut("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return K(this.globalScopes,"string"==typeof t?this.name+"."+t:this.name+"."+t.constructor.name)}static getAllGlobalScopes(){return this.globalScopes}static setAllGlobalScopes(t){this.globalScopes=t}getGlobalScopes(){return K(this.constructor.globalScopes,this.constructor.name,{})}},bt=class{hooks={creating:[],created:[],updating:[],updated:[],saving:[],saved:[],deleting:[],deleted:[],restoring:[],restored:[],trashed:[],forceDeleting:[],forceDeleted:[]};add(t,e){this.hooks[t].push(e)}async exec(t,e){const s=this.hooks[t]??[];for(const t of s)await t(...e);return!0}},Ct=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof bt==!1&&(this.hooks=new bt),this.hooks.add(t,e)}static creating(t){this.addHook("creating",t)}static created(t){this.addHook("created",t)}static updating(t){this.addHook("updating",t)}static updated(t){this.addHook("updated",t)}static saving(t){this.addHook("saving",t)}static saved(t){this.addHook("saved",t)}static deleting(t){this.addHook("deleting",t)}static deleted(t){this.addHook("deleted",t)}static restoring(t){this.addHook("restoring",t)}static restored(t){this.addHook("restored",t)}static trashed(t){this.addHook("trashed",t)}static forceDeleted(t){this.addHook("forceDeleted",t)}async execHooks(t,e){if(this.constructor.hooks instanceof bt!=!1)return await this.constructor.hooks.exec(t,[this,e])}},vt=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new nt(i)}matchOneOrMany(t,e,s,i){const r=this.buildDictionary(e);return t.map(t=>{const e=t.attributes[this.localKey];void 0!==r[e]&&t.setRelation(s,this.getRelationValue(r,e,i))}),t}buildDictionary(t){const e=this.getForeignKeyName();return D(t).mapToDictionary(t=>[t[e],t]).all()}async save(t){return this.setForeignAttributesForCreate(t),!!await t.save()&&t}async saveMany(t){return await Promise.all(t.map(async t=>{await this.save(t)})),t instanceof nt?t:new nt(t)}async create(t={}){return await Y(this.related.constructor.init(t),async t=>{this.setForeignAttributesForCreate(t),await t.save()})}async createMany(t){const e=await Promise.all(t.map(async t=>await this.create(t)));return e instanceof nt?e:new nt(e)}setForeignAttributesForCreate(t){t[this.getForeignKeyName()]=this.getParentKey()}getForeignKeyName(){const t=this.getQualifiedForeignKeyName().split(".");return t[t.length-1]}getParentKey(){return this.parent.attributes[this.localKey]}getQualifiedForeignKeyName(){return this.foreignKey}getExistenceCompareKey(){return this.getQualifiedForeignKeyName()}addConstraints(){if(this.constructor.constraints){const t=this.getRelationQuery();t.where(this.foreignKey,"=",this.getParentKey()),t.whereNotNull(this.foreignKey)}}},Pt=class extends(Z(st,vt)){foreignKey;localKey;constructor(t,e,s,i){return super(t,e),this.foreignKey=s,this.localKey=i,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,new nt([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new nt([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return q(t).mapToDictionary(t=>[t[e],t]).all()}match(t,e,s){return this.matchOneOrMany(t,e,s,"many")}addEagerConstraints(t){this.query.whereIn(this.foreignKey,this.getKeys(t,this.localKey))}},Kt=class extends(Z(st,vt,it)){foreignKey;localKey;constructor(t,e,s,i){return super(t,e),this.foreignKey=s,this.localKey=i,this.addConstraints(),this.asProxy()}initRelation(t,e){return t.map(t=>{t.setRelation(e,this.getDefaultFor(t))}),t}matchOne(t,e,s){return this.matchOneOrMany(t,e,s,"one")}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}async getResults(){if(null===this.getParentKey())return this.getDefaultFor(this.parent);return await this.query.first()||this.getDefaultFor(this.parent)}match(t,e,s){return this.matchOneOrMany(t,e,s,"one")}addEagerConstraints(t){this.query.whereIn(this.foreignKey,this.getKeys(t,this.localKey))}newRelatedInstanceFor(t){return this.related.newInstance().setAttribute(this.getForeignKeyName(),t[this.localKey])}},Nt=class extends st{throughParent;farParent;firstKey;secondKey;localKey;secondLocalKey;constructor(t,e,s,i,r,n,a){return super(t,s),this.localKey=n,this.firstKey=i,this.secondKey=r,this.farParent=e,this.throughParent=s,this.secondLocalKey=a,this.asProxy()}addConstraints(){const t=this.farParent[this.localKey];this.performJoin(),this.constructor.constraints&&this.query.where(this.getQualifiedFirstKeyName(),"=",t)}performJoin(t=null){t=t||this.query;const e=this.getQualifiedFarKeyName();t.join(this.throughParent.getTable(),this.getQualifiedParentKeyName(),"=",e),this.throughParentSoftDeletes()&&t.withGlobalScope("SoftDeletableHasManyThrough",t=>{t.whereNull(this.throughParent.getQualifiedDeletedAtColumn())})}getQualifiedParentKeyName(){return this.parent.qualifyColumn(this.secondLocalKey)}throughParentSoftDeletes(){return void 0!==this.throughParent.pluginInitializers.SoftDeletes}withTrashedParents(){return this.query.withoutGlobalScope("SoftDeletableHasManyThrough"),this}addEagerConstraints(t){const e=this.whereInMethod(this.farParent,this.localKey);this.whereInEager(e,this.getQualifiedFirstKeyName(),this.getKeys(t,this.localKey))}initRelation(t,e){for(const s of t)s.setRelation(e,this.related.newCollection());return t}match(t,e,s){const i=this.buildDictionary(e);for(const e of t){const t=this.getDictionaryKey(e.getAttribute(this.localKey));void 0!==i[t]&&e.setRelation(s,this.related.newCollection(i[t]))}return t}buildDictionary(t){const e={};for(const s of t)void 0===e[s.laravel_through_key]&&(e[s.laravel_through_key]=[]),e[s.laravel_through_key].push(s);return e}async firstOrNew(t){return await this.where(t).first()||this.related.newInstance(t)}async updateOrCreate(t,e={}){return Y(await this.firstOrCreate(t,e),async t=>{t.wasRecentlyCreated||await t.fill(e).save()})}async firstWhere(t,e=null,s=null,i="and"){return await this.where(t,e,s,i).first()}async first(t=["*"]){const e=await this.take(1).get(t);return e.count()>0?e.first():null}async firstOrFail(t=["*"]){const e=await this.first(t);if(e)return e;throw(new ht).setModel(this.related.constructor)}async firstOr(t=["*"],e=null){"function"==typeof t&&(e=t,t=["*"]);const s=await this.first(t);return s||e?.()}async find(t,e=["*"]){return w(t)?await this.findMany(t,e):await this.where(this.getRelated().getQualifiedKeyName(),"=",t).first(e)}async findMany(t,e=["*"]){return 0===t.length?this.getRelated().newCollection():await this.whereIn(this.getRelated().getQualifiedKeyName(),t).get(e)}async findOrFail(t,e=["*"]){const s=await this.find(t,e);if(Array.isArray(t)){if(s.count()===t.length)return s}else if(s)return s;throw(new ht).setModel(this.related.constructor,t)}async getResults(){return this.farParent[this.localKey]?await this.get():this.related.newCollection()}async get(t=["*"]){const e=this.prepareQueryBuilder(t);let s=await e.getModels();return s.count()>0&&(s=await e.eagerLoadRelations(s)),this.related.newCollection(s)}async paginate(t=null,e=["*"],s="page",i=null){return this.query.addSelect(this.shouldSelect(e)),await this.query.paginate(t,e,s,i)}shouldSelect(t=["*"]){return"*"==t?.at(0)&&(t=[this.related.getTable()+".*"]),[...t,this.getQualifiedFirstKeyName()+" as laravel_through_key"]}async chunk(t,e){return await this.prepareQueryBuilder().chunk(t,e)}prepareQueryBuilder(t=["*"]){const e=this.query.applyScopes();return e.addSelect(this.shouldSelect(e.getQuery().columns?[]:t))}getRelationExistenceQuery(t,e,s=["*"]){return e.getQuery().from===t.getQuery().from?this.getRelationExistenceQueryForSelfRelation(t,e,s):e.getQuery().from===this.throughParent.getTable()?this.getRelationExistenceQueryForThroughSelfRelation(t,e,s):(this.performJoin(t),t.select(s).where(this.getQualifiedLocalKeyName(),"=",this.getQualifiedFirstKeyName()))}getRelationExistenceQueryForSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash();return t.from(t.getModel().getTable()+" as "+i),t.join(this.throughParent.getTable(),this.getQualifiedParentKeyName(),"=",i+"."+this.secondKey),this.throughParentSoftDeletes()&&t.whereNull(this.throughParent.getQualifiedDeletedAtColumn()),t.getModel().setTable(i),t.select(s).whereColumn(e.getQuery().from+"."+this.localKey,"=",this.getQualifiedFirstKeyName())}getRelationExistenceQueryForThroughSelfRelation(t,e,s=["*"]){const i=this.getRelationCountHash(),r=this.throughParent.getTable()+" as "+i;return t.join(r,i+"."+this.secondLocalKey,"=",this.getQualifiedFarKeyName()),this.throughParentSoftDeletes()&&t.whereNull(i+"."+this.throughParent.getDeletedAtColumn()),t.select(s).where(e.getQuery().from+"."+this.localKey,"=",i+"."+this.firstKey)}getQualifiedFarKeyName(){return this.getQualifiedForeignKeyName()}getFirstKeyName(){return this.firstKey}getQualifiedFirstKeyName(){return this.throughParent.qualifyColumn(this.firstKey)}getForeignKeyName(){return this.secondKey}getQualifiedForeignKeyName(){return this.related.qualifyColumn(this.secondKey)}getLocalKeyName(){return this.localKey}getQualifiedLocalKeyName(){return this.farParent.qualifyColumn(this.localKey)}getSecondLocalKeyName(){return this.secondLocalKey}},Rt=class extends(Z(Nt,it)){async getResults(){return await this.first()||this.getDefaultFor(this.farParent)}initRelation(t,e){for(const s of t)s.setRelation(e,this.getDefaultFor(s));return t}match(t,e,s){const i=this.buildDictionary(e);for(const e of t){const t=this.getDictionaryKey(e.getAttribute(this.localKey));if(void 0!==i[t]){const r=i[t];e.setRelation(s,r[0])}}return t}newRelatedInstanceFor(t){return this.related.newInstance()}},At=t=>class extends t{relations={};getRelation(t){return this.relations[t]}setRelation(t,e){return this.relations[t]=e,this}unsetRelation(t){return this.relations=d(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[J(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new ct(e)}return this[J(t)]()}async getRelated(t){return await this.related(t).getResults()}relationsToData(){const t={};for(const e in this.relations)this.hidden.includes(e)||this.visible.length>0&&!1===this.visible.includes(e)||(t[e]=this.relations[e]instanceof Array?this.relations[e].map(t=>t.toData()):null===this.relations[e]?null:this.relations[e].toData());return t}guessBelongsToRelation(){const t=(new Error).stack.split("\n")[2].split(" ")[5];return R(t.substring(8))}joiningTable(t,e=null){return[e?e.joiningTableSegment():tt(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return tt(this.constructor.name)}hasOne(t,e=null,s=null){const i=t.query(),r=new t;return e=e||this.getForeignKey(),s=s||this.getKeyName(),new Kt(i,this,r.getTable()+"."+e,s)}hasMany(t,e=null,s=null){const i=t.query(),r=new t;return e=e||this.getForeignKey(),s=s||this.getKeyName(),new Pt(i,this,r.getTable()+"."+e,s)}belongsTo(t,e=null,s=null,i=null){const r=t.query(),n=new t;return e=e||n.getForeignKey(),s=s||n.getKeyName(),i=i||this.guessBelongsToRelation(),new rt(r,this,e,s,i)}belongsToMany(t,e=null,s=null,i=null,r=null,n=null){const a=t.query(),o=new t;return e=e||this.joiningTable(t,o),s=s||this.getForeignKey(),i=i||o.getForeignKey(),r=r||this.getKeyName(),n=n||o.getKeyName(),new lt(a,this,e,s,i,r,n)}hasOneThrough(t,e,s=null,i=null,r=null,n=null){e=new e;const a=t.query();return s=s||this.getForeignKey(),i=i||e.getForeignKey(),new Rt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}hasManyThrough(t,e,s=null,i=null,r=null,n=null){e=new e;const a=t.query();return s=s||this.getForeignKey(),i=i||e.getForeignKey(),new Nt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},xt=t=>class extends t{static CREATED_AT="created_at";static UPDATED_AT="updated_at";static DELETED_AT="deleted_at";timestamps=!0;dateFormat="YYYY-MM-DD HH:mm:ss";usesTimestamps(){return this.timestamps}updateTimestamps(){const t=this.freshTimestampString(),e=this.getUpdatedAtColumn();e&&!this.isDirty(e)&&this.setUpdatedAt(t);const s=this.getCreatedAtColumn();return this.exists||!s||this.isDirty(s)||this.setCreatedAt(t),this}getCreatedAtColumn(){return this.constructor.CREATED_AT}getUpdatedAtColumn(){return this.constructor.UPDATED_AT}setCreatedAt(t){return this.attributes[this.getCreatedAtColumn()]=t,this}setUpdatedAt(t){return this.attributes[this.getUpdatedAtColumn()]=t,this}freshTimestamp(){const t=new Date;return t.setMilliseconds(0),t}freshTimestampString(){return this.fromDateTime(this.freshTimestamp())}},Tt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=X(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=f(this.hidden,e),this}makeHidden(t,...e){const s=X([...t,...e]);return this.hidden.length>0&&(this.hidden=[...this.hidden,...s]),this}getHidden(){return this.hidden}getVisible(){return this.visible}setHidden(t){return this.hidden=t,this}setVisible(t){return this.visible=t,this}},St=t=>class extends t{useUniqueIds=!1;usesUniqueIds(){return this.useUniqueIds}uniqueIds(){return[]}newUniqueId(){return null}setUniqueIds(){const t=this.uniqueIds();for(const e of t)null!==this[e]&&void 0!==this[e]||(this[e]=this.newUniqueId())}},Dt=Z(class{},ft,Tt,At,xt,Ct,wt,St),qt=class t extends Dt{primaryKey="id";builder=null;table=null;keyType="int";incrementing=!0;withCount=[];perPage=15;static globalScopes={};static pluginInitializers={};static _booted={};static resolver;connection=null;eagerLoad={};exists=!1;with=[];trx=null;constructor(t={}){return super(),this.bootIfNotBooted(),this.initializePlugins(),this.syncOriginal(),this.fill(t),this.asProxy()}static query(t=null){return(new this).newQuery(t)}static on(t=null){const e=new this;return e.setConnection(t),e.newQuery()}static init(t={}){return new this(t)}static extend(t,e){t(this,e)}static make(t={}){const e=new this;for(const s in t)if("function"!=typeof e[J(s)])e.setAttribute(s,t[s]);else{const i=e[J(s)](),r=i.getRelated().constructor;i instanceof Kt||i instanceof rt?e.setRelation(s,r.make(t[s])):(i instanceof Pt||i instanceof lt)&&Array.isArray(t[s])&&e.setRelation(s,new nt(t[s].map(t=>r.make(t))))}return e}getConstructor(){return this.constructor}bootIfNotBooted(){void 0===this.constructor._booted[this.constructor.name]&&(this.constructor._booted[this.constructor.name]=!0,this.constructor.booting(),this.initialize(),this.constructor.boot(),this.constructor.booted())}static booting(){}static boot(){}static booted(){}static setConnectionResolver(t){this.resolver=t}initialize(){}initializePlugins(){if(void 0!==this.constructor.pluginInitializers[this.constructor.name])for(const t of this.constructor.pluginInitializers[this.constructor.name])this[t]()}addPluginInitializer(t){this.constructor.pluginInitializers[this.constructor.name]||(this.constructor.pluginInitializers[this.constructor.name]=[]),this.constructor.pluginInitializers[this.constructor.name].push(t)}newInstance(t={},e=!1){const s=new this.constructor;return s.exists=e,s.setConnection(this.getConnectionName()),s.setTable(this.getTable()),s.fill(t),s}newFromBuilder(t={},e=null){const s=this.newInstance({},!0);return s.setRawAttributes(t,!0),s.setConnection(e||this.getConnectionName()),s}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:"string"==typeof e?t.getAttribute(e):void 0},set:function(t,e,s){return void 0!==t[e]&&"function"!=typeof t?(t[e]=s,t):"string"==typeof e?t.setAttribute(e,s):t}})}getKey(){return this.getAttribute(this.getKeyName())}getKeyName(){return this.primaryKey}getForeignKey(){return tt(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||M(tt(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):Ft.connection(this.connection)}setConnection(t){return this.connection=t,this}getKeyType(){return this.keyType}newQuery(t=null){return this.addGlobalScopes(this.newQueryWithoutScopes(t))}newQueryWithoutScopes(t=null){return this.newModelQuery(t).with(this.with).withCount(this.withCount)}newModelQuery(t=null){return new mt(t||this.getConnection()).setModel(this)}addGlobalScopes(t){const e=this.getGlobalScopes();for(const s in e){const i=e[s];t.withGlobalScope(s,i)}return t}hasNamedScope(t){return"function"==typeof this[z(t)]}callNamedScope(t,e){return this[z(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new nt(t)}async load(...t){const e=this.constructor.query().with(...t);return await e.eagerLoadRelations([this]),this}async loadAggregate(t,e,s=null){return console.log(t),await new nt([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=X(t),await this.loadAggregate(t,"*","count")}async loadMax(t,e){return await this.loadAggregate(t,e,"max")}async loadMin(t,e){return await this.loadAggregate(t,e,"min")}async loadSum(t,e){return await this.loadAggregate(t,e,"sum")}async increment(t,e=1,s={},i={}){return await this.incrementOrDecrement(t,e,s,"increment",i)}async decrement(t,e=1,s={},i={}){return await this.incrementOrDecrement(t,e,s,"decrement",i)}async incrementOrDecrement(t,e,s,i,r){const n=this.newModelQuery(r.client);if(!this.exists)return await n[i](t,e,s);this.attributes[t]=this[t]+("increment"===i?e:-1*e);for(const t in s)this.attributes[t]=s[t];return await this.execHooks("updating",r),await Y(await n.where(this.getKeyName(),this.getKey())[i](t,e,s),async()=>{this.syncChanges(),await this.execHooks("updated",r),this.syncOriginalAttribute(t)})}toData(){return p(this.attributesToData(),this.relationsToData())}toJSON(){return this.toData()}toJson(...t){return JSON.stringify(this.toData(),...t)}toString(){return this.toJson()}fill(t){for(const e in t)this.setAttribute(e,t[e]);return this}transacting(t){return this.trx=t,this}trashed(){return null!==this[this.getDeletedAtColumn()]}getIncrementing(){return this.incrementing}setIncrementing(t){return this.incrementing=t,this}async save(t={}){const e=this.newModelQuery(t.client);let s;if(await this.execHooks("saving",t),this.exists)if(!1===this.isDirty())s=!0;else{await this.execHooks("updating",t),this.usesTimestamps()&&this.updateTimestamps();const i=this.getDirty();Object.keys(i).length>0&&(await e.where(this.getKeyName(),this.getKey()).query.update(i),this.syncChanges(),await this.execHooks("updated",t)),s=!0}else{this.usesUniqueIds()&&this.setUniqueIds(),await this.execHooks("creating",t),this.usesTimestamps()&&this.updateTimestamps();const i=this.getAttributes();if(this.getIncrementing()){const t=this.getKeyName(),s=await e.insert([i],[t]);this.setAttribute(t,s[0]?.[t]||s[0])}else Object.keys(i).length>0&&await e.insert(i);this.exists=!0,await this.execHooks("created",t),s=!0}return s&&(await this.execHooks("saved",t),this.syncOriginal()),s}async update(t={},e={}){if(!this.exists)return!1;for(const e in t)this[e]=t[e];return await this.save(e)}async delete(t={}){return await this.execHooks("deleting",t),await this.performDeleteOnModel(t),await this.execHooks("deleted",t),!0}async performDeleteOnModel(t={}){await this.setKeysForSaveQuery(this.newModelQuery(t.client)).delete(),this.exists=!1}setKeysForSaveQuery(t){return t.where(this.getKeyName(),"=",this.getKey()),t}async forceDelete(t={}){return await this.delete(t)}fresh(){if(this.exists)return this.constructor.query().where(this.getKeyName(),this.getKey()).first()}async refresh(){if(!this.exists)return Promise.resolve(void 0);const t=await this.constructor.query().where(this.getKeyName(),this.getKey()).first();return this.attributes={...t.attributes},await this.load(D(this.relations).reject(t=>t instanceof Et).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):Et.fromAttributes(t,e,s,i)}qualifyColumn(t){return t.includes(".")?t:`${this.getTable()}.${t}`}getQualifiedKeyName(){return this.qualifyColumn(this.getKeyName())}async push(t={}){if(!await this.save(t))return!1;for(const e in this.relations){let s=this.relations[e];s=s instanceof nt?s.all():[s];for(const e of s)if(!await e.push(t))return!1}return!0}is(e){return e&&e instanceof t&&this.getKey()===e.getKey()&&this.getTable()===e.getTable()&&this.getConnectionName()===e.getConnectionName()}isNot(t){return!this.is(t)}},Et=class extends qt{incrementing=!1;guarded=[];pivotParent=null;foreignKey=null;relatedKey=null;setPivotKeys(t,e){return this.foreignKey=t,this.relatedKey=e,this}static fromRawAttributes(t,e,s,i=!1){const r=this.fromAttributes(t,{},s,i);return r.timestamps=r.hasTimestampAttributes(e),r.attributes=e,r.exists=i,r}static fromAttributes(t,e,s,i=!1){const r=new this;return r.timestamps=r.hasTimestampAttributes(e),r.setConnection(t.connection).setTable(s).fill(e).syncOriginal(),r.pivotParent=t,r.exists=i,r}hasTimestampAttributes(t=null){return void 0!==(t||this.attributes)[this.constructor.CREATED_AT]}},Mt=qt,kt=class{},_t=class t extends kt{model;schema;connector;constructor(t,e){return super(),this.connector=e(t),this.asProxy()}asProxy(){return new Proxy(this,{get:function(t,e){return void 0!==t[e]?t[e]:["destroy","schema"].includes(e)?t.connector.schema:["select","from","where","orWhere","whereColumn","whereRaw","whereNot","orWhereNot","whereIn","orWhereIn","whereNotIn","orWhereNotIn","whereNull","orWhereNull","whereNotNull","orWhereNotNull","whereExists","orWhereExists","whereNotExists","orWhereNotExists","whereBetween","orWhereBetween","whereNotBetween","orWhereNotBetween","whereLike","orWhereLike","whereILike","orWhereILike","whereJsonObject","whereJsonPath","whereJsonSupersetOf","whereJsonSubsetOf","join","joinRaw","leftJoin","leftOuterJoin","rightJoin","rightOuterJoin","crossJoin","transacting","groupBy","groupByRaw","returning","having","havingRaw","havingBetween","limit","offset","orderBy","orderByRaw","union","insert","forUpdate","forShare","distinct","clearOrder","clear","clearSelect","clearWhere","clearHaving","clearGroup"].includes(e)?(...s)=>(t.connector[e](...s),t.asProxy()):t.connector[e]},set:function(t,e,s){return void 0!==t[e]?(t[e]=s,t):(t.connector[e]=s,t)}})}async beginTransaction(){return await this.connector.transaction()}table(e){const s=this.connector.table(e);return new t(null,()=>s)}transaction(e){return e?this.connector.transaction(s=>e(new t(null,()=>s))):e}async find(t,e=["*"]){return await this.connector.where("id",t).first(...e)}async get(t=["*"]){return await this.connector}async exists(){return null!==await this.connector.first()}skip(...t){return this.offset(...t)}take(...t){return this.limit(...t)}async chunk(t,e){if(0===this.connector._statements.filter(t=>"order"===t.grouping).length)throw new Error("You must specify an orderBy clause when using this function.");let s,i=1;do{const r=this.clone(),n=await r.forPage(i,t).get();if(s=n.length,0==s)break;if(!1===await e(n,i))return!1;i++}while(s===t);return!0}async paginate(t=1,e=15){const s=this.clone(),i=await s.clearOrder().count("*");let r;if(i>0){const s=(t-1)*e;this.take(e).skip(s),r=await this.get()}else r=[];return new gt(r,parseInt(i),e,t)}forPage(t=1,e=15){return this.offset((t-1)*e).limit(e)}toSQL(...t){return this.connector.toSQL(...t)}async count(t){const[{aggregate:e}]=await this.connector.count(t,{as:"aggregate"});return Number(e)}async min(t){const[{aggregate:e}]=await this.connector.min(t,{as:"aggregate"});return Number(e)}async max(t){const[{aggregate:e}]=await this.connector.max(t,{as:"aggregate"});return Number(e)}async sum(t){const[{aggregate:e}]=await this.connector.sum(t,{as:"aggregate"});return Number(e)}async avg(t){const[{aggregate:e}]=await this.connector.avg(t,{as:"aggregate"});return Number(e)}clone(){const e=this.connector.clone();return new t(null,()=>e)}async delete(){return await this.connector.delete()}async insert(...t){return await this.connector.insert(...t)}async update(...t){return await this.connector.update(...t)}destroy(...t){return this.connector.destroy(...t)}get _statements(){return this.connector._statements}get _single(){return this.connector._single}get from(){return this.connector.from}},Ft=class t{static connectorFactory=null;static instance=null;manager;connections;models;constructor(){this.manager={},this.connections={},this.models={}}getConstructor(){return this.constructor}static getInstance(){return null===this.instance&&(this.instance=new t),this.instance}static fire(t=null){return this.getInstance().getConnection(t)}static connection(t=null){return this.fire(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??S}static addConnection(t,e="default"){return this.getInstance().addConnection(t,e)}static beginTransaction(t=null){return this.getInstance().beginTransaction(t)}static transaction(t,e=null){return this.getInstance().transaction(t,e)}static table(t,e=null){return this.getInstance().table(t,e)}static schema(t=null){return this.getInstance().schema(t)}static async destroyAll(){await this.getInstance().destroyAll()}static createModel(t,e){return this.getInstance().createModel(t,e)}connection(t=null){return this.getConnection(t)}getConnection(e=null){if(e=e||"default",void 0===this.manager[e]){const s=new _t(this.connections[e],t.getConnectorFactory());this.manager[e]=s}return this.manager[e]}addConnection(t,e="default"){this.connections[e]={...t,connection:{...t.connection,dateStrings:!0,typeCast:function(t,e){return"JSON"===t.type?t.string("utf8"):e()}}}}static async autoLoad(t=!0){let e;const s=u.resolve("arquebus.config.js"),i=u.resolve("arquebus.config.ts"),r=this.getInstance();if(k(s))return e=(await import(s)).default,t&&r.addConnection(e,e.client),e;if(k(i)){if("production"!==process.env.NODE_ENV)return e=(await import(i)).default,t&&r.addConnection(e,e.client),e;throw new Error("arquebus.config.ts found in production without build step")}return{}}beginTransaction(t=null){return this.connection(t).beginTransaction()}transaction(t,e=null){return this.connection(e).transaction(t)}table(t,e=null){return this.connection(e).table(t)}schema(t=null){return this.connection(t).schema}async destroyAll(){await Promise.all(Object.values(this.manager).map(t=>t?.destroy()))}createModel(t,e={}){let s=qt;if("plugins"in e&&(s=Z(s,...e.plugins??[])),this.models={...this.models,[t]:class extends s{table=e?.table??null;connection=e?.connection??null;timestamps=e?.timestamps??!0;primaryKey=e?.primaryKey??"id";keyType=e?.keyType??"int";incrementing=e?.incrementing??!0;with=e?.with??[];casts=e?.casts??{};static CREATED_AT=e?.CREATED_AT??"created_at";static UPDATED_AT=e?.UPDATED_AT??"updated_at";static DELETED_AT=e?.DELETED_AT??"deleted_at"}},"attributes"in e)for(const s in e.attributes){if(e.attributes[s]instanceof et==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[G(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[J(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[z(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},It=class{constructor(t,e,s){this.basePath=t,this.customStubPath=e,this.callback=s??((t="")=>{})}callback;async run(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t);await this.prepareDatabase(r);const n=await j.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path);await r.setOutput(!0).run(n,{step:e.step,pretend:e.pretend}),s&&await i.destroyAll()}async rollback(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t),n=await j.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path);await r.setOutput(!0).rollback(n,{step:e.step||0,pretend:e.pretend,batch:e.batch||0}),s&&await i.destroyAll()}async prepareDatabase(t){await t.repositoryExists()||(this.callback("INFO: Preparing database.","info"),this.callback("INFO: Creating migration table...","info"),await t.repository.createRepository(),this.callback("SUCCESS: Migration table created successfully.","success"))}async status(t,e={},s=!1){const{arquebus:i,migrator:r}=await this.setupConnection(t),n=async()=>await r.getMigrationFiles(await j.getMigrationPaths(this.basePath??process.cwd(),r,t.migrations.path,e.path));await r.repositoryExists()||this.callback("ERROR: Migration table does not exist.","error");const a=await r.repository.getRan(),o=await r.getRepository().getMigrationBatches(),h=await async function(t,e){const s=await n();return Object.values(s).map(s=>{const i=r.getMigrationName(s);return{name:i,ran:t.includes(i),batch:t.includes(i)?e[i]:null}})}(a,o);return s&&await i.destroyAll(),h}async setupConnection(t){const e=t?.migrations?.table||"migrations";!0!==t.skipConnection&&(Ft.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{Ft.addConnection(e,t)}));const s=new $(Ft,e),i=new L(s,Ft);return{arquebus:Ft,migrator:i}}},Ot=class{constructor(t,e="js"){this.customStubPath=t,this.type=e}postCreate=[];async create(t,e,s,r=!1){const n=this.getStub(s,r),a=this.getPath(t,e);return await this.ensureDirectoryExists(u.dirname(a)),await i.writeFile(a,this.populateStub(n,s)),await this.firePostCreateHooks(s,a),a}async publish(t,e){const s=await i.readdir(this.customStubPath??"");await this.ensureDirectoryExists(t);for(const r of s){const s=u.join(this.customStubPath??"",r),n=u.join(t,r);await i.copyFile(s,n),e&&e(r,s,n)}}getStub(t,e=!1){let s;if(t)if(e){const t=u.join(this.customStubPath??"",`migration.create-${this.type}.stub`);s=k(t)?t:this.stubPath(`/migration.create-${this.type}.stub`)}else{const t=u.join(this.customStubPath??"",`migration.update-${this.type}.stub`);s=k(t)?t:this.stubPath(`/migration.update-${this.type}.stub`)}else{const t=u.join(this.customStubPath??"",`migration-${this.type}.stub`);console.log("\n",t,"---"),s=k(t)?t:this.stubPath(`/migration-${this.type}.stub`)}return _(s,"utf-8")}populateStub(t,e){return null!==e&&(t=t.replace(/DummyTable|{{\s*table\s*}}/g,e)),t}getClassName(t){return t.replace(/_+([a-z])/g,(t,e)=>e.toUpperCase())}getPath(t,e){const s=T().format("YYYY_MM_DD_HHmmss");return u.join(e,`${s}_${t}.${this.type}`)}async firePostCreateHooks(t,e){for(const s of this.postCreate)await s(t,e)}afterCreate(t){this.postCreate.push(t)}async ensureDirectoryExists(t){await i.mkdir(t,{recursive:!0})}stubPath(t=""){const e=this.getDirname(import.meta);return u.join(e,"stubs",t)}getDirname(t){if("undefined"!=typeof __dirname)return __dirname;if(t&&t.url)return l(F(t.url));throw new Error("Unable to determine dirname")}},Qt="0.3.0";(class i{cwd;output=j.output();config={};basePath="";modulePath;configPath;modulePackage;constructor(t){this.basePath=t??("true"===process.env.TEST?"test/cli":"")}terminateNotFound(){this.output.error(`ERROR: Arquebus config not found. Run ${h.italic.black.bgGray("arquebus init")} first.`)}static init(){I({quiet:!0});const t=new i;Promise.all([t.loadPaths(),t.loadConfig()]).then(([t,e])=>e.run())}async loadPaths(){this.cwd=u.join(process.cwd(),this.basePath),this.configPath=j.findUpConfig(this.cwd,"arquebus.config",["js","ts","cjs"])??void 0,this.modulePath=j.findModulePkg("@h3ravel/arquebus",this.cwd)??"";try{this.modulePackage=await import(u.join(this.modulePath,"package.json"))}catch{this.modulePackage={version:"N/A"}}return this}async loadConfig(){try{this.config=(await import(this.configPath??"----")).default,this.config.migrations?.path&&await r(u.join(this.cwd,this.config.migrations?.path),{recursive:!0})}catch{this.config={}}return this}async run(){const i=["Arquebus CLI version:",h.green(Qt)].join(" "),o=["Arquebus Local version:",h.green(this.modulePackage.version||"None")].join(" ");t.name("arquebus").version(`${i}\n${o}`),t.command("init").description("Create a fresh Arquebus config.").addArgument(new e("[type]","Type of config to generate.").choices(["js","ts"]).default("js","generates a js config")).action(async t=>{this.modulePath||this.output.error(["ERROR: No local arquebus install found"," Try running: npm install arquebus --save"]),this.configPath&&this.output.error(`ERROR: ${this.configPath} already exists`);try{const e=`./arquebus.config.${t}`,s=await n(u.join(this.modulePath,`/src/stubs/arquebus.config-${t}.stub`),{encoding:"utf8"});await a(u.join(this.cwd,e),s),this.output.success(`Initialized: Arquebus has been initialized as ${e}`)}catch(t){this.output.error("ERROR: "+t)}}),t.command("migrate:make <name>").description("Create a new migration file.").addOption(new s("-l, --type [string]","Type of migration file to generate.").choices(["js","ts"]).default("js","generates a js migration file")).option("-t, --table [string]","The table to migrate").option("-c, --create [string]","The table to be created").option("-p, --path [path]","The path to the migrations directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();try{t=R(t);const s=u.join(this.cwd,e.path??this.config.migrations?.path??"./migrations");let i=e.table,r=e.create||!1;if(i||"string"!=typeof r||(i=r,r=!0),!i){const e=W.guess(t);i=e[0],r=!!e[1]}this.output.info("INFO: Creating Migration");const n=new Ot(void 0,e.type),a=await n.create(t,s,i,r);this.output.success(`INFO: Migration Created \n ${h.gray(u.basename(a))}`,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]","The path to the migrations directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();try{const s=j.findModulePkg(t)??"",i=u.join(this.cwd,e.path??this.config.migrations?.path??"./migrations"),r=await import(u.join(s,"package.json"));s||this.output.error(`ERROR: package ${t} not found`);const n=new Ot(u.join(s,r.migrations??"migrations"));this.output.info(`INFO: Publishing migrations from ${h.italic.gray(r.name+"@"+r.version)}`),await n.publish(i,t=>{j.twoColumnDetail(t,h.green("PUBLISHED"))})}catch(t){this.output.error("ERROR: "+t)}}),t.command("migrate").description("Run all pending migrations.").option("-s, --step [number]","Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?u.join(this.cwd,t.path):this.cwd;try{await new It(e).run(this.config,t,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]","The number of migrations to be reverted.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?u.join(this.cwd,t.path):this.cwd;try{await new It(e,void 0,(t,e)=>{e&&this.output[e](t)}).rollback(this.config,t,!0)}catch(t){this.output.error("ERROR: "+t)}}),t.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]","The path to the migrations directory.").action(async t=>{this.configPath||this.terminateNotFound();const e=t.path?u.join(this.cwd,t.path):this.cwd;try{const s=await new It(e,void 0,(t,e)=>{e&&this.output[e](t)}).status(this.config,t,!0);s.length>0?(j.twoColumnDetail(h.gray("Migration name"),h.gray("Batch / Status")),s.forEach(t=>{const e=t.ran?`[${t.batch}] ${h.green("Ran")}`:h.yellow("Pending");j.twoColumnDetail(t.name,e)})):console.log("No migrations found")}catch(t){this.output.error("ERROR: "+t)}}),t.command("model:make <name>").description("Create a new Model file.").addOption(new s("-l, --type [string]","Type of migration file to generate.").choices(["js","ts"]).default("js","generates a js migration file")).option("--force","Force creation if model already exists.",!1).option("-p, --path [path]","The path to the models directory.").action(async(t,e)=>{this.configPath||this.terminateNotFound();const s=u.join(this.cwd,e.path??this.config.models?.path??"./models",t.toLowerCase()+"."+e.type);try{!e.force&&await j.fileExists(s)&&this.output.error("ERROR: Model already exists."),await r(u.dirname(s),{recursive:!0});const i=u.join(this.modulePath,`src/stubs/model-${e.type}.stub`);let o=await n(i,"utf-8");o=o.replace(/{{ name }}/g,t),await a(s,o),this.output.success(`Created Model: ${s}`)}catch(t){this.output.error("ERROR: "+t)}}),await t.parseAsync(process.argv),process.exit(0)}}).init();
2
+ import "node:module";
3
+ import { Argument, Option, program } from "commander";
4
+ import { access } from "fs/promises";
5
+ import chalk from "chalk";
6
+ import escalade from "escalade/sync";
7
+ import path from "path";
8
+ import resolveFrom from "resolve-from";
9
+ import fs, { mkdir, readFile, writeFile } from "node:fs/promises";
10
+ import { assign, camel, diff, flat, get, isArray, isEmpty, isEqual, isString, omit, pick, set, snake, trim } from "radashi";
11
+ import advancedFormat from "dayjs/plugin/advancedFormat.js";
12
+ import dayjs from "dayjs";
13
+ import Knex from "knex";
14
+ import collect, { Collection, collect as collect$1 } from "collect.js";
15
+ import pluralize from "pluralize";
16
+ import { existsSync } from "fs";
17
+ import { existsSync as existsSync$1, readFileSync } from "node:fs";
18
+ import { dirname } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { config } from "dotenv";
21
+
22
+ //#region rolldown:runtime
23
+ var __defProp = Object.defineProperty;
24
+ var __export = (all) => {
25
+ let target = {};
26
+ for (var name$1 in all) __defProp(target, name$1, {
27
+ get: all[name$1],
28
+ enumerable: true
29
+ });
30
+ return target;
31
+ };
32
+
33
+ //#endregion
34
+ //#region src/cli/utils.ts
35
+ const join = path.join;
36
+ var Utils = class {
37
+ /**
38
+ * Wraps text with chalk
39
+ *
40
+ * @param txt
41
+ * @param color
42
+ * @returns
43
+ */
44
+ static textFormat(txt, color) {
45
+ return String(txt).split(":").map((e, i, a) => i == 0 && a.length > 1 ? color(" " + e + ": ") : e).join("");
46
+ }
47
+ /**
48
+ * Ouput formater object
49
+ *
50
+ * @returns
51
+ */
52
+ static output() {
53
+ return {
54
+ success: (msg, exit = false) => {
55
+ console.log(chalk.green("✓"), this.textFormat(msg, chalk.bgGreen), "\n");
56
+ if (exit) process.exit(0);
57
+ },
58
+ info: (msg, exit = false) => {
59
+ console.log(chalk.blue("ℹ"), this.textFormat(msg, chalk.bgBlue), "\n");
60
+ if (exit) process.exit(0);
61
+ },
62
+ error: (msg, exit = true) => {
63
+ if (msg instanceof Error) {
64
+ if (msg.message) console.error(chalk.red("✖"), this.textFormat(msg.message, chalk.bgRed));
65
+ console.error(chalk.red(`${msg.detail ? `${msg.detail}\n` : ""}${msg.stack}`), "\n");
66
+ } else console.error(chalk.red("✖"), this.textFormat(msg, chalk.bgRed), "\n");
67
+ if (exit) process.exit(1);
68
+ },
69
+ quiet: () => {
70
+ process.exit(0);
71
+ }
72
+ };
73
+ }
74
+ static findModulePkg(moduleId, cwd) {
75
+ const parts = moduleId.replace(/\\/g, "/").split("/");
76
+ let packageName = "";
77
+ if (parts.length > 0 && parts[0][0] === "@") packageName += parts.shift() + "/";
78
+ packageName += parts.shift();
79
+ const packageJson = path.join(packageName, "package.json");
80
+ const resolved = resolveFrom.silent(cwd ?? process.cwd(), packageJson);
81
+ if (!resolved) return;
82
+ return path.join(path.dirname(resolved), parts.join("/"));
83
+ }
84
+ static async getMigrationPaths(cwd, migrator, defaultPath, path$1) {
85
+ if (path$1) return [join(cwd, path$1)];
86
+ return [...migrator.getPaths(), join(cwd, defaultPath)];
87
+ }
88
+ static twoColumnDetail(name$1, value) {
89
+ const regex = /\x1b\[\d+m/g;
90
+ const width = Math.min(process.stdout.columns, 100);
91
+ const dots = Math.max(width - name$1.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
92
+ return console.log(name$1, chalk.gray(".".repeat(dots)), value);
93
+ }
94
+ /**
95
+ * Check if file exists
96
+ *
97
+ * @param path
98
+ * @returns
99
+ */
100
+ static async fileExists(path$1) {
101
+ try {
102
+ await access(path$1);
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+ static findUpConfig(cwd, name$1, extensions) {
109
+ return escalade(cwd, (_dir, names) => {
110
+ for (const ext of extensions) {
111
+ const filename = `${name$1}.${ext}`;
112
+ if (names.includes(filename)) return filename;
113
+ }
114
+ return false;
115
+ });
116
+ }
117
+ };
118
+ var TableGuesser = class TableGuesser {
119
+ static CREATE_PATTERNS = [/^create_(\w+)_table$/, /^create_(\w+)$/];
120
+ static CHANGE_PATTERNS = [/.+_(to|from|in)_(\w+)_table$/, /.+_(to|from|in)_(\w+)$/];
121
+ static guess(migration) {
122
+ for (const pattern of TableGuesser.CREATE_PATTERNS) {
123
+ const matches = migration.match(pattern);
124
+ if (matches) return [matches[1], true];
125
+ }
126
+ for (const pattern of TableGuesser.CHANGE_PATTERNS) {
127
+ const matches = migration.match(pattern);
128
+ if (matches) return [matches[2], false];
129
+ }
130
+ return [];
131
+ }
132
+ };
133
+
134
+ //#endregion
135
+ //#region src/migrations/migration-repository.ts
136
+ var MigrationRepository = class {
137
+ resolver;
138
+ table;
139
+ connection = null;
140
+ constructor(resolver, table) {
141
+ this.resolver = resolver;
142
+ this.table = table;
143
+ }
144
+ async getRan() {
145
+ return await this.getTable().orderBy("batch", "asc").orderBy("migration", "asc").pluck("migration");
146
+ }
147
+ async getMigrations(steps) {
148
+ return await this.getTable().where("batch", ">=", "1").orderBy("batch", "desc").orderBy("migration", "desc").take(steps).get();
149
+ }
150
+ async getMigrationsByBatch(batch) {
151
+ return await this.getTable().where("batch", batch).orderBy("migration", "desc").get();
152
+ }
153
+ async getLast() {
154
+ return await this.getTable().where("batch", await this.getLastBatchNumber()).orderBy("migration", "desc").get();
155
+ }
156
+ async getMigrationBatches() {
157
+ const migrations = await this.getTable().select("batch", "migration").orderBy("batch", "asc").orderBy("migration", "asc").get();
158
+ const migrationBatches = {};
159
+ migrations.map((migration) => {
160
+ migrationBatches[migration.migration] = migration.batch;
161
+ });
162
+ return migrationBatches;
163
+ }
164
+ async log(file, batch) {
165
+ await this.getTable().insert({
166
+ migration: file,
167
+ batch
168
+ });
169
+ }
170
+ async delete(migration) {
171
+ await this.getTable().where("migration", migration.migration).delete();
172
+ }
173
+ async getNextBatchNumber() {
174
+ return await this.getLastBatchNumber() + 1;
175
+ }
176
+ async getLastBatchNumber() {
177
+ return await this.getTable().max("batch");
178
+ }
179
+ async createRepository() {
180
+ await this.getConnection().schema.createTable(this.table, function(table) {
181
+ table.increments("id");
182
+ table.string("migration");
183
+ table.integer("batch");
184
+ });
185
+ }
186
+ repositoryExists() {
187
+ return this.getConnection().schema.hasTable(this.table);
188
+ }
189
+ async deleteRepository() {
190
+ await this.getConnection().schema.drop(this.table);
191
+ }
192
+ getTable() {
193
+ return this.getConnection().table(this.table);
194
+ }
195
+ getConnection() {
196
+ return this.resolver.connection(this.connection);
197
+ }
198
+ setSource(name$1) {
199
+ this.connection = name$1;
200
+ }
201
+ };
202
+ var migration_repository_default = MigrationRepository;
203
+
204
+ //#endregion
205
+ //#region src/migrations/migrator.ts
206
+ async function glob(folderPath) {
207
+ const files$1 = await fs.readdir(folderPath);
208
+ const allFiles = [];
209
+ for (const file of files$1) {
210
+ const filePath = `${folderPath}/${file}`;
211
+ const stats = await fs.stat(filePath);
212
+ if (stats.isFile()) allFiles.push(filePath);
213
+ else if (stats.isDirectory()) {
214
+ const subFiles = await glob(filePath);
215
+ allFiles.push(...subFiles);
216
+ }
217
+ }
218
+ return allFiles;
219
+ }
220
+ var Migrator = class {
221
+ events = null;
222
+ repository;
223
+ files;
224
+ resolver;
225
+ connection;
226
+ paths = [];
227
+ output = null;
228
+ constructor(repository$1, resolver = null, files$1 = null, dispatcher = null) {
229
+ this.repository = repository$1;
230
+ this.files = files$1;
231
+ this.resolver = resolver;
232
+ this.events = dispatcher;
233
+ }
234
+ async run(paths = [], options = {}) {
235
+ const files$1 = await this.getMigrationFiles(paths);
236
+ const ran = await this.repository.getRan();
237
+ const migrations = this.pendingMigrations(files$1, ran);
238
+ await this.runPending(migrations, options);
239
+ return migrations;
240
+ }
241
+ pendingMigrations(files$1, ran) {
242
+ return Object.values(files$1).filter((file) => !ran.includes(this.getMigrationName(file)));
243
+ }
244
+ async runPending(migrations, options = {}) {
245
+ if (migrations.length === 0) {
246
+ this.write("Nothing to migrate");
247
+ return;
248
+ }
249
+ let batch = await this.repository.getNextBatchNumber();
250
+ const pretend = options.pretend || false;
251
+ const step = options.step || false;
252
+ this.write("Running migrations.");
253
+ for (const file of migrations) {
254
+ await this.runUp(file, batch, pretend);
255
+ if (step) batch++;
256
+ }
257
+ }
258
+ async runUp(file, batch, _pretend) {
259
+ const migration = await this.resolvePath(file);
260
+ const name$1 = this.getMigrationName(file);
261
+ await this.writeTask(name$1, () => this.runMigration(migration, "up"));
262
+ await this.repository.log(name$1, batch);
263
+ }
264
+ async runDown(file, migration, _pretend) {
265
+ const instance = await this.resolvePath(file);
266
+ const name$1 = this.getMigrationName(file);
267
+ await this.writeTask(name$1, () => this.runMigration(instance, "down"));
268
+ await this.repository.delete(migration);
269
+ }
270
+ async rollback(paths = [], options = {}) {
271
+ const migrations = await this.getMigrationsForRollback(options);
272
+ if (migrations.length === 0) {
273
+ this.write("Nothing to rollback.");
274
+ return [];
275
+ }
276
+ return await this.rollbackMigrations(migrations, paths, options);
277
+ }
278
+ async getMigrationsForRollback(options) {
279
+ if (options.step && options.step > 0) return await this.repository.getMigrations(options.step);
280
+ if (options.batch && options.batch > 0) return await this.repository.getMigrationsByBatch(options.batch);
281
+ return await this.repository.getLast();
282
+ }
283
+ async rollbackMigrations(migrations, paths, options) {
284
+ const rolledBack = [];
285
+ const files$1 = await this.getMigrationFiles(paths);
286
+ this.write("Rolling back migrations.");
287
+ for (const migration of migrations) {
288
+ const file = files$1[migration.migration];
289
+ if (!file) {
290
+ this.writeTwoColumns(migration.migration, chalk.yellow("Migration not found"));
291
+ continue;
292
+ }
293
+ rolledBack.push(file);
294
+ await this.runDown(file, migration, options.pretend || false);
295
+ }
296
+ return rolledBack;
297
+ }
298
+ reset(_paths = [], _pretend = false) {
299
+ this.repository.getRan().then((r) => r.reverse());
300
+ return [];
301
+ }
302
+ resetMigrations(migrations, paths, pretend = false) {
303
+ return this.rollbackMigrations(migrations, paths, { pretend });
304
+ }
305
+ async runMigration(migration, method) {
306
+ const connection = this.resolveConnection(migration.getConnection());
307
+ const callback = async (trx) => {
308
+ if (typeof migration[method] === "function") await this.runMethod(trx, migration, method);
309
+ };
310
+ if (migration.withinTransaction) await connection.transaction(callback);
311
+ else await callback(connection);
312
+ }
313
+ async runMethod(connection, migration, method) {
314
+ var _migration$method;
315
+ await ((_migration$method = migration[method]) === null || _migration$method === void 0 ? void 0 : _migration$method.call(migration, connection.schema, connection));
316
+ }
317
+ async resolvePath(filePath) {
318
+ try {
319
+ return new (await (import(filePath))).default();
320
+ } catch {}
321
+ return new class {}();
322
+ }
323
+ getMigrationClass(migrationName) {
324
+ return migrationName.split("_").slice(4).map((str) => str.charAt(0).toUpperCase() + str.slice(1)).join("");
325
+ }
326
+ async getMigrationFiles(paths) {
327
+ const files$1 = [];
328
+ for (const p of paths) {
329
+ if (p.endsWith(".js") || p.endsWith(".ts")) {
330
+ files$1.push(p);
331
+ continue;
332
+ }
333
+ files$1.push(...await glob(p));
334
+ }
335
+ return files$1.filter(Boolean).reduce((result, file) => {
336
+ result[this.getMigrationName(file)] = file;
337
+ return result;
338
+ }, {});
339
+ }
340
+ getMigrationName(filePath) {
341
+ return path.basename(filePath).replace(".js", "");
342
+ }
343
+ path(p) {
344
+ this.paths = Array.from(new Set([...this.paths, p]));
345
+ }
346
+ getPaths() {
347
+ return this.paths;
348
+ }
349
+ getConnection() {
350
+ return this.connection;
351
+ }
352
+ resolveConnection(connection) {
353
+ return this.resolver.connection(connection || this.connection);
354
+ }
355
+ getRepository() {
356
+ return this.repository;
357
+ }
358
+ repositoryExists() {
359
+ return this.repository.repositoryExists();
360
+ }
361
+ async hasRunAnyMigrations() {
362
+ const ran = await this.repository.getRan();
363
+ return await this.repositoryExists() && ran.length > 0;
364
+ }
365
+ deleteRepository() {
366
+ this.repository.deleteRepository();
367
+ }
368
+ setOutput(output) {
369
+ this.output = output;
370
+ return this;
371
+ }
372
+ write(...args) {
373
+ if (this.output) console.log(...args);
374
+ }
375
+ writeTwoColumns(name$1, ...args) {
376
+ const value = args.join(" ");
377
+ const regex = /\x1b\[\d+m/g;
378
+ const width = Math.min(process.stdout.columns, 100);
379
+ const dots = Math.max(width - name$1.replace(regex, "").length - value.replace(regex, "").length - 10, 0);
380
+ this.write(name$1, chalk.gray(".".repeat(dots)), value);
381
+ }
382
+ async writeTask(description$1, task) {
383
+ const startTime = process.hrtime();
384
+ let result = false;
385
+ try {
386
+ result = await (task || (() => true))();
387
+ } finally {
388
+ const endTime = process.hrtime(startTime);
389
+ const duration = (endTime[0] * 1e9 + endTime[1]) / 1e6;
390
+ this.writeTwoColumns(chalk.green(description$1), chalk.gray(`${Math.floor(duration)}ms`), result !== false ? chalk.green("✔") : chalk.red("✘"));
391
+ }
392
+ }
393
+ };
394
+ var migrator_default = Migrator;
395
+
396
+ //#endregion
397
+ //#region src/mixin.ts
398
+ var mixin_exports = /* @__PURE__ */ __export({ compose: () => compose$1 });
399
+ /**
400
+ * Compose function that merges multiple classes and mixins
401
+ *
402
+ * @example
403
+ * const SomePlugin = <TBase extends new (...args: any[]) => TGeneric> (Base: TBase) => {
404
+ * return class extends Base {
405
+ * pluginAttribtue = 'plugin'
406
+ * pluginMethod () {
407
+ * return this.pluginAttribtue
408
+ * }
409
+ * }
410
+ * }
411
+ *
412
+ * // Base class
413
+ * class Model {
414
+ * make () {
415
+ * console.log('make')
416
+ * }
417
+ * pluginMethod (id: string) {
418
+ * }
419
+ * }
420
+ *
421
+ * class User extends compose(
422
+ * Model,
423
+ * SomePlugin,
424
+ * ) {
425
+ * relationPosts () {
426
+ * return 'hasMany Posts'
427
+ * }
428
+ * }
429
+ *
430
+ * const user = new User()
431
+ * user.make() // from Model
432
+ * user.pluginMethod() // from SomePlugin
433
+ * user.relationPosts() // from User
434
+ *
435
+ * console.log(user.pluginMethod('w')) // "plugin"
436
+ * console.log(user.pluginMethod()) // "plugin"
437
+ * console.log(user.relationPosts()) // "hasMany Posts"
438
+ *
439
+ * @param Base
440
+ * @param mixins
441
+ * @returns
442
+ */
443
+ function compose$1(Base, ...mixins) {
444
+ /**
445
+ * Apply each mixin or class in sequence
446
+ */
447
+ return mixins.reduce((acc, mixin) => {
448
+ if (typeof mixin === "function" && mixin.prototype)
449
+ /**
450
+ * If it's a class constructor, extend it
451
+ */
452
+ return class extends acc {
453
+ constructor(...args) {
454
+ super(...args);
455
+ /**
456
+ * Copy instance properties from mixin prototype
457
+ */
458
+ Object.getOwnPropertyNames(mixin.prototype).forEach((name$1) => {
459
+ if (name$1 !== "constructor") Object.defineProperty(this, name$1, Object.getOwnPropertyDescriptor(mixin.prototype, name$1));
460
+ });
461
+ }
462
+ };
463
+ else if (typeof mixin === "function")
464
+ /**
465
+ * If it's a mixin function, call it with current class
466
+ */
467
+ return mixin(acc);
468
+ return acc;
469
+ }, Base);
470
+ }
471
+
472
+ //#endregion
473
+ //#region src/utils.ts
474
+ dayjs.extend(advancedFormat);
475
+ const getRelationName = (relationMethod) => {
476
+ return snake(relationMethod.substring(8));
477
+ };
478
+ const getRelationMethod = (relation) => {
479
+ return camel(`relation_${relation}`);
480
+ };
481
+ const getScopeMethod = (scope) => {
482
+ return camel(`scope_${scope}`);
483
+ };
484
+ const getAttrMethod = (attr) => {
485
+ return camel(`attribute_${attr}`);
486
+ };
487
+ const getGetterMethod = (attr) => {
488
+ return camel(`get_${attr}_attribute`);
489
+ };
490
+ const getSetterMethod = (attr) => {
491
+ return camel(`set_${attr}_attribute`);
492
+ };
493
+ /**
494
+ * Tap into a model a collection instance
495
+ *
496
+ * @param instance
497
+ * @param callback
498
+ * @returns
499
+ */
500
+ const tap = (instance, callback) => {
501
+ const result = callback(instance);
502
+ return result instanceof Promise ? result.then(() => instance) : instance;
503
+ };
504
+ const { compose } = mixin_exports;
505
+ const flattenDeep = (arr) => Array.isArray(arr) ? arr.reduce((a, b) => a.concat(flattenDeep(b)), []) : [arr];
506
+ const snakeCase = (str) => trim(snake(str.replace(/[^a-zA-Z0-9_-]/g, "-")), "_-");
507
+
508
+ //#endregion
509
+ //#region src/casts/attribute.ts
510
+ var Attribute = class Attribute {
511
+ get;
512
+ set;
513
+ withCaching = false;
514
+ withObjectCaching = true;
515
+ constructor({ get: get$1 = null, set: set$1 = null }) {
516
+ this.get = get$1;
517
+ this.set = set$1;
518
+ }
519
+ static make({ get: get$1 = null, set: set$1 = null }) {
520
+ return new Attribute({
521
+ get: get$1,
522
+ set: set$1
523
+ });
524
+ }
525
+ static get(get$1) {
526
+ return new Attribute({ get: get$1 });
527
+ }
528
+ static set(set$1) {
529
+ return new Attribute({ set: set$1 });
530
+ }
531
+ withoutObjectCaching() {
532
+ this.withObjectCaching = false;
533
+ return this;
534
+ }
535
+ shouldCache() {
536
+ this.withCaching = true;
537
+ return this;
538
+ }
539
+ };
540
+ var attribute_default = Attribute;
541
+
542
+ //#endregion
543
+ //#region src/relations/relation.ts
544
+ var Relation = class {
545
+ query;
546
+ parent;
547
+ related;
548
+ eagerKeysWereEmpty = false;
549
+ static constraints = true;
550
+ static selfJoinCount = 0;
551
+ constructor(query, parent) {
552
+ this.query = query;
553
+ this.parent = parent;
554
+ this.related = this.query.model;
555
+ }
556
+ static extend(trait) {
557
+ for (const methodName in trait) this.prototype[methodName] = trait[methodName];
558
+ }
559
+ static noConstraints(callback) {
560
+ const previous = this.constraints;
561
+ this.constraints = false;
562
+ try {
563
+ return callback();
564
+ } finally {
565
+ this.constraints = previous;
566
+ }
567
+ }
568
+ asProxy() {
569
+ return new Proxy(this, { get: function(target, prop) {
570
+ if (typeof target[prop] !== "undefined") return target[prop];
571
+ if (typeof prop === "string") {
572
+ if (typeof target.query[prop] === "function") return (...args) => {
573
+ target.query[prop](...args);
574
+ return target.asProxy();
575
+ };
576
+ }
577
+ } });
578
+ }
579
+ getRelated() {
580
+ return this.related;
581
+ }
582
+ getKeys(models, key) {
583
+ return models.map((model) => key ? model.attributes[key] : model.getKey()).sort();
584
+ }
585
+ getRelationQuery() {
586
+ return this.query;
587
+ }
588
+ whereInEager(whereIn, key, modelKeys, query = null) {
589
+ (query || this.query)[whereIn](key, modelKeys);
590
+ if (modelKeys.length === 0) this.eagerKeysWereEmpty = true;
591
+ }
592
+ whereInMethod(model, key) {
593
+ return "whereIn";
594
+ }
595
+ getEager() {
596
+ return this.eagerKeysWereEmpty ? this.query.getModel().newCollection() : this.get();
597
+ }
598
+ async get(columns = ["*"]) {
599
+ return await this.query.get(columns);
600
+ }
601
+ async first(columns = ["*"]) {
602
+ return await this.query.first(columns);
603
+ }
604
+ async paginate(...args) {
605
+ return await this.query.paginate(...args);
606
+ }
607
+ async count(...args) {
608
+ return await this.query.clearSelect().count(...args);
609
+ }
610
+ toSql() {
611
+ return this.query.toSql();
612
+ }
613
+ addConstraints() {}
614
+ getRelationCountHash(incrementJoinCount = true) {
615
+ return "arquebus_reserved_" + (incrementJoinCount ? this.constructor.selfJoinCount++ : this.constructor.selfJoinCount);
616
+ }
617
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
618
+ return query.select(columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.getExistenceCompareKey());
619
+ }
620
+ getRelationExistenceCountQuery(query, parentQuery) {
621
+ const db = this.related.getConnection();
622
+ return this.getRelationExistenceQuery(query, parentQuery, db.raw("count(*)"));
623
+ }
624
+ getQualifiedParentKeyName() {
625
+ return this.parent.getQualifiedKeyName();
626
+ }
627
+ getExistenceCompareKey() {
628
+ var _this$getQualifiedFor;
629
+ return (_this$getQualifiedFor = this.getQualifiedForeignKeyName) === null || _this$getQualifiedFor === void 0 ? void 0 : _this$getQualifiedFor.call(this);
630
+ }
631
+ };
632
+ var relation_default = Relation;
633
+
634
+ //#endregion
635
+ //#region src/relations/concerns/supports-default-models.ts
636
+ const SupportsDefaultModels = (Relation$1) => {
637
+ return class extends Relation$1 {
638
+ _withDefault;
639
+ withDefault(callback = true) {
640
+ this._withDefault = callback;
641
+ return this;
642
+ }
643
+ getDefaultFor(parent) {
644
+ if (!this._withDefault) return null;
645
+ const instance = this.newRelatedInstanceFor(parent);
646
+ if (typeof this._withDefault === "function") return this._withDefault(instance, parent) || instance;
647
+ if (typeof this._withDefault === "object") for (const key in this._withDefault) instance.setAttribute(key, this._withDefault[key]);
648
+ return instance;
649
+ }
650
+ };
651
+ };
652
+ var supports_default_models_default = SupportsDefaultModels;
653
+
654
+ //#endregion
655
+ //#region src/relations/belongs-to.ts
656
+ var BelongsTo = class extends compose(relation_default, supports_default_models_default) {
657
+ foreignKey;
658
+ ownerKey;
659
+ child;
660
+ relationName;
661
+ constructor(query, child, foreignKey, ownerKey, relationName) {
662
+ super(query, child);
663
+ this.foreignKey = foreignKey;
664
+ this.ownerKey = ownerKey;
665
+ this.child = child;
666
+ this.relationName = relationName;
667
+ this.addConstraints();
668
+ return this.asProxy();
669
+ }
670
+ async getResults() {
671
+ if (this.child[this.foreignKey] === null) return this.getDefaultFor(this.parent);
672
+ return await this.query.first() || this.getDefaultFor(this.parent);
673
+ }
674
+ match(models, results, relation) {
675
+ const foreign = this.foreignKey;
676
+ const owner = this.ownerKey;
677
+ const dictionary = {};
678
+ results.map((result) => {
679
+ const attribute = result.attributes[owner];
680
+ dictionary[attribute] = result;
681
+ });
682
+ models.map((model) => {
683
+ const attribute = model[foreign];
684
+ if (dictionary[attribute] !== void 0) model.setRelation(relation, dictionary[attribute]);
685
+ });
686
+ return models;
687
+ }
688
+ getQualifiedForeignKeyName() {
689
+ return this.child.qualifyColumn(this.foreignKey);
690
+ }
691
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
692
+ if (parentQuery.getQuery()._single.table === query.getQuery()._single.table) return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
693
+ return query.select(columns).whereColumn(this.getQualifiedForeignKeyName(), "=", query.qualifyColumn(this.ownerKey));
694
+ }
695
+ getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
696
+ const hash = this.getRelationCountHash();
697
+ query.select(columns).from(query.getModel().getTable() + " as " + hash);
698
+ query.getModel().setTable(hash);
699
+ return query.whereColumn(`${hash}.${this.ownerKey}`, "=", this.getQualifiedForeignKeyName());
700
+ }
701
+ initRelation(models, relation) {
702
+ models.forEach((model) => {
703
+ model.setRelation(relation, this.getDefaultFor(model));
704
+ });
705
+ return models;
706
+ }
707
+ addEagerConstraints(models) {
708
+ const key = `${this.related.getTable()}.${this.ownerKey}`;
709
+ this.query.whereIn(key, this.getEagerModelKeys(models));
710
+ }
711
+ getEagerModelKeys(models) {
712
+ const keys = [];
713
+ models.forEach((model) => {
714
+ const value = model[this.foreignKey];
715
+ if (value !== null && value !== void 0) keys.push(value);
716
+ });
717
+ keys.sort();
718
+ return [...new Set(keys)];
719
+ }
720
+ associate(model) {
721
+ const ownerKey = model instanceof Model ? model.attributes[this.ownerKey] : model;
722
+ this.child[this.foreignKey] = ownerKey;
723
+ if (model instanceof Model) this.child.setRelation(this.relationName, model);
724
+ else this.child.unsetRelation(this.relationName);
725
+ return this.child;
726
+ }
727
+ dissociate() {
728
+ this.child[this.foreignKey] = null;
729
+ return this.child.setRelation(this.relationName, null);
730
+ }
731
+ addConstraints() {
732
+ if (this.constructor.constraints) {
733
+ const table = this.related.getTable();
734
+ this.query.where(`${table}.${this.ownerKey}`, "=", this.child[this.foreignKey]);
735
+ }
736
+ }
737
+ newRelatedInstanceFor(_parent) {
738
+ return this.related.newInstance();
739
+ }
740
+ };
741
+ var belongs_to_default = BelongsTo;
742
+
743
+ //#endregion
744
+ //#region src/collection.ts
745
+ var Collection$1 = class Collection$1 extends Collection {
746
+ newConstructor(...args) {
747
+ return new (this.getConstructor())(...args);
748
+ }
749
+ getConstructor() {
750
+ return this.constructor;
751
+ }
752
+ async load(...relations) {
753
+ if (this.isNotEmpty()) {
754
+ const items = await this.first().constructor.query().with(...relations).eagerLoadRelations(this.items);
755
+ return this.newConstructor(items);
756
+ }
757
+ return this;
758
+ }
759
+ async loadAggregate(relations, column, action = null) {
760
+ if (this.isEmpty()) return this;
761
+ const models = (await this.first().newModelQuery().whereIn(this.first().getKeyName(), this.modelKeys()).select(this.first().getKeyName()).withAggregate(relations, column, action).get()).keyBy(this.first().getKeyName());
762
+ const attributes = diff(Object.keys(models.first().getAttributes()), [models.first().getKeyName()]);
763
+ this.each((model) => {
764
+ const extraAttributes = pick(models.get(model.getKey()).getAttributes(), attributes);
765
+ model.fill(extraAttributes).syncOriginalAttributes(...attributes);
766
+ });
767
+ return this;
768
+ }
769
+ loadCount(relations) {
770
+ return this.loadAggregate(relations, "*", "count");
771
+ }
772
+ loadMax(relation, column) {
773
+ return this.loadAggregate(relation, column, "max");
774
+ }
775
+ loadMin(relation, column) {
776
+ return this.loadAggregate(relation, column, "min");
777
+ }
778
+ loadSum(relation, column) {
779
+ return this.loadAggregate(relation, column, "sum");
780
+ }
781
+ loadAvg(relation, column) {
782
+ return this.loadAggregate(relation, column, "avg");
783
+ }
784
+ mapThen(callback) {
785
+ return Promise.all(this.map(callback));
786
+ }
787
+ modelKeys() {
788
+ return this.all().map((item) => item.getKey());
789
+ }
790
+ contains(key, operator, value) {
791
+ if (arguments.length > 1) return super.contains(key, value ?? operator);
792
+ if (key instanceof model_default) return super.contains((model) => {
793
+ return model.is(key);
794
+ });
795
+ return super.contains((model) => {
796
+ return model.getKey() == key;
797
+ });
798
+ }
799
+ diff(items) {
800
+ const diff$1 = new this.constructor();
801
+ const dictionary = this.getDictionary(items);
802
+ this.items.map((item) => {
803
+ if (dictionary[item.getKey()] === void 0) diff$1.add(item);
804
+ });
805
+ return diff$1;
806
+ }
807
+ except(keys) {
808
+ const dictionary = omit(this.getDictionary(), keys);
809
+ return new this.constructor(Object.values(dictionary));
810
+ }
811
+ intersect(items) {
812
+ const intersect = new this.constructor();
813
+ if (isEmpty(items)) return intersect;
814
+ const dictionary = this.getDictionary(items);
815
+ for (const item of this.items) if (dictionary[item.getKey()] !== void 0) intersect.add(item);
816
+ return intersect;
817
+ }
818
+ unique(key, _strict = false) {
819
+ if (key) return super.unique(key);
820
+ return new this.constructor(Object.values(this.getDictionary()));
821
+ }
822
+ find(key, defaultValue = null) {
823
+ if (key instanceof model_default) key = key.getKey();
824
+ if (isArray(key)) {
825
+ if (this.isEmpty()) return new this.constructor();
826
+ return this.whereIn(this.first().getKeyName(), key);
827
+ }
828
+ collect$1(this.items).first((model) => {
829
+ return model.getKey() == key;
830
+ });
831
+ return this.items.filter((model) => {
832
+ return model.getKey() == key;
833
+ })[0] || defaultValue;
834
+ }
835
+ async fresh(...args) {
836
+ if (this.isEmpty()) return new this.constructor();
837
+ const model = this.first();
838
+ const freshModels = (await model.newQuery().with(...args).whereIn(model.getKeyName(), this.modelKeys()).get()).getDictionary();
839
+ return this.filter((model$1) => {
840
+ return model$1.exists && freshModels[model$1.getKey()] !== void 0;
841
+ }).map((model$1) => {
842
+ return freshModels[model$1.getKey()];
843
+ });
844
+ }
845
+ makeVisible(attributes) {
846
+ return this.each((item) => {
847
+ item.makeVisible(attributes);
848
+ });
849
+ }
850
+ makeHidden(attributes) {
851
+ return this.each((item) => {
852
+ item.makeHidden(attributes);
853
+ });
854
+ }
855
+ append(attributes) {
856
+ return this.each((item) => {
857
+ item.append(attributes);
858
+ });
859
+ }
860
+ only(keys) {
861
+ if (keys === null) return new Collection$1(this.items);
862
+ const dictionary = pick(this.getDictionary(), keys);
863
+ return new this.constructor(Object.values(dictionary));
864
+ }
865
+ getDictionary(items) {
866
+ items = !items ? this.items : items;
867
+ const dictionary = {};
868
+ items.map((value) => {
869
+ dictionary[value.getKey()] = value;
870
+ });
871
+ return dictionary;
872
+ }
873
+ toQuery() {
874
+ const model = this.first();
875
+ if (!model) throw new Error("Unable to create query for empty collection.");
876
+ const modelName = model.constructor.name;
877
+ if (this.filter((model$1) => {
878
+ return !(model$1 instanceof modelName);
879
+ }).isNotEmpty()) throw new Error("Unable to create query for collection with mixed types.");
880
+ return model.newModelQuery().whereKey(this.modelKeys());
881
+ }
882
+ toData() {
883
+ return this.all().map((item) => typeof item.toData == "function" ? item.toData() : item);
884
+ }
885
+ toJSON() {
886
+ return this.toData();
887
+ }
888
+ toJson(...args) {
889
+ return JSON.stringify(this.toData(), ...args);
890
+ }
891
+ [Symbol.iterator] = () => {
892
+ const items = this.items;
893
+ const length = this.items.length;
894
+ let n = 0;
895
+ return { next() {
896
+ return n < length ? {
897
+ value: items[n++],
898
+ done: false
899
+ } : { done: true };
900
+ } };
901
+ };
902
+ };
903
+ var collection_default = Collection$1;
904
+
905
+ //#endregion
906
+ //#region src/relations/concerns/interacts-with-pivot-table.ts
907
+ const InteractsWithPivotTable = (Relation$1) => {
908
+ return class extends Relation$1 {
909
+ newExistingPivot(attributes = []) {
910
+ return this.newPivot(attributes, true);
911
+ }
912
+ newPivot(attributes = [], exists = false) {
913
+ return this.related.newPivot(this.parent, attributes, this.getTable(), exists, this.using).setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
914
+ }
915
+ async attach(id, attributes = {}, _touch = true) {
916
+ if (this.using) await this.attachUsingCustomClass(id, attributes);
917
+ else await this.newPivotStatement().insert(this.formatAttachRecords(this.parseIds(id), attributes));
918
+ }
919
+ async detach(ids, _touch = true) {
920
+ let results;
921
+ if (this.using && ids !== null && this.pivotWheres.length == 0 && this.pivotWhereIns.length == 0 && this.pivotWhereNulls.length == 0) results = await this.detachUsingCustomClass(ids);
922
+ else {
923
+ const query = this.newPivotQuery();
924
+ if (ids !== null) {
925
+ ids = this.parseIds(ids);
926
+ if (ids.length == 0) return 0;
927
+ query.whereIn(this.getQualifiedRelatedPivotKeyName(), ids);
928
+ }
929
+ results = await query.delete();
930
+ }
931
+ return results;
932
+ }
933
+ async sync(ids, detaching = true) {
934
+ let changes = {
935
+ attached: [],
936
+ detached: [],
937
+ updated: []
938
+ };
939
+ let records;
940
+ const results = await this.getCurrentlyAttachedPivots();
941
+ const current = results.length === 0 ? [] : results.map((result) => result.toData()).pluck(this.relatedPivotKey).all().map((i) => String(i));
942
+ const detach = diff(current, Object.keys(records = this.formatRecordsList(this.parseIds(ids))));
943
+ if (detaching && detach.length > 0) {
944
+ await this.detach(detach);
945
+ changes.detached = this.castKeys(detach);
946
+ }
947
+ changes = assign(changes, await this.attachNew(records, current, false));
948
+ return changes;
949
+ }
950
+ syncWithoutDetaching(ids) {
951
+ return this.sync(ids, false);
952
+ }
953
+ syncWithPivotValues(ids, values, detaching = true) {
954
+ return this.sync(collect$1(this.parseIds(ids)).mapWithKeys((id) => {
955
+ return [id, values];
956
+ }), detaching);
957
+ }
958
+ withPivot(columns) {
959
+ this.pivotColumns = this.pivotColumns.concat(isArray(columns) ? columns : Array.prototype.slice.call(columns));
960
+ return this;
961
+ }
962
+ async attachNew(records, current, touch = true) {
963
+ const changes = {
964
+ attached: [],
965
+ updated: []
966
+ };
967
+ for (const id in records) {
968
+ const attributes = records[id];
969
+ if (!current.includes(id)) {
970
+ await this.attach(id, attributes, touch);
971
+ changes.attached.push(this.castKey(id));
972
+ } else if (Object.keys(attributes).length > 0 && await this.updateExistingPivot(id, attributes, touch)) changes.updated.push(this.castKey(id));
973
+ }
974
+ return changes;
975
+ }
976
+ async updateExistingPivot(id, attributes, touch = true) {
977
+ if (this.using && this.pivotWheres.length > 0 && this.pivotWhereInspivotWheres.length > 0 && this.pivotWhereNullspivotWheres.length > 0) return await this.updateExistingPivotUsingCustomClass(id, attributes, touch);
978
+ if (this.hasPivotColumn(this.updatedAt())) attributes = this.addTimestampsToAttachment(attributes, true);
979
+ return this.newPivotStatementForId(this.parseId(id)).update(this.castAttributes(attributes));
980
+ }
981
+ addTimestampsToAttachment(record, exists = false) {
982
+ let fresh = this.parent.freshTimestamp();
983
+ if (this.using) fresh = new this.using().fromDateTime(fresh);
984
+ if (!exists && this.hasPivotColumn(this.createdAt())) record[this.createdAt()] = fresh;
985
+ if (this.hasPivotColumn(this.updatedAt())) record[this.updatedAt()] = fresh;
986
+ return record;
987
+ }
988
+ async updateExistingPivotUsingCustomClass(id, attributes, _touch) {
989
+ const pivot = await this.getCurrentlyAttachedPivots().where(this.foreignPivotKey, this.parent[this.parentKey]).where(this.relatedPivotKey, this.parseId(id)).first();
990
+ const updated = pivot ? pivot.fill(attributes).isDirty() : false;
991
+ if (updated) await pivot.save();
992
+ return parseInt(updated);
993
+ }
994
+ formatRecordsList(records) {
995
+ return collect$1(records).mapWithKeys((attributes, id) => {
996
+ if (!isArray(attributes)) [id, attributes] = [attributes, {}];
997
+ return [id, attributes];
998
+ }).all();
999
+ }
1000
+ async getCurrentlyAttachedPivots() {
1001
+ return (await this.newPivotQuery().get()).map((record) => {
1002
+ return (this.using || Pivot).fromRawAttributes(this.parent, record, this.getTable(), true).setPivotKeys(this.foreignPivotKey, this.relatedPivotKey);
1003
+ });
1004
+ }
1005
+ castKeys(keys) {
1006
+ return keys.map((v) => {
1007
+ return this.castKey(v);
1008
+ });
1009
+ }
1010
+ castKey(key) {
1011
+ return this.getTypeSwapValue(this.related.getKeyType(), key);
1012
+ }
1013
+ getTypeSwapValue(type$1, value) {
1014
+ switch (type$1.toLowerCase()) {
1015
+ case "int":
1016
+ case "integer": return parseInt(value);
1017
+ case "real":
1018
+ case "float":
1019
+ case "double": return parseFloat(value);
1020
+ case "string": return String(value);
1021
+ default: return value;
1022
+ }
1023
+ }
1024
+ newPivotQuery() {
1025
+ const query = this.newPivotStatement();
1026
+ this.pivotWheres.map((args) => {
1027
+ query.where(...args);
1028
+ });
1029
+ this.pivotWhereIns.map((args) => {
1030
+ query.whereIn(...args);
1031
+ });
1032
+ this.pivotWhereNulls.map((args) => {
1033
+ query.whereNull(...args);
1034
+ });
1035
+ return query.where(this.getQualifiedForeignPivotKeyName(), this.parent[this.parentKey]);
1036
+ }
1037
+ async detachUsingCustomClass(ids) {
1038
+ let results = 0;
1039
+ for (const id in this.parseIds(ids)) results += await this.newPivot({
1040
+ [this.foreignPivotKey]: this.parent[this.parentKey],
1041
+ [this.relatedPivotKey]: id
1042
+ }, true).delete();
1043
+ return results;
1044
+ }
1045
+ newPivotStatement() {
1046
+ const builder = this.parent.newQuery();
1047
+ builder.setTable(this.table);
1048
+ return builder;
1049
+ }
1050
+ async attachUsingCustomClass(id, attributes) {
1051
+ const records = this.formatAttachRecords(this.parseIds(id), attributes);
1052
+ await Promise.all(records.map(async (record) => {
1053
+ await this.newPivot(record, false).save();
1054
+ }));
1055
+ }
1056
+ formatAttachRecords(ids, attributes) {
1057
+ const records = [];
1058
+ const hasTimestamps = this.hasPivotColumn(this.createdAt()) || this.hasPivotColumn(this.updatedAt());
1059
+ for (const key in ids) {
1060
+ const value = ids[key];
1061
+ records.push(this.formatAttachRecord(key, value, attributes, hasTimestamps));
1062
+ }
1063
+ return records;
1064
+ }
1065
+ formatAttachRecord(key, value, attributes, hasTimestamps) {
1066
+ const [id, newAttributes] = this.extractAttachIdAndAttributes(key, value, attributes);
1067
+ return assign(this.baseAttachRecord(id, hasTimestamps), newAttributes);
1068
+ }
1069
+ baseAttachRecord(id, timed) {
1070
+ let record = {};
1071
+ record[this.relatedPivotKey] = id;
1072
+ record[this.foreignPivotKey] = this.parent[this.parentKey];
1073
+ if (timed) record = this.addTimestampsToAttachment(record);
1074
+ this.pivotValues.map((value) => {
1075
+ record[value.column] = value.value;
1076
+ });
1077
+ return record;
1078
+ }
1079
+ extractAttachIdAndAttributes(key, value, newAttributes) {
1080
+ return isArray(value) ? [key, {
1081
+ ...value,
1082
+ ...newAttributes
1083
+ }] : [value, newAttributes];
1084
+ }
1085
+ hasPivotColumn(column) {
1086
+ return this.pivotColumns.includes(column);
1087
+ }
1088
+ parseIds(value) {
1089
+ if (value instanceof Model) return [value[this.relatedKey]];
1090
+ if (value instanceof collection_default) return value.pluck(this.relatedKey).all();
1091
+ return isArray(value) ? value : [value];
1092
+ }
1093
+ };
1094
+ };
1095
+ var interacts_with_pivot_table_default = InteractsWithPivotTable;
1096
+
1097
+ //#endregion
1098
+ //#region src/errors.ts
1099
+ var BaseError = class extends Error {
1100
+ constructor(message, _entity) {
1101
+ super(message);
1102
+ Error.captureStackTrace(this, this.constructor);
1103
+ this.name = this.constructor.name;
1104
+ this.message = message;
1105
+ }
1106
+ };
1107
+ var ModelNotFoundError = class extends BaseError {
1108
+ model;
1109
+ ids = [];
1110
+ constructor() {
1111
+ super("");
1112
+ }
1113
+ setModel(model, ids = []) {
1114
+ this.model = model;
1115
+ this.ids = isArray(ids) ? ids : [ids];
1116
+ this.message = `No query results for model [${model}]`;
1117
+ if (this.ids.length > 0) this.message += " " + this.ids.join(", ");
1118
+ else this.message += ".";
1119
+ return this;
1120
+ }
1121
+ getModel() {
1122
+ return this.model;
1123
+ }
1124
+ getIds() {
1125
+ return this.ids;
1126
+ }
1127
+ };
1128
+ var RelationNotFoundError = class extends BaseError {};
1129
+ var InvalidArgumentError = class extends BaseError {};
1130
+
1131
+ //#endregion
1132
+ //#region src/relations/belongs-to-many.ts
1133
+ var BelongsToMany = class extends compose(relation_default, interacts_with_pivot_table_default) {
1134
+ table;
1135
+ foreignPivotKey;
1136
+ relatedPivotKey;
1137
+ parentKey;
1138
+ relatedKey;
1139
+ pivotColumns = [];
1140
+ pivotValues = [];
1141
+ pivotWheres = [];
1142
+ pivotWhereIns = [];
1143
+ pivotWhereNulls = [];
1144
+ accessor = "pivot";
1145
+ using;
1146
+ pivotCreatedAt;
1147
+ pivotUpdatedAt;
1148
+ constructor(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
1149
+ super(query, parent);
1150
+ this.table = table;
1151
+ this.foreignPivotKey = foreignPivotKey;
1152
+ this.relatedPivotKey = relatedPivotKey;
1153
+ this.parentKey = parentKey;
1154
+ this.relatedKey = relatedKey;
1155
+ this.addConstraints();
1156
+ return this.asProxy();
1157
+ }
1158
+ initRelation(models, relation) {
1159
+ models.map((model) => {
1160
+ model.setRelation(relation, new collection_default([]));
1161
+ });
1162
+ return models;
1163
+ }
1164
+ addConstraints() {
1165
+ this.performJoin();
1166
+ if (this.constructor.constraints) this.addWhereConstraints();
1167
+ }
1168
+ performJoin(query = null) {
1169
+ query = query || this.query;
1170
+ query.join(this.getTable(), this.getQualifiedRelatedKeyName(), "=", this.qualifyPivotColumn(this.relatedPivotKey));
1171
+ return this;
1172
+ }
1173
+ getTable() {
1174
+ return this.table;
1175
+ }
1176
+ getQualifiedRelatedKeyName() {
1177
+ return this.related.qualifyColumn(this.relatedKey);
1178
+ }
1179
+ async getResults() {
1180
+ return this.parent[this.parentKey] !== null ? await this.get() : new collection_default([]);
1181
+ }
1182
+ addWhereConstraints() {
1183
+ this.query.where(this.getQualifiedForeignPivotKeyName(), "=", this.parent[this.parentKey]);
1184
+ return this;
1185
+ }
1186
+ async get(columns) {
1187
+ var _builder$query;
1188
+ const builder = this.query.applyScopes();
1189
+ columns = ((_builder$query = builder.query) === null || _builder$query === void 0 || (_builder$query = _builder$query._statements) === null || _builder$query === void 0 ? void 0 : _builder$query.find((item) => item.grouping == "columns")) ? [] : columns;
1190
+ let models = await builder.select(this.shouldSelect(columns)).getModels();
1191
+ this.hydratePivotRelation(models);
1192
+ if (models.length > 0) models = await builder.eagerLoadRelations(models);
1193
+ return new collection_default(models);
1194
+ }
1195
+ async first(columns = ["*"]) {
1196
+ const results = await this.take(1).get(columns);
1197
+ return results.count() > 0 ? results.first() : null;
1198
+ }
1199
+ async firstOrFail(columns = ["*"]) {
1200
+ const model = await this.first(columns);
1201
+ if (model !== null) return model;
1202
+ throw new ModelNotFoundError().setModel(this.related.constructor);
1203
+ }
1204
+ async paginate(page = 1, perPage = 15, columns = ["*"]) {
1205
+ this.query.select(this.shouldSelect(columns));
1206
+ return tap(await this.query.paginate(page, perPage), (paginator) => {
1207
+ this.hydratePivotRelation(paginator.items());
1208
+ });
1209
+ }
1210
+ async chunk(count, callback) {
1211
+ return await this.prepareQueryBuilder().chunk(count, async (results, page) => {
1212
+ this.hydratePivotRelation(results.all());
1213
+ return await callback(results, page);
1214
+ });
1215
+ }
1216
+ setUsing(model) {
1217
+ this.using = model;
1218
+ return this;
1219
+ }
1220
+ as(accessor) {
1221
+ this.accessor = accessor;
1222
+ return this;
1223
+ }
1224
+ prepareQueryBuilder() {
1225
+ return this.query.select(this.shouldSelect());
1226
+ }
1227
+ hydratePivotRelation(models) {
1228
+ models.map((model) => {
1229
+ model.setRelation(this.accessor, this.newExistingPivot(this.migratePivotAttributes(model)));
1230
+ });
1231
+ }
1232
+ migratePivotAttributes(model) {
1233
+ const values = {};
1234
+ for (const key in model.attributes) {
1235
+ const value = model.attributes[key];
1236
+ if (key.startsWith("pivot_")) {
1237
+ values[key.substring(6)] = value;
1238
+ model.attributes = omit(model.attributes, [key]);
1239
+ }
1240
+ }
1241
+ return values;
1242
+ }
1243
+ withTimestamps(createdAt = null, updatedAt = null) {
1244
+ this.pivotCreatedAt = createdAt;
1245
+ this.pivotUpdatedAt = updatedAt;
1246
+ return this.withPivot(this.createdAt(), this.updatedAt());
1247
+ }
1248
+ shouldSelect(columns = ["*"]) {
1249
+ if (isEqual(columns, ["*"])) columns = [this.related.getTable() + ".*"];
1250
+ return columns.concat(this.aliasedPivotColumns());
1251
+ }
1252
+ aliasedPivotColumns() {
1253
+ const defaults = [this.foreignPivotKey, this.relatedPivotKey];
1254
+ return collect$1(defaults.concat(this.pivotColumns)).map((column) => {
1255
+ return this.qualifyPivotColumn(column) + " as pivot_" + column;
1256
+ }).unique().all();
1257
+ }
1258
+ qualifyPivotColumn(column) {
1259
+ return column.includes(".") ? column : this.getTable() + "." + column;
1260
+ }
1261
+ match(models, results, relation) {
1262
+ const dictionary = this.buildDictionary(results);
1263
+ models.map((model) => {
1264
+ const key = model.getKey();
1265
+ if (dictionary[key] !== void 0) model.setRelation(relation, dictionary[key]);
1266
+ });
1267
+ return models;
1268
+ }
1269
+ buildDictionary(results) {
1270
+ const dictionary = {};
1271
+ results.map((result) => {
1272
+ const value = result[this.accessor][this.foreignPivotKey];
1273
+ if (dictionary[value] === void 0) dictionary[value] = new collection_default([]);
1274
+ dictionary[value].push(result);
1275
+ });
1276
+ return dictionary;
1277
+ }
1278
+ addEagerConstraints(models) {
1279
+ this.query.whereIn(this.getQualifiedForeignPivotKeyName(), this.getKeys(models, this.parentKey));
1280
+ }
1281
+ getQualifiedForeignPivotKeyName() {
1282
+ return this.qualifyPivotColumn(this.foreignPivotKey);
1283
+ }
1284
+ getQualifiedRelatedPivotKeyName() {
1285
+ return this.qualifyPivotColumn(this.relatedPivotKey);
1286
+ }
1287
+ wherePivot(column, operator = null, value = null, boolean = "and") {
1288
+ this.pivotWheres.push(Array.prototype.slice.call(arguments));
1289
+ return this.where(this.qualifyPivotColumn(column), operator, value, boolean);
1290
+ }
1291
+ wherePivotBetween(column, values, boolean = "and", not = false) {
1292
+ return this.whereBetween(this.qualifyPivotColumn(column), values, boolean, not);
1293
+ }
1294
+ orWherePivotBetween(column, values) {
1295
+ return this.wherePivotBetween(column, values, "or");
1296
+ }
1297
+ wherePivotNotBetween(column, values, boolean = "and") {
1298
+ return this.wherePivotBetween(column, values, boolean, true);
1299
+ }
1300
+ orWherePivotNotBetween(column, values) {
1301
+ return this.wherePivotBetween(column, values, "or", true);
1302
+ }
1303
+ wherePivotIn(column, values, boolean = "and", not = false) {
1304
+ return this.whereIn(this.qualifyPivotColumn(column), values, boolean, not);
1305
+ }
1306
+ orWherePivot(column, operator = null, value = null) {
1307
+ return this.wherePivot(column, operator, value, "or");
1308
+ }
1309
+ orWherePivotIn(column, values) {
1310
+ return this.wherePivotIn(column, values, "or");
1311
+ }
1312
+ wherePivotNotIn(column, values, boolean = "and") {
1313
+ return this.wherePivotIn(column, values, boolean, true);
1314
+ }
1315
+ orWherePivotNotIn(column, values) {
1316
+ return this.wherePivotNotIn(column, values, "or");
1317
+ }
1318
+ wherePivotNull(column, boolean = "and", not = false) {
1319
+ return this.whereNull(this.qualifyPivotColumn(column), boolean, not);
1320
+ }
1321
+ wherePivotNotNull(column, boolean = "and") {
1322
+ return this.wherePivotNull(column, boolean, true);
1323
+ }
1324
+ orWherePivotNull(column, not = false) {
1325
+ return this.wherePivotNull(column, "or", not);
1326
+ }
1327
+ orWherePivotNotNull(column) {
1328
+ return this.orWherePivotNull(column, true);
1329
+ }
1330
+ orderByPivot(column, direction = "asc") {
1331
+ return this.orderBy(this.qualifyPivotColumn(column), direction);
1332
+ }
1333
+ createdAt() {
1334
+ return this.pivotCreatedAt || this.parent.getCreatedAtColumn();
1335
+ }
1336
+ updatedAt() {
1337
+ return this.pivotUpdatedAt || this.parent.getUpdatedAtColumn();
1338
+ }
1339
+ getExistenceCompareKey() {
1340
+ return this.getQualifiedForeignPivotKeyName();
1341
+ }
1342
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
1343
+ if (parentQuery.getQuery()._single.table == query.getQuery()._single.table) return this.getRelationExistenceQueryForSelfJoin(query, parentQuery, columns);
1344
+ this.performJoin(query);
1345
+ return super.getRelationExistenceQuery(query, parentQuery, columns);
1346
+ }
1347
+ getRelationExistenceQueryForSelfJoin(query, parentQuery, columns = ["*"]) {
1348
+ const hash = this.getRelationCountHash();
1349
+ query.select(columns).from(this.related.getTable() + " as " + hash);
1350
+ this.related.setTable(hash);
1351
+ this.performJoin(query);
1352
+ return super.getRelationExistenceQuery(query, parentQuery, columns);
1353
+ }
1354
+ };
1355
+ var belongs_to_many_default = BelongsToMany;
1356
+
1357
+ //#endregion
1358
+ //#region src/paginator.ts
1359
+ var Paginator = class {
1360
+ static formatter;
1361
+ _items;
1362
+ _total;
1363
+ _perPage;
1364
+ _lastPage;
1365
+ _currentPage;
1366
+ hasMore = false;
1367
+ options = {};
1368
+ static setFormatter(formatter) {
1369
+ if (typeof formatter !== "function" && formatter !== null && formatter !== void 0) throw new Error("Paginator formatter must be a function or null");
1370
+ this.formatter = formatter;
1371
+ }
1372
+ constructor(items, total, perPage, currentPage = 1, options = {}) {
1373
+ this.options = options;
1374
+ for (const key in options) this[key] = options[key];
1375
+ this._items = new collection_default([]);
1376
+ this._total = total;
1377
+ this._perPage = parseInt(String(perPage));
1378
+ this._lastPage = Math.max(Math.ceil(total / perPage), 1);
1379
+ this._currentPage = currentPage;
1380
+ this.setItems(items);
1381
+ }
1382
+ setItems(items) {
1383
+ this._items = items instanceof collection_default ? items : new collection_default(items);
1384
+ this.hasMore = this._items.count() > this._perPage;
1385
+ this._items = this._items.slice(0, this._perPage);
1386
+ }
1387
+ firstItem() {
1388
+ return this.count() > 0 ? (this._currentPage - 1) * this._perPage + 1 : null;
1389
+ }
1390
+ lastItem() {
1391
+ return this.count() > 0 ? (this.firstItem() ?? 0) + this.count() - 1 : null;
1392
+ }
1393
+ hasMorePages() {
1394
+ return this._currentPage < this._lastPage;
1395
+ }
1396
+ get(index) {
1397
+ return this._items.get(index);
1398
+ }
1399
+ count() {
1400
+ return this._items.count();
1401
+ }
1402
+ items() {
1403
+ return this._items;
1404
+ }
1405
+ map(callback) {
1406
+ return this._items.map(callback);
1407
+ }
1408
+ currentPage() {
1409
+ return this._currentPage;
1410
+ }
1411
+ onFirstPage() {
1412
+ return this._currentPage === 1;
1413
+ }
1414
+ perPage() {
1415
+ return this._perPage;
1416
+ }
1417
+ lastPage() {
1418
+ return this._lastPage;
1419
+ }
1420
+ total() {
1421
+ return this._total;
1422
+ }
1423
+ toData() {
1424
+ if (this.constructor.formatter && typeof this.constructor.formatter === "function") return this.constructor.formatter(this);
1425
+ return {
1426
+ current_page: this._currentPage,
1427
+ data: this._items.toData(),
1428
+ per_page: this._perPage,
1429
+ total: this._total,
1430
+ last_page: this._lastPage,
1431
+ count: this.count()
1432
+ };
1433
+ }
1434
+ toJSON() {
1435
+ return this.toData();
1436
+ }
1437
+ toJson(...args) {
1438
+ return JSON.stringify(this.toData(), ...args);
1439
+ }
1440
+ };
1441
+ var paginator_default = Paginator;
1442
+
1443
+ //#endregion
1444
+ //#region src/scope.ts
1445
+ var Scope = class Scope {
1446
+ constructor() {
1447
+ if (this.constructor === Scope) throw new Error("Scope cannot be instantiated");
1448
+ }
1449
+ apply(_builder, _model) {
1450
+ throw new Error("apply not implemented");
1451
+ }
1452
+ };
1453
+ var scope_default = Scope;
1454
+
1455
+ //#endregion
1456
+ //#region src/builder.ts
1457
+ const Inference$1 = class {};
1458
+ var Builder = class Builder extends Inference$1 {
1459
+ query;
1460
+ connection;
1461
+ model;
1462
+ actions;
1463
+ localMacros = {};
1464
+ eagerLoad = {};
1465
+ globalScopes = {};
1466
+ onDeleteCallback;
1467
+ constructor(query) {
1468
+ super();
1469
+ this.query = query;
1470
+ return this.asProxy();
1471
+ }
1472
+ asProxy() {
1473
+ return new Proxy(this, { get(target, prop) {
1474
+ if (typeof target[prop] !== "undefined") return target[prop];
1475
+ if ([
1476
+ "select",
1477
+ "from",
1478
+ "where",
1479
+ "orWhere",
1480
+ "whereColumn",
1481
+ "whereRaw",
1482
+ "whereNot",
1483
+ "orWhereNot",
1484
+ "whereIn",
1485
+ "orWhereIn",
1486
+ "whereNotIn",
1487
+ "orWhereNotIn",
1488
+ "whereNull",
1489
+ "orWhereNull",
1490
+ "whereNotNull",
1491
+ "orWhereNotNull",
1492
+ "whereExists",
1493
+ "orWhereExists",
1494
+ "whereNotExists",
1495
+ "orWhereNotExists",
1496
+ "whereBetween",
1497
+ "orWhereBetween",
1498
+ "whereNotBetween",
1499
+ "orWhereNotBetween",
1500
+ "whereLike",
1501
+ "orWhereLike",
1502
+ "whereILike",
1503
+ "orWhereILike",
1504
+ "whereJsonObject",
1505
+ "whereJsonPath",
1506
+ "whereJsonSupersetOf",
1507
+ "whereJsonSubsetOf",
1508
+ "join",
1509
+ "joinRaw",
1510
+ "leftJoin",
1511
+ "leftOuterJoin",
1512
+ "rightJoin",
1513
+ "rightOuterJoin",
1514
+ "crossJoin",
1515
+ "transacting",
1516
+ "groupBy",
1517
+ "groupByRaw",
1518
+ "returning",
1519
+ "having",
1520
+ "havingRaw",
1521
+ "havingBetween",
1522
+ "limit",
1523
+ "offset",
1524
+ "orderBy",
1525
+ "orderByRaw",
1526
+ "union",
1527
+ "insert",
1528
+ "forUpdate",
1529
+ "forShare",
1530
+ "distinct",
1531
+ "clearOrder",
1532
+ "clear",
1533
+ "clearSelect",
1534
+ "clearWhere",
1535
+ "clearHaving",
1536
+ "clearGroup"
1537
+ ].includes(prop)) return (...args) => {
1538
+ target.query[prop](...args);
1539
+ return target.asProxy();
1540
+ };
1541
+ if ([
1542
+ "avg",
1543
+ "max",
1544
+ "min",
1545
+ "sum",
1546
+ "count"
1547
+ ].includes(prop)) return (column) => {
1548
+ const instance = target.asProxy();
1549
+ instance.applyScopes();
1550
+ column = !column && prop === "count" ? "*" : column;
1551
+ return instance.query[prop](column);
1552
+ };
1553
+ if (typeof prop === "string") {
1554
+ if (target.hasMacro(prop)) {
1555
+ const instance = target.asProxy();
1556
+ return (...args) => {
1557
+ return instance.localMacros[prop](instance, ...args);
1558
+ };
1559
+ }
1560
+ if (target.hasNamedScope(prop)) {
1561
+ const instance = target.asProxy();
1562
+ return (...args) => {
1563
+ instance.callNamedScope(prop, args);
1564
+ return instance;
1565
+ };
1566
+ }
1567
+ if (prop.startsWith("where")) {
1568
+ const column = snake(prop.substring(5));
1569
+ return (...args) => {
1570
+ target.query.where(column, ...args);
1571
+ return target.asProxy();
1572
+ };
1573
+ }
1574
+ }
1575
+ } });
1576
+ }
1577
+ orWhere(...args) {
1578
+ if (typeof args[0] === "function") {
1579
+ const callback = args[0];
1580
+ this.query.orWhere((query) => {
1581
+ this.query = query;
1582
+ callback(this);
1583
+ });
1584
+ return this;
1585
+ }
1586
+ this.query.orWhere(...args);
1587
+ return this;
1588
+ }
1589
+ async chunk(count, callback) {
1590
+ let page = 1;
1591
+ let countResults;
1592
+ do {
1593
+ this.enforceOrderBy();
1594
+ const results = await this.clone().forPage(page, count).get();
1595
+ countResults = results.count();
1596
+ if (countResults == 0) break;
1597
+ if (await callback(results, page) === false) return false;
1598
+ page++;
1599
+ } while (countResults === count);
1600
+ return true;
1601
+ }
1602
+ enforceOrderBy() {
1603
+ if (this.query._statements.filter((item) => item.grouping === "order").length === 0) this.orderBy(this.model.getQualifiedKeyName(), "asc");
1604
+ }
1605
+ clone() {
1606
+ const query = this.query.clone();
1607
+ const builder = new this.constructor(query);
1608
+ builder.connection = this.connection;
1609
+ builder.setModel(this.model);
1610
+ builder.globalScopes = { ...this.globalScopes };
1611
+ builder.localMacros = { ...this.localMacros };
1612
+ builder.eagerLoad = { ...this.eagerLoad };
1613
+ return builder;
1614
+ }
1615
+ forPage(page, perPage = 15) {
1616
+ return this.offset((page - 1) * perPage).limit(perPage);
1617
+ }
1618
+ insert(...args) {
1619
+ return this.query.insert(...args);
1620
+ }
1621
+ update(values) {
1622
+ this.applyScopes();
1623
+ return this.query.update(this.addUpdatedAtColumn(values));
1624
+ }
1625
+ increment(column, amount = 1, extra = {}) {
1626
+ this.applyScopes();
1627
+ const db = this.model.getConnection();
1628
+ return this.query.update(this.addUpdatedAtColumn({
1629
+ ...extra,
1630
+ [column]: db.raw(`${column} + ${amount}`)
1631
+ }));
1632
+ }
1633
+ decrement(column, amount = 1, extra = {}) {
1634
+ this.applyScopes();
1635
+ const db = this.model.getConnection();
1636
+ return this.query.update(this.addUpdatedAtColumn({
1637
+ ...extra,
1638
+ [column]: db.raw(`${column} - ${amount}`)
1639
+ }));
1640
+ }
1641
+ addUpdatedAtColumn(values) {
1642
+ if (!this.model.usesTimestamps() || this.model.getUpdatedAtColumn() === null) return values;
1643
+ const column = this.model.getUpdatedAtColumn();
1644
+ values = assign({ [column]: this.model.freshTimestampString() }, values);
1645
+ return values;
1646
+ }
1647
+ delete() {
1648
+ if (this.onDeleteCallback) return this.onDeleteCallback(this);
1649
+ return this.query.delete();
1650
+ }
1651
+ onDelete(callback) {
1652
+ this.onDeleteCallback = callback;
1653
+ }
1654
+ forceDelete() {
1655
+ return this.query.delete();
1656
+ }
1657
+ async create(attributes = {}) {
1658
+ return await tap(this.newModelInstance(attributes), async (instance) => {
1659
+ await instance.save({ client: this.query });
1660
+ });
1661
+ }
1662
+ newModelInstance(attributes = {}) {
1663
+ return this.model.newInstance(attributes).setConnection(this.model.getConnectionName());
1664
+ }
1665
+ getQuery() {
1666
+ return this.query;
1667
+ }
1668
+ getModel() {
1669
+ return this.model;
1670
+ }
1671
+ setModel(model) {
1672
+ var _this$query;
1673
+ this.model = model;
1674
+ if (typeof ((_this$query = this.query) === null || _this$query === void 0 || (_this$query = _this$query.client) === null || _this$query === void 0 ? void 0 : _this$query.table) == "function") this.query = this.query.client.table(this.model.getTable());
1675
+ else this.query = this.query.table(this.model.getTable());
1676
+ return this;
1677
+ }
1678
+ qualifyColumn(column) {
1679
+ return this.model.qualifyColumn(column);
1680
+ }
1681
+ setTable(table) {
1682
+ this.query = this.query.table(table);
1683
+ return this;
1684
+ }
1685
+ applyScopes() {
1686
+ if (!this.globalScopes) return this;
1687
+ for (const identifier in this.globalScopes) {
1688
+ const scope = this.globalScopes[identifier];
1689
+ if (scope instanceof scope_default) scope.apply(this, this.getModel());
1690
+ else scope(this);
1691
+ }
1692
+ return this;
1693
+ }
1694
+ hasNamedScope(name$1) {
1695
+ return this.model && this.model.hasNamedScope(name$1);
1696
+ }
1697
+ callNamedScope(scope, parameters) {
1698
+ return this.model.callNamedScope(scope, [this, ...parameters]);
1699
+ }
1700
+ callScope(scope, parameters = []) {
1701
+ return scope(this, ...parameters) || this;
1702
+ }
1703
+ scopes(scopes) {
1704
+ scopes.map((scopeName) => {
1705
+ const scopeMethod = getScopeMethod(scopeName);
1706
+ if (typeof this.model[scopeMethod] === "function") this.globalScopes[scopeName] = this.model[scopeMethod];
1707
+ });
1708
+ return this;
1709
+ }
1710
+ withGlobalScope(identifier, scope) {
1711
+ this.globalScopes[identifier] = scope;
1712
+ if (typeof scope.extend === "function") scope.extend(this);
1713
+ return this;
1714
+ }
1715
+ withoutGlobalScope(scope) {
1716
+ if (typeof scope !== "string") scope = scope.constructor.name;
1717
+ this.globalScopes = omit(this.globalScopes, [scope]);
1718
+ return this;
1719
+ }
1720
+ macro(name$1, callback) {
1721
+ this.localMacros[name$1] = callback;
1722
+ return this;
1723
+ }
1724
+ hasMacro(name$1) {
1725
+ return name$1 in this.localMacros;
1726
+ }
1727
+ getMacro(name$1) {
1728
+ return this.localMacros[name$1];
1729
+ }
1730
+ with(...args) {
1731
+ let eagerLoads = {};
1732
+ if (typeof args[1] === "function") {
1733
+ const eagerLoad = this.parseWithRelations({ [args[0]]: args[1] });
1734
+ this.eagerLoad = assign(this.eagerLoad, eagerLoad);
1735
+ return this;
1736
+ }
1737
+ const relations = flattenDeep(args);
1738
+ if (relations.length === 0) return this;
1739
+ for (const relation of relations) {
1740
+ let eagerLoad;
1741
+ if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
1742
+ else if (typeof relation === "object") eagerLoad = relation;
1743
+ eagerLoads = assign(eagerLoads, eagerLoad);
1744
+ }
1745
+ this.eagerLoad = assign(this.eagerLoad, this.parseWithRelations(eagerLoads));
1746
+ return this;
1747
+ }
1748
+ has(relation, operator = ">=", count = 1, boolean = "and", callback = null) {
1749
+ if (isString(relation)) {
1750
+ if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
1751
+ relation = this.getRelationWithoutConstraints(getRelationMethod(relation));
1752
+ }
1753
+ const method = this.canUseExistsForExistenceCheck(operator, count) ? "getRelationExistenceQuery" : "getRelationExistenceCountQuery";
1754
+ const hasQuery = relation[method](relation.getRelated().newModelQuery(), this);
1755
+ if (callback) callback(hasQuery);
1756
+ return this.addHasWhere(hasQuery, relation, operator, count, boolean);
1757
+ }
1758
+ orHas(relation, operator = ">=", count = 1) {
1759
+ return this.has(relation, operator, count, "or");
1760
+ }
1761
+ doesntHave(relation, boolean = "and", callback = null) {
1762
+ return this.has(relation, "<", 1, boolean, callback);
1763
+ }
1764
+ orDoesntHave(relation) {
1765
+ return this.doesntHave(relation, "or");
1766
+ }
1767
+ whereHas(relation, callback = null, operator = ">=", count = 1) {
1768
+ return this.has(relation, operator, count, "and", callback);
1769
+ }
1770
+ orWhereHas(relation, callback = null, operator = ">=", count = 1) {
1771
+ return this.has(relation, operator, count, "or", callback);
1772
+ }
1773
+ whereRelation(relation, ...args) {
1774
+ const column = args.shift();
1775
+ return this.whereHas(relation, (query) => {
1776
+ if (typeof column === "function") column(query);
1777
+ else query.where(column, ...args);
1778
+ });
1779
+ }
1780
+ orWhereRelation(relation, ...args) {
1781
+ const column = args.shift();
1782
+ return this.orWhereHas(relation, function(query) {
1783
+ if (typeof column === "function") column(query);
1784
+ else query.where(column, ...args);
1785
+ });
1786
+ }
1787
+ hasNested(relations, operator = ">=", count = 1, boolean = "and", callback = null) {
1788
+ relations = relations.split(".");
1789
+ const doesntHave = operator === "<" && count === 1;
1790
+ if (doesntHave) {
1791
+ operator = ">=";
1792
+ count = 1;
1793
+ }
1794
+ const closure = (q) => {
1795
+ if (relations.length > 1) q.whereHas(relations.shift(), closure);
1796
+ else q.has(relations.shift(), operator, count, "and", callback);
1797
+ return null;
1798
+ };
1799
+ return this.has(relations.shift(), doesntHave ? "<" : ">=", 1, boolean, closure);
1800
+ }
1801
+ canUseExistsForExistenceCheck(operator, count) {
1802
+ return (operator === ">=" || operator === "<") && count === 1;
1803
+ }
1804
+ addHasWhere(hasQuery, relation, operator, count, boolean) {
1805
+ hasQuery.mergeConstraintsFrom(relation.getQuery());
1806
+ return this.canUseExistsForExistenceCheck(operator, count) ? this.addWhereExistsQuery(hasQuery.getQuery(), boolean, operator === "<" && count === 1) : this.addWhereCountQuery(hasQuery.getQuery(), operator, count, boolean);
1807
+ }
1808
+ addWhereExistsQuery(query, boolean = "and", not = false) {
1809
+ const type$1 = not ? "NotExists" : "Exists";
1810
+ const method = boolean === "and" ? "where" + type$1 : "orWhere" + type$1;
1811
+ this[method](query.connector);
1812
+ return this;
1813
+ }
1814
+ addWhereCountQuery(query, operator = ">=", count = 1, boolean = "and") {
1815
+ const db = this.model.getConnection();
1816
+ return this.where(db.raw("(" + query.toSQL().sql + ")"), operator, typeof count === "number" ? db.raw(count) : count, boolean);
1817
+ }
1818
+ withAggregate(relations, column, action = null) {
1819
+ if (relations.length === 0) return this;
1820
+ relations = flattenDeep([relations]);
1821
+ let eagerLoads = {};
1822
+ for (const relation of relations) {
1823
+ let eagerLoad;
1824
+ if (typeof relation === "string") eagerLoad = { [relation]: (q) => q };
1825
+ else if (typeof relation === "object") eagerLoad = relation;
1826
+ eagerLoads = assign(eagerLoads, eagerLoad);
1827
+ }
1828
+ relations = eagerLoads;
1829
+ const db = this.model.getConnection();
1830
+ if (this.query._statements.filter((item) => item.grouping == "columns").map((item) => item.value).flat().length === 0) this.query.select([this.query._single.table + ".*"]);
1831
+ const parses = this.parseWithRelations(relations);
1832
+ for (let name$1 in parses) {
1833
+ const constraints = parses[name$1];
1834
+ const segments = name$1.split(" ");
1835
+ let alias, expression;
1836
+ if (segments.length === 3 && segments[1].toLocaleLowerCase() === "as") [name$1, alias] = [segments[0], segments[2]];
1837
+ const relation = this.getRelationWithoutConstraints(getRelationMethod(name$1));
1838
+ if (action) {
1839
+ const hashedColumn = this.query._single.table === relation.query.query._single.table ? `${relation.getRelationCountHash(false)}.${column}` : column;
1840
+ const wrappedColumn = column === "*" ? column : relation.getRelated().qualifyColumn(hashedColumn);
1841
+ expression = action === "exists" ? wrappedColumn : `${action}(${wrappedColumn})`;
1842
+ } else expression = column;
1843
+ const query = relation.getRelationExistenceQuery(relation.getRelated().newModelQuery(), this, db.raw(expression));
1844
+ constraints(query);
1845
+ alias = alias || snake(`${name$1} ${action} ${column}`.replace("/[^[:alnum:][:space:]_]/u", ""));
1846
+ if (action === "exists") this.select(db.raw(`exists(${query.toSql().sql}) as ${alias}`));
1847
+ else this.selectSub(action ? query : query.limit(1), alias);
1848
+ }
1849
+ return this;
1850
+ }
1851
+ toSql() {
1852
+ const query = this.clone();
1853
+ query.applyScopes();
1854
+ return query.query.toSQL();
1855
+ }
1856
+ mergeConstraintsFrom(_from) {
1857
+ return this;
1858
+ }
1859
+ selectSub(query, as) {
1860
+ const [querySub, bindings] = this.createSub(query);
1861
+ const db = this.model.getConnection();
1862
+ return this.select(db.raw("(" + querySub + ") as " + as, bindings));
1863
+ }
1864
+ createSub(query) {
1865
+ return this.parseSub(query);
1866
+ }
1867
+ parseSub(query) {
1868
+ if (query instanceof Builder || query instanceof relation_default) return [query.toSql().sql, query.toSql().bindings];
1869
+ else if (isString(query)) return [query, []];
1870
+ else throw new Error("A subquery must be a query builder instance, a Closure, or a string.");
1871
+ }
1872
+ prependDatabaseNameIfCrossDatabaseQuery(query) {
1873
+ if (query.query._single.table !== this.query._single.table) {
1874
+ const databaseName = query.query._single.table;
1875
+ if (!query.query._single.table.startsWith(databaseName) && !query.query._single.table.contains(".")) query.from(databaseName + "." + query.from);
1876
+ }
1877
+ return query;
1878
+ }
1879
+ getRelationWithoutConstraints(relation) {
1880
+ return relation_default.noConstraints(() => {
1881
+ return this.getModel()[relation]();
1882
+ });
1883
+ }
1884
+ withCount(...args) {
1885
+ return this.withAggregate(flattenDeep(args), "*", "count");
1886
+ }
1887
+ withMax(relation, column) {
1888
+ return this.withAggregate(relation, column, "max");
1889
+ }
1890
+ withMin(relation, column) {
1891
+ return this.withAggregate(relation, column, "min");
1892
+ }
1893
+ withAvg(relation, column) {
1894
+ return this.withAggregate(relation, column, "avg");
1895
+ }
1896
+ withSum(relation, column) {
1897
+ return this.withAggregate(relation, column, "sum");
1898
+ }
1899
+ withExists(relation) {
1900
+ return this.withAggregate(relation, "*", "exists");
1901
+ }
1902
+ parseWithRelations(relations) {
1903
+ if (relations.length === 0) return [];
1904
+ let results = {};
1905
+ const constraintsMap = this.prepareNestedWithRelationships(relations);
1906
+ for (const name$1 in constraintsMap) {
1907
+ results = this.addNestedWiths(name$1, results);
1908
+ results[name$1] = constraintsMap[name$1];
1909
+ }
1910
+ return results;
1911
+ }
1912
+ addNestedWiths(name$1, results) {
1913
+ const progress = [];
1914
+ name$1.split(".").map((segment) => {
1915
+ progress.push(segment);
1916
+ const last = progress.join(".");
1917
+ if (results[last] === void 0) results[last] = () => {};
1918
+ });
1919
+ return results;
1920
+ }
1921
+ prepareNestedWithRelationships(relations, prefix = "") {
1922
+ let preparedRelationships = {};
1923
+ if (prefix !== "") prefix += ".";
1924
+ for (const key in relations) {
1925
+ const value = relations[key];
1926
+ if (isString(value) || Number.isFinite(parseInt(value))) continue;
1927
+ const [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(key, value);
1928
+ preparedRelationships = Object.assign({}, preparedRelationships, { [`${prefix}${attribute}`]: attributeSelectConstraint }, this.prepareNestedWithRelationships(value, `${prefix}${attribute}`));
1929
+ relations = omit(relations, [key]);
1930
+ }
1931
+ for (const key in relations) {
1932
+ const value = relations[key];
1933
+ let attribute = key, attributeSelectConstraint = value;
1934
+ if (isString(value)) [attribute, attributeSelectConstraint] = this.parseNameAndAttributeSelectionConstraint(value);
1935
+ preparedRelationships[`${prefix}${attribute}`] = this.combineConstraints([attributeSelectConstraint, preparedRelationships[`${prefix}${attribute}`] || (() => {})]);
1936
+ }
1937
+ return preparedRelationships;
1938
+ }
1939
+ combineConstraints(constraints) {
1940
+ return (builder) => {
1941
+ constraints.map((constraint) => {
1942
+ builder = constraint(builder) || builder;
1943
+ });
1944
+ return builder;
1945
+ };
1946
+ }
1947
+ parseNameAndAttributeSelectionConstraint(name$1, value) {
1948
+ return name$1.includes(":") ? this.createSelectWithConstraint(name$1) : [name$1, value];
1949
+ }
1950
+ createSelectWithConstraint(name$1) {
1951
+ return [name$1.split(":")[0], (query) => {
1952
+ query.select(name$1.split(":")[1].split(",").map((column) => {
1953
+ if (column.includes(".")) return column;
1954
+ return query instanceof belongs_to_many_default ? query.related.getTable() + "." + column : column;
1955
+ }));
1956
+ }];
1957
+ }
1958
+ related(relation) {
1959
+ if (typeof this.model[getRelationMethod(relation)] !== "function") {
1960
+ const message = `Model [${this.model.constructor.name}]'s relation [${relation}] doesn't exist.`;
1961
+ throw new RelationNotFoundError(message);
1962
+ }
1963
+ return this.model[getRelationMethod(relation)]();
1964
+ }
1965
+ take(...args) {
1966
+ return this.limit(...args);
1967
+ }
1968
+ skip(...args) {
1969
+ return this.offset(...args);
1970
+ }
1971
+ async first(...columns) {
1972
+ this.applyScopes();
1973
+ this.limit(1);
1974
+ let models = await this.getModels(columns);
1975
+ if (models.length > 0) models = await this.eagerLoadRelations(models);
1976
+ return models[0] || null;
1977
+ }
1978
+ async firstOrFail(...columns) {
1979
+ const data = await this.first(...columns);
1980
+ if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name);
1981
+ return data;
1982
+ }
1983
+ async findOrFail(...args) {
1984
+ const data = await this.find(...args);
1985
+ if (isArray(args[0])) {
1986
+ if (data.count() !== args[0].length) throw new ModelNotFoundError().setModel(this.model.constructor.name, diff(args[0], data.modelKeys()));
1987
+ return data;
1988
+ }
1989
+ if (data === null) throw new ModelNotFoundError().setModel(this.model.constructor.name, args[0]);
1990
+ return data;
1991
+ }
1992
+ async findOrNew(id, columns = ["*"]) {
1993
+ const model = await this.find(id, columns);
1994
+ if (model !== null) return model;
1995
+ return this.newModelInstance();
1996
+ }
1997
+ async firstOrNew(attributes = {}, values = {}) {
1998
+ const instance = await this.where(attributes).first();
1999
+ if (instance !== null) return instance;
2000
+ return this.newModelInstance(assign(attributes, values));
2001
+ }
2002
+ async firstOrCreate(attributes = {}, values = {}) {
2003
+ const instance = await this.where(attributes).first();
2004
+ if (instance !== null) return instance;
2005
+ return tap(this.newModelInstance(assign(attributes, values)), async (instance$1) => {
2006
+ await instance$1.save({ client: this.query });
2007
+ });
2008
+ }
2009
+ async updateOrCreate(attributes, values = {}) {
2010
+ return await tap(await this.firstOrNew(attributes), async (instance) => {
2011
+ await instance.fill(values).save({ client: this.query });
2012
+ });
2013
+ }
2014
+ latest(column = "id") {
2015
+ if (column === null) column = this.model.getCreatedAtColumn() || "created_at";
2016
+ this.query.orderBy(column, "desc");
2017
+ return this;
2018
+ }
2019
+ oldest(column = "id") {
2020
+ if (column === null) column = this.model.getCreatedAtColumn() || "created_at";
2021
+ this.query.orderBy(column, "asc");
2022
+ return this;
2023
+ }
2024
+ async find(id, columns) {
2025
+ if (isArray(id) || id instanceof collection_default) return await this.findMany(id, columns);
2026
+ return await this.where(this.model.getKeyName(), id).first(columns);
2027
+ }
2028
+ async findMany(ids, columns = ["*"]) {
2029
+ if (ids instanceof collection_default) ids = ids.modelKeys();
2030
+ ids = isArray(ids) ? ids : [ids];
2031
+ if (ids.length === 0) return new collection_default([]);
2032
+ return await this.whereIn(this.model.getKeyName(), ids).get(columns);
2033
+ }
2034
+ async pluck(column) {
2035
+ const data = await this.query.pluck(column);
2036
+ return new collection_default(data);
2037
+ }
2038
+ async destroy(ids) {
2039
+ if (ids instanceof collection_default) ids = ids.modelKeys();
2040
+ if (ids instanceof Collection) ids = ids.all();
2041
+ ids = isArray(ids) ? ids : Array.prototype.slice.call(ids);
2042
+ if (ids.length === 0) return 0;
2043
+ const key = this.model.newInstance().getKeyName();
2044
+ let count = 0;
2045
+ const models = await this.model.newModelQuery().whereIn(key, ids).get();
2046
+ for (const model of models) if (await model.delete()) count++;
2047
+ return count;
2048
+ }
2049
+ async get(columns = ["*"]) {
2050
+ this.applyScopes();
2051
+ let models = await this.getModels(columns);
2052
+ if (models.length > 0) models = await this.eagerLoadRelations(models);
2053
+ return new collection_default(models);
2054
+ }
2055
+ async all(columns = ["*"]) {
2056
+ return await this.model.newModelQuery().get(columns);
2057
+ }
2058
+ async paginate(page = 1, perPage = 10) {
2059
+ var _this;
2060
+ page = page || 1;
2061
+ perPage = perPage || ((_this = this) === null || _this === void 0 || (_this = _this.model) === null || _this === void 0 ? void 0 : _this.perPage) || 15;
2062
+ this.applyScopes();
2063
+ const total = await this.query.clone().clearOrder().clearSelect().count(this.primaryKey);
2064
+ let results = [];
2065
+ if (total > 0) {
2066
+ const skip = (page - 1) * (perPage ?? 10);
2067
+ this.take(perPage).skip(skip);
2068
+ results = await this.getModels();
2069
+ if (results.length > 0) results = await this.eagerLoadRelations(results);
2070
+ } else results = [];
2071
+ return new paginator_default(results, parseInt(total), perPage, page);
2072
+ }
2073
+ async getModels(...columns) {
2074
+ columns = flat(columns);
2075
+ if (columns.length > 0) {
2076
+ if (this.query._statements.filter((item) => item.grouping == "columns").length == 0 && columns[0] !== "*") this.query.select(...columns);
2077
+ }
2078
+ return this.hydrate(await this.query.get()).all();
2079
+ }
2080
+ getRelation(name$1) {
2081
+ if (typeof this.model[getRelationMethod(name$1)] !== "function") {
2082
+ const message = `Model [${this.model.constructor.name}]'s relation [${name$1}] doesn't exist.`;
2083
+ throw new RelationNotFoundError(message);
2084
+ }
2085
+ const relation = relation_default.noConstraints(() => this.model.newInstance(this.model.attributes)[getRelationMethod(name$1)]());
2086
+ const nested = this.relationsNestedUnder(name$1);
2087
+ if (Object.keys(nested).length > 0) relation.query.with(nested);
2088
+ return relation.asProxy();
2089
+ }
2090
+ relationsNestedUnder(relation) {
2091
+ const nested = {};
2092
+ for (const name$1 in this.eagerLoad) {
2093
+ const constraints = this.eagerLoad[name$1];
2094
+ if (this.isNestedUnder(relation, name$1)) nested[name$1.substring((relation + ".").length)] = constraints;
2095
+ }
2096
+ return nested;
2097
+ }
2098
+ isNestedUnder(relation, name$1) {
2099
+ return name$1.includes(".") && name$1.startsWith(relation + ".");
2100
+ }
2101
+ async eagerLoadRelation(models, name$1, constraints) {
2102
+ const relation = this.getRelation(name$1);
2103
+ relation.addEagerConstraints(models);
2104
+ constraints(relation);
2105
+ return relation.match(relation.initRelation(models, name$1), await relation.get(), name$1);
2106
+ }
2107
+ async eagerLoadRelations(models) {
2108
+ for (const name$1 in this.eagerLoad) {
2109
+ const constraints = this.eagerLoad[name$1];
2110
+ if (!name$1.includes(".")) models = await this.eagerLoadRelation(models, name$1, constraints);
2111
+ }
2112
+ return models;
2113
+ }
2114
+ hydrate(items) {
2115
+ return new collection_default(items.map((item) => {
2116
+ if (!this.model) return item;
2117
+ return this.model.newFromBuilder(item);
2118
+ }));
2119
+ }
2120
+ };
2121
+ var builder_default = Builder;
2122
+
2123
+ //#endregion
2124
+ //#region src/casts-attributes.ts
2125
+ var CastsAttributes = class CastsAttributes {
2126
+ constructor() {
2127
+ if (this.constructor === CastsAttributes) throw new Error("CastsAttributes cannot be instantiated");
2128
+ }
2129
+ static get(_model, _key, _value, _attributes) {
2130
+ throw new Error("get not implemented");
2131
+ }
2132
+ static set(_model, _key, _value, _attributes) {
2133
+ throw new Error("set not implemented");
2134
+ }
2135
+ };
2136
+ var casts_attributes_default = CastsAttributes;
2137
+
2138
+ //#endregion
2139
+ //#region src/concerns/has-attributes.ts
2140
+ const HasAttributes = (Model$1) => {
2141
+ return class extends Model$1 {
2142
+ static castTypeCache = {};
2143
+ attributes = {};
2144
+ original = {};
2145
+ casts = {};
2146
+ changes = {};
2147
+ appends = [];
2148
+ setAppends(appends) {
2149
+ this.appends = appends;
2150
+ return this;
2151
+ }
2152
+ append(...keys) {
2153
+ const appends = flattenDeep(keys);
2154
+ this.appends = [...this.appends, ...appends];
2155
+ return this;
2156
+ }
2157
+ normalizeCastClassResponse(key, value) {
2158
+ var _value$constructor;
2159
+ return (value === null || value === void 0 || (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name) === "Object" ? value : { [key]: value };
2160
+ }
2161
+ syncOriginal() {
2162
+ this.original = this.getAttributes();
2163
+ return this;
2164
+ }
2165
+ syncChanges() {
2166
+ this.changes = this.getDirty();
2167
+ return this;
2168
+ }
2169
+ syncOriginalAttribute(attribute) {
2170
+ this.syncOriginalAttributes(attribute);
2171
+ }
2172
+ syncOriginalAttributes(...attributes) {
2173
+ attributes = flattenDeep(attributes);
2174
+ const modelAttributes = this.getAttributes();
2175
+ for (const attribute of attributes) this.original[attribute] = modelAttributes[attribute];
2176
+ return this;
2177
+ }
2178
+ isDirty(...attributes) {
2179
+ const changes = this.getDirty();
2180
+ attributes = flattenDeep(attributes);
2181
+ if (attributes.length === 0) return Object.keys(changes).length > 0;
2182
+ for (const attribute of attributes) if (attribute in changes) return true;
2183
+ return false;
2184
+ }
2185
+ getDirty() {
2186
+ const dirty = {};
2187
+ const attributes = this.getAttributes();
2188
+ for (const key in attributes) {
2189
+ const value = attributes[key];
2190
+ if (!this.originalIsEquivalent(key)) dirty[key] = value;
2191
+ }
2192
+ return dirty;
2193
+ }
2194
+ originalIsEquivalent(key) {
2195
+ if (this.original[key] === void 0) return false;
2196
+ const attribute = this.attributes[key];
2197
+ const original = this.original[key];
2198
+ if (attribute === original) return true;
2199
+ else return false;
2200
+ }
2201
+ setAttributes(attributes) {
2202
+ this.attributes = { ...attributes };
2203
+ }
2204
+ setRawAttributes(attributes, sync = false) {
2205
+ this.attributes = attributes;
2206
+ if (sync) this.syncOriginal();
2207
+ return this;
2208
+ }
2209
+ getAttributes() {
2210
+ return { ...this.attributes };
2211
+ }
2212
+ setAttribute(key, value) {
2213
+ const setterMethod = getSetterMethod(key);
2214
+ if (typeof this[setterMethod] === "function") {
2215
+ this[setterMethod](value);
2216
+ return this;
2217
+ }
2218
+ const attrMethod = getAttrMethod(key);
2219
+ if (typeof this[attrMethod] === "function") {
2220
+ const callback = this[attrMethod]().set || ((value$1) => {
2221
+ this.attributes[key] = value$1;
2222
+ });
2223
+ this.attributes = {
2224
+ ...this.attributes,
2225
+ ...this.normalizeCastClassResponse(key, callback(value, this.attributes))
2226
+ };
2227
+ return this;
2228
+ }
2229
+ const castType = this.getCasts()[key];
2230
+ if (this.isCustomCast(castType) && typeof castType !== "string") value = castType.set(this, key, value, this.attributes) ?? "";
2231
+ if (castType === "json") value = JSON.stringify(value);
2232
+ if (castType === "collection") value = JSON.stringify(value);
2233
+ if (value !== null && this.isDateAttribute(key)) value = this.fromDateTime(value);
2234
+ this.attributes[key] = value;
2235
+ return this;
2236
+ }
2237
+ getAttribute(key) {
2238
+ if (!key) return;
2239
+ const getterMethod = getGetterMethod(key);
2240
+ if (typeof this[getterMethod] === "function") return this[getterMethod](this.attributes[key], this.attributes);
2241
+ const attrMethod = getAttrMethod(key);
2242
+ if (typeof this[attrMethod] === "function") return this[attrMethod]().get(this.attributes[key], this.attributes);
2243
+ if (key in this.attributes) {
2244
+ if (this.hasCast(key)) return this.castAttribute(key, this.attributes[key]);
2245
+ if (this.getDates().includes(key)) return this.asDateTime(this.attributes[key]);
2246
+ return this.attributes[key];
2247
+ }
2248
+ if (key in this.relations) return this.relations[key];
2249
+ }
2250
+ castAttribute(key, value) {
2251
+ const castType = this.getCastType(key);
2252
+ if (!castType) return value;
2253
+ if (value === null) return value;
2254
+ switch (castType) {
2255
+ case "int":
2256
+ case "integer": return parseInt(value);
2257
+ case "real":
2258
+ case "float":
2259
+ case "double": return parseFloat(value);
2260
+ case "decimal": return this.asDecimal(value, castType.split(":")[1]);
2261
+ case "string": return String(value);
2262
+ case "bool":
2263
+ case "boolean": return Boolean(value);
2264
+ case "object":
2265
+ case "json": try {
2266
+ return JSON.parse(value);
2267
+ } catch {
2268
+ return null;
2269
+ }
2270
+ case "collection": try {
2271
+ return collect(JSON.parse(value));
2272
+ } catch {
2273
+ return collect([]);
2274
+ }
2275
+ case "date": return this.asDate(value);
2276
+ case "datetime":
2277
+ case "custom_datetime": return this.asDateTime(value);
2278
+ case "timestamp": return this.asTimestamp(value);
2279
+ }
2280
+ if (this.isCustomCast(castType)) return castType.get(this, key, value, this.attributes);
2281
+ return value;
2282
+ }
2283
+ attributesToData() {
2284
+ let attributes = { ...this.attributes };
2285
+ for (const key in attributes) {
2286
+ if (this.hidden.includes(key)) attributes = omit(attributes, [key]);
2287
+ if (this.visible.length > 0 && this.visible.includes(key) === false) attributes = omit(attributes, [key]);
2288
+ }
2289
+ for (const key of this.getDates()) {
2290
+ if (attributes[key] === void 0) continue;
2291
+ attributes[key] = this.serializeDate(this.asDateTime(attributes[key]));
2292
+ }
2293
+ const casts = this.getCasts();
2294
+ for (const key in casts) {
2295
+ const value = casts[key];
2296
+ if (key in attributes === false) continue;
2297
+ attributes[key] = this.castAttribute(key, attributes[key]);
2298
+ if (key in attributes && ["date", "datetime"].includes(String(value))) attributes[key] = this.serializeDate(attributes[key]);
2299
+ if (key in attributes && this.isCustomDateTimeCast(value)) attributes[key] = dayjs(attributes[key]).format(String(value).split(":")[1]);
2300
+ }
2301
+ for (const key of this.appends) attributes[key] = this.mutateAttribute(key, null);
2302
+ return attributes;
2303
+ }
2304
+ mutateAttribute(key, value) {
2305
+ if (typeof this[getGetterMethod(key)] === "function") return this[getGetterMethod(key)](value);
2306
+ else if (typeof this[getAttrMethod(key)] === "function") return this[getAttrMethod(key)]().get(key, this.attributes);
2307
+ else if (key in this) return this[key];
2308
+ return value;
2309
+ }
2310
+ mutateAttributeForArray(_key, _value) {}
2311
+ isDateAttribute(key) {
2312
+ return this.getDates().includes(key) || this.isDateCastable(key);
2313
+ }
2314
+ serializeDate(date) {
2315
+ return date ? dayjs(date).toISOString() : null;
2316
+ }
2317
+ getDates() {
2318
+ return this.usesTimestamps() ? [this.getCreatedAtColumn(), this.getUpdatedAtColumn()] : [];
2319
+ }
2320
+ getCasts() {
2321
+ if (this.getIncrementing()) return {
2322
+ [this.getKeyName()]: this.getKeyType(),
2323
+ ...this.casts
2324
+ };
2325
+ return this.casts;
2326
+ }
2327
+ getCastType(key) {
2328
+ const castType = this.getCasts()[key];
2329
+ let castTypeCacheKey;
2330
+ if (typeof castType === "string") castTypeCacheKey = castType;
2331
+ else if (new castType() instanceof casts_attributes_default) castTypeCacheKey = castType.name;
2332
+ if (castTypeCacheKey && this.getConstructor().castTypeCache[castTypeCacheKey] !== void 0) return this.getConstructor().castTypeCache[castTypeCacheKey];
2333
+ let convertedCastType;
2334
+ if (this.isCustomDateTimeCast(castType)) convertedCastType = "custom_datetime";
2335
+ else if (this.isDecimalCast(castType)) convertedCastType = "decimal";
2336
+ else if (this.isCustomCast(castType)) convertedCastType = castType;
2337
+ else convertedCastType = String(castType).toLocaleLowerCase().trim();
2338
+ return this.getConstructor()[castTypeCacheKey] = convertedCastType;
2339
+ }
2340
+ hasCast(key, types$1 = []) {
2341
+ if (key in this.casts) {
2342
+ types$1 = flat(types$1);
2343
+ return types$1.length > 0 ? types$1.includes(this.getCastType(key)) : true;
2344
+ }
2345
+ return false;
2346
+ }
2347
+ withDayjs(date) {
2348
+ return dayjs(date);
2349
+ }
2350
+ isCustomCast(cast) {
2351
+ return typeof cast === "function" && new cast() instanceof casts_attributes_default;
2352
+ }
2353
+ isCustomDateTimeCast(cast) {
2354
+ if (typeof cast !== "string") return false;
2355
+ return cast.startsWith("date:") || cast.startsWith("datetime:");
2356
+ }
2357
+ isDecimalCast(cast) {
2358
+ if (typeof cast !== "string") return false;
2359
+ return cast.startsWith("decimal:");
2360
+ }
2361
+ isDateCastable(key) {
2362
+ return this.hasCast(key, ["date", "datetime"]);
2363
+ }
2364
+ fromDateTime(value) {
2365
+ return dayjs(this.asDateTime(value)).format(this.getDateFormat());
2366
+ }
2367
+ getDateFormat() {
2368
+ return this.dateFormat || "YYYY-MM-DD HH:mm:ss";
2369
+ }
2370
+ asDecimal(value, decimals) {
2371
+ return parseFloat(value).toFixed(decimals);
2372
+ }
2373
+ asDateTime(value) {
2374
+ if (value === null) return null;
2375
+ if (value instanceof Date) return value;
2376
+ if (typeof value === "number") return /* @__PURE__ */ new Date(value * 1e3);
2377
+ return new Date(value);
2378
+ }
2379
+ asDate(value) {
2380
+ const date = this.asDateTime(value);
2381
+ return dayjs(date).startOf("day").toDate();
2382
+ }
2383
+ };
2384
+ };
2385
+ var has_attributes_default = HasAttributes;
2386
+
2387
+ //#endregion
2388
+ //#region src/concerns/has-global-scopes.ts
2389
+ const HasGlobalScopes = (Model$1) => {
2390
+ return class extends Model$1 {
2391
+ static globalScopes;
2392
+ static addGlobalScope(scope, implementation = null) {
2393
+ if (typeof scope === "string" && implementation instanceof scope_default) {
2394
+ this.globalScopes = set(this.globalScopes ?? {}, this.name + "." + scope, implementation);
2395
+ return implementation;
2396
+ } else if (scope instanceof scope_default) {
2397
+ this.globalScopes = set(this.globalScopes ?? {}, this.name + "." + scope.constructor.name, scope);
2398
+ return scope;
2399
+ }
2400
+ throw new InvalidArgumentError("Global scope must be an instance of Scope.");
2401
+ }
2402
+ static hasGlobalScope(scope) {
2403
+ return this.getGlobalScope(scope) !== null;
2404
+ }
2405
+ static getGlobalScope(scope) {
2406
+ if (typeof scope === "string") return get(this.globalScopes, this.name + "." + scope);
2407
+ return get(this.globalScopes, this.name + "." + scope.constructor.name);
2408
+ }
2409
+ static getAllGlobalScopes() {
2410
+ return this.globalScopes;
2411
+ }
2412
+ static setAllGlobalScopes(scopes) {
2413
+ this.globalScopes = scopes;
2414
+ }
2415
+ getGlobalScopes() {
2416
+ return get(this.constructor.globalScopes, this.constructor.name, {});
2417
+ }
2418
+ };
2419
+ };
2420
+ var has_global_scopes_default = HasGlobalScopes;
2421
+
2422
+ //#endregion
2423
+ //#region src/hooks.ts
2424
+ var Hooks = class {
2425
+ hooks = {
2426
+ creating: [],
2427
+ created: [],
2428
+ updating: [],
2429
+ updated: [],
2430
+ saving: [],
2431
+ saved: [],
2432
+ deleting: [],
2433
+ deleted: [],
2434
+ restoring: [],
2435
+ restored: [],
2436
+ trashed: [],
2437
+ forceDeleting: [],
2438
+ forceDeleted: []
2439
+ };
2440
+ add(hook, callback) {
2441
+ this.hooks[hook].push(callback);
2442
+ }
2443
+ async exec(hook, data) {
2444
+ const callbacks = this.hooks[hook] ?? [];
2445
+ for (const callback of callbacks) await callback(...data);
2446
+ return true;
2447
+ }
2448
+ };
2449
+ var hooks_default = Hooks;
2450
+
2451
+ //#endregion
2452
+ //#region src/concerns/has-hooks.ts
2453
+ const HasHooks = (Model$1) => {
2454
+ return class extends Model$1 {
2455
+ static hooks = null;
2456
+ static addHook(hook, callback) {
2457
+ if (this.hooks instanceof hooks_default === false) this.hooks = new hooks_default();
2458
+ this.hooks.add(hook, callback);
2459
+ }
2460
+ static creating(callback) {
2461
+ this.addHook("creating", callback);
2462
+ }
2463
+ static created(callback) {
2464
+ this.addHook("created", callback);
2465
+ }
2466
+ static updating(callback) {
2467
+ this.addHook("updating", callback);
2468
+ }
2469
+ static updated(callback) {
2470
+ this.addHook("updated", callback);
2471
+ }
2472
+ static saving(callback) {
2473
+ this.addHook("saving", callback);
2474
+ }
2475
+ static saved(callback) {
2476
+ this.addHook("saved", callback);
2477
+ }
2478
+ static deleting(callback) {
2479
+ this.addHook("deleting", callback);
2480
+ }
2481
+ static deleted(callback) {
2482
+ this.addHook("deleted", callback);
2483
+ }
2484
+ static restoring(callback) {
2485
+ this.addHook("restoring", callback);
2486
+ }
2487
+ static restored(callback) {
2488
+ this.addHook("restored", callback);
2489
+ }
2490
+ static trashed(callback) {
2491
+ this.addHook("trashed", callback);
2492
+ }
2493
+ static forceDeleted(callback) {
2494
+ this.addHook("forceDeleted", callback);
2495
+ }
2496
+ async execHooks(hook, options) {
2497
+ if (this.constructor.hooks instanceof hooks_default === false) return;
2498
+ return await this.constructor.hooks.exec(hook, [this, options]);
2499
+ }
2500
+ };
2501
+ };
2502
+ var has_hooks_default = HasHooks;
2503
+
2504
+ //#endregion
2505
+ //#region src/relations/has-one-or-many.ts
2506
+ const HasOneOrMany = (Relation$1) => {
2507
+ return class extends Relation$1 {
2508
+ getRelationValue(dictionary, key, type$1) {
2509
+ const value = dictionary[key];
2510
+ return type$1 === "one" ? value[0] : new collection_default(value);
2511
+ }
2512
+ matchOneOrMany(models, results, relation, type$1) {
2513
+ const dictionary = this.buildDictionary(results);
2514
+ models.map((model) => {
2515
+ const key = model.attributes[this.localKey];
2516
+ if (dictionary[key] !== void 0) model.setRelation(relation, this.getRelationValue(dictionary, key, type$1));
2517
+ });
2518
+ return models;
2519
+ }
2520
+ buildDictionary(results) {
2521
+ const foreign = this.getForeignKeyName();
2522
+ return collect(results).mapToDictionary((result) => [result[foreign], result]).all();
2523
+ }
2524
+ async save(model) {
2525
+ this.setForeignAttributesForCreate(model);
2526
+ return await model.save() ? model : false;
2527
+ }
2528
+ async saveMany(models) {
2529
+ await Promise.all(models.map(async (model) => {
2530
+ await this.save(model);
2531
+ }));
2532
+ return models instanceof collection_default ? models : new collection_default(models);
2533
+ }
2534
+ async create(attributes = {}) {
2535
+ return await tap(this.related.constructor.init(attributes), async (instance) => {
2536
+ this.setForeignAttributesForCreate(instance);
2537
+ await instance.save();
2538
+ });
2539
+ }
2540
+ async createMany(records) {
2541
+ const instances = await Promise.all(records.map(async (record) => {
2542
+ return await this.create(record);
2543
+ }));
2544
+ return instances instanceof collection_default ? instances : new collection_default(instances);
2545
+ }
2546
+ setForeignAttributesForCreate(model) {
2547
+ model[this.getForeignKeyName()] = this.getParentKey();
2548
+ }
2549
+ getForeignKeyName() {
2550
+ const segments = this.getQualifiedForeignKeyName().split(".");
2551
+ return segments[segments.length - 1];
2552
+ }
2553
+ getParentKey() {
2554
+ return this.parent.attributes[this.localKey];
2555
+ }
2556
+ getQualifiedForeignKeyName() {
2557
+ return this.foreignKey;
2558
+ }
2559
+ getExistenceCompareKey() {
2560
+ return this.getQualifiedForeignKeyName();
2561
+ }
2562
+ addConstraints() {
2563
+ if (this.constructor.constraints) {
2564
+ const query = this.getRelationQuery();
2565
+ query.where(this.foreignKey, "=", this.getParentKey());
2566
+ query.whereNotNull(this.foreignKey);
2567
+ }
2568
+ }
2569
+ };
2570
+ };
2571
+ var has_one_or_many_default = HasOneOrMany;
2572
+
2573
+ //#endregion
2574
+ //#region src/relations/has-many.ts
2575
+ var HasMany = class extends compose(relation_default, has_one_or_many_default) {
2576
+ foreignKey;
2577
+ localKey;
2578
+ constructor(query, parent, foreignKey, localKey) {
2579
+ super(query, parent);
2580
+ this.foreignKey = foreignKey;
2581
+ this.localKey = localKey;
2582
+ this.addConstraints();
2583
+ return this.asProxy();
2584
+ }
2585
+ initRelation(models, relation) {
2586
+ models.map((model) => {
2587
+ model.setRelation(relation, new collection_default([]));
2588
+ });
2589
+ return models;
2590
+ }
2591
+ async getResults() {
2592
+ return this.getParentKey() !== null ? await this.query.get() : new collection_default([]);
2593
+ }
2594
+ getForeignKeyName() {
2595
+ var _this$foreignKey;
2596
+ const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
2597
+ return segments === null || segments === void 0 ? void 0 : segments.pop();
2598
+ }
2599
+ buildDictionary(results) {
2600
+ const foreign = this.getForeignKeyName();
2601
+ return collect$1(results).mapToDictionary((result) => [result[foreign], result]).all();
2602
+ }
2603
+ match(models, results, relation) {
2604
+ return this.matchOneOrMany(models, results, relation, "many");
2605
+ }
2606
+ addEagerConstraints(models) {
2607
+ this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
2608
+ }
2609
+ };
2610
+ var has_many_default = HasMany;
2611
+
2612
+ //#endregion
2613
+ //#region src/relations/has-one.ts
2614
+ var HasOne = class extends compose(relation_default, has_one_or_many_default, supports_default_models_default) {
2615
+ foreignKey;
2616
+ localKey;
2617
+ constructor(query, parent, foreignKey, localKey) {
2618
+ super(query, parent);
2619
+ this.foreignKey = foreignKey;
2620
+ this.localKey = localKey;
2621
+ this.addConstraints();
2622
+ return this.asProxy();
2623
+ }
2624
+ initRelation(models, relation) {
2625
+ models.map((model) => {
2626
+ model.setRelation(relation, this.getDefaultFor(model));
2627
+ });
2628
+ return models;
2629
+ }
2630
+ matchOne(models, results, relation) {
2631
+ return this.matchOneOrMany(models, results, relation, "one");
2632
+ }
2633
+ getForeignKeyName() {
2634
+ var _this$foreignKey;
2635
+ const segments = (_this$foreignKey = this.foreignKey) === null || _this$foreignKey === void 0 ? void 0 : _this$foreignKey.split(".");
2636
+ return segments === null || segments === void 0 ? void 0 : segments.pop();
2637
+ }
2638
+ async getResults() {
2639
+ if (this.getParentKey() === null) return this.getDefaultFor(this.parent);
2640
+ return await this.query.first() || this.getDefaultFor(this.parent);
2641
+ }
2642
+ match(models, results, relation) {
2643
+ return this.matchOneOrMany(models, results, relation, "one");
2644
+ }
2645
+ addEagerConstraints(models) {
2646
+ this.query.whereIn(this.foreignKey, this.getKeys(models, this.localKey));
2647
+ }
2648
+ newRelatedInstanceFor(parent) {
2649
+ return this.related.newInstance().setAttribute(this.getForeignKeyName(), parent[this.localKey]);
2650
+ }
2651
+ };
2652
+ var has_one_default = HasOne;
2653
+
2654
+ //#endregion
2655
+ //#region src/relations/has-many-through.ts
2656
+ var HasManyThrough = class extends relation_default {
2657
+ throughParent;
2658
+ farParent;
2659
+ firstKey;
2660
+ secondKey;
2661
+ localKey;
2662
+ secondLocalKey;
2663
+ constructor(query, farParent, throughParent, firstKey, secondKey, localKey, secondLocalKey) {
2664
+ super(query, throughParent);
2665
+ this.localKey = localKey;
2666
+ this.firstKey = firstKey;
2667
+ this.secondKey = secondKey;
2668
+ this.farParent = farParent;
2669
+ this.throughParent = throughParent;
2670
+ this.secondLocalKey = secondLocalKey;
2671
+ return this.asProxy();
2672
+ }
2673
+ addConstraints() {
2674
+ const localValue = this.farParent[this.localKey];
2675
+ this.performJoin();
2676
+ if (this.constructor.constraints) this.query.where(this.getQualifiedFirstKeyName(), "=", localValue);
2677
+ }
2678
+ performJoin(query = null) {
2679
+ query = query || this.query;
2680
+ const farKey = this.getQualifiedFarKeyName();
2681
+ query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", farKey);
2682
+ if (this.throughParentSoftDeletes()) query.withGlobalScope("SoftDeletableHasManyThrough", (query$1) => {
2683
+ query$1.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
2684
+ });
2685
+ }
2686
+ getQualifiedParentKeyName() {
2687
+ return this.parent.qualifyColumn(this.secondLocalKey);
2688
+ }
2689
+ throughParentSoftDeletes() {
2690
+ return this.throughParent.pluginInitializers["SoftDeletes"] !== void 0;
2691
+ }
2692
+ withTrashedParents() {
2693
+ this.query.withoutGlobalScope("SoftDeletableHasManyThrough");
2694
+ return this;
2695
+ }
2696
+ addEagerConstraints(models) {
2697
+ const whereIn = this.whereInMethod(this.farParent, this.localKey);
2698
+ this.whereInEager(whereIn, this.getQualifiedFirstKeyName(), this.getKeys(models, this.localKey));
2699
+ }
2700
+ initRelation(models, relation) {
2701
+ for (const model of models) model.setRelation(relation, this.related.newCollection());
2702
+ return models;
2703
+ }
2704
+ match(models, results, relation) {
2705
+ const dictionary = this.buildDictionary(results);
2706
+ for (const model of models) {
2707
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
2708
+ if (dictionary[key] !== void 0) model.setRelation(relation, this.related.newCollection(dictionary[key]));
2709
+ }
2710
+ return models;
2711
+ }
2712
+ buildDictionary(results) {
2713
+ const dictionary = {};
2714
+ for (const result of results) {
2715
+ if (dictionary[result.laravel_through_key] === void 0) dictionary[result.laravel_through_key] = [];
2716
+ dictionary[result.laravel_through_key].push(result);
2717
+ }
2718
+ return dictionary;
2719
+ }
2720
+ async firstOrNew(attributes) {
2721
+ return await this.where(attributes).first() || this.related.newInstance(attributes);
2722
+ }
2723
+ async updateOrCreate(attributes, values = {}) {
2724
+ return tap(await this.firstOrCreate(attributes, values), async (instance) => {
2725
+ if (!instance.wasRecentlyCreated) await instance.fill(values).save();
2726
+ });
2727
+ }
2728
+ async firstWhere(column, operator = null, value = null, boolean = "and") {
2729
+ return await this.where(column, operator, value, boolean).first();
2730
+ }
2731
+ async first(columns = ["*"]) {
2732
+ const results = await this.take(1).get(columns);
2733
+ return results.count() > 0 ? results.first() : null;
2734
+ }
2735
+ async firstOrFail(columns = ["*"]) {
2736
+ const model = await this.first(columns);
2737
+ if (model) return model;
2738
+ throw new ModelNotFoundError().setModel(this.related.constructor);
2739
+ }
2740
+ async firstOr(columns = ["*"], callback = null) {
2741
+ if (typeof columns === "function") {
2742
+ callback = columns;
2743
+ columns = ["*"];
2744
+ }
2745
+ const model = await this.first(columns);
2746
+ if (model) return model;
2747
+ return callback === null || callback === void 0 ? void 0 : callback();
2748
+ }
2749
+ async find(id, columns = ["*"]) {
2750
+ if (isArray(id)) return await this.findMany(id, columns);
2751
+ return await this.where(this.getRelated().getQualifiedKeyName(), "=", id).first(columns);
2752
+ }
2753
+ async findMany(ids, columns = ["*"]) {
2754
+ if (ids.length === 0) return this.getRelated().newCollection();
2755
+ return await this.whereIn(this.getRelated().getQualifiedKeyName(), ids).get(columns);
2756
+ }
2757
+ async findOrFail(id, columns = ["*"]) {
2758
+ const result = await this.find(id, columns);
2759
+ if (Array.isArray(id)) {
2760
+ if (result.count() === id.length) return result;
2761
+ } else if (result) return result;
2762
+ throw new ModelNotFoundError().setModel(this.related.constructor, id);
2763
+ }
2764
+ async getResults() {
2765
+ return this.farParent[this.localKey] ? await this.get() : this.related.newCollection();
2766
+ }
2767
+ async get(columns = ["*"]) {
2768
+ const builder = this.prepareQueryBuilder(columns);
2769
+ let models = await builder.getModels();
2770
+ if (models.count() > 0) models = await builder.eagerLoadRelations(models);
2771
+ return this.related.newCollection(models);
2772
+ }
2773
+ async paginate(perPage = null, columns = ["*"], pageName = "page", page = null) {
2774
+ this.query.addSelect(this.shouldSelect(columns));
2775
+ return await this.query.paginate(perPage, columns, pageName, page);
2776
+ }
2777
+ shouldSelect(columns = ["*"]) {
2778
+ if ((columns === null || columns === void 0 ? void 0 : columns.at(0)) == "*") columns = [this.related.getTable() + ".*"];
2779
+ return [...columns, this.getQualifiedFirstKeyName() + " as laravel_through_key"];
2780
+ }
2781
+ async chunk(count, callback) {
2782
+ return await this.prepareQueryBuilder().chunk(count, callback);
2783
+ }
2784
+ prepareQueryBuilder(columns = ["*"]) {
2785
+ const builder = this.query.applyScopes();
2786
+ return builder.addSelect(this.shouldSelect(builder.getQuery().columns ? [] : columns));
2787
+ }
2788
+ getRelationExistenceQuery(query, parentQuery, columns = ["*"]) {
2789
+ if (parentQuery.getQuery().from === query.getQuery().from) return this.getRelationExistenceQueryForSelfRelation(query, parentQuery, columns);
2790
+ if (parentQuery.getQuery().from === this.throughParent.getTable()) return this.getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns);
2791
+ this.performJoin(query);
2792
+ return query.select(columns).where(this.getQualifiedLocalKeyName(), "=", this.getQualifiedFirstKeyName());
2793
+ }
2794
+ getRelationExistenceQueryForSelfRelation(query, parentQuery, columns = ["*"]) {
2795
+ const hash = this.getRelationCountHash();
2796
+ query.from(query.getModel().getTable() + " as " + hash);
2797
+ query.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", hash + "." + this.secondKey);
2798
+ if (this.throughParentSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
2799
+ query.getModel().setTable(hash);
2800
+ return query.select(columns).whereColumn(parentQuery.getQuery().from + "." + this.localKey, "=", this.getQualifiedFirstKeyName());
2801
+ }
2802
+ getRelationExistenceQueryForThroughSelfRelation(query, parentQuery, columns = ["*"]) {
2803
+ const hash = this.getRelationCountHash();
2804
+ const table = this.throughParent.getTable() + " as " + hash;
2805
+ query.join(table, hash + "." + this.secondLocalKey, "=", this.getQualifiedFarKeyName());
2806
+ if (this.throughParentSoftDeletes()) query.whereNull(hash + "." + this.throughParent.getDeletedAtColumn());
2807
+ return query.select(columns).where(parentQuery.getQuery().from + "." + this.localKey, "=", hash + "." + this.firstKey);
2808
+ }
2809
+ getQualifiedFarKeyName() {
2810
+ return this.getQualifiedForeignKeyName();
2811
+ }
2812
+ getFirstKeyName() {
2813
+ return this.firstKey;
2814
+ }
2815
+ getQualifiedFirstKeyName() {
2816
+ return this.throughParent.qualifyColumn(this.firstKey);
2817
+ }
2818
+ getForeignKeyName() {
2819
+ return this.secondKey;
2820
+ }
2821
+ getQualifiedForeignKeyName() {
2822
+ return this.related.qualifyColumn(this.secondKey);
2823
+ }
2824
+ getLocalKeyName() {
2825
+ return this.localKey;
2826
+ }
2827
+ getQualifiedLocalKeyName() {
2828
+ return this.farParent.qualifyColumn(this.localKey);
2829
+ }
2830
+ getSecondLocalKeyName() {
2831
+ return this.secondLocalKey;
2832
+ }
2833
+ };
2834
+ var has_many_through_default = HasManyThrough;
2835
+
2836
+ //#endregion
2837
+ //#region src/relations/has-one-through.ts
2838
+ var HasOneThrough = class extends compose(has_many_through_default, supports_default_models_default) {
2839
+ async getResults() {
2840
+ return await this.first() || this.getDefaultFor(this.farParent);
2841
+ }
2842
+ initRelation(models, relation) {
2843
+ for (const model of models) model.setRelation(relation, this.getDefaultFor(model));
2844
+ return models;
2845
+ }
2846
+ match(models, results, relation) {
2847
+ const dictionary = this.buildDictionary(results);
2848
+ for (const model of models) {
2849
+ const key = this.getDictionaryKey(model.getAttribute(this.localKey));
2850
+ if (dictionary[key] !== void 0) {
2851
+ const value = dictionary[key];
2852
+ model.setRelation(relation, value[0]);
2853
+ }
2854
+ }
2855
+ return models;
2856
+ }
2857
+ newRelatedInstanceFor(_parent) {
2858
+ return this.related.newInstance();
2859
+ }
2860
+ };
2861
+ var has_one_through_default = HasOneThrough;
2862
+
2863
+ //#endregion
2864
+ //#region src/concerns/has-relations.ts
2865
+ const HasRelations = (Model$1) => {
2866
+ return class extends Model$1 {
2867
+ relations = {};
2868
+ getRelation(relation) {
2869
+ return this.relations[relation];
2870
+ }
2871
+ setRelation(relation, value) {
2872
+ this.relations[relation] = value;
2873
+ return this;
2874
+ }
2875
+ unsetRelation(relation) {
2876
+ this.relations = omit(this.relations, [relation]);
2877
+ return this;
2878
+ }
2879
+ relationLoaded(relation) {
2880
+ return this.relations[relation] !== void 0;
2881
+ }
2882
+ related(relation) {
2883
+ if (typeof this[getRelationMethod(relation)] !== "function") {
2884
+ const message = `Model [${this.constructor.name}]'s relation [${relation}] doesn't exist.`;
2885
+ throw new RelationNotFoundError(message);
2886
+ }
2887
+ return this[getRelationMethod(relation)]();
2888
+ }
2889
+ async getRelated(relation) {
2890
+ return await this.related(relation).getResults();
2891
+ }
2892
+ relationsToData() {
2893
+ const data = {};
2894
+ for (const key in this.relations) {
2895
+ if (this.hidden.includes(key)) continue;
2896
+ if (this.visible.length > 0 && this.visible.includes(key) === false) continue;
2897
+ data[key] = this.relations[key] instanceof Array ? this.relations[key].map((item) => item.toData()) : this.relations[key] === null ? null : this.relations[key].toData();
2898
+ }
2899
+ return data;
2900
+ }
2901
+ guessBelongsToRelation() {
2902
+ const functionName = (/* @__PURE__ */ new Error()).stack.split("\n")[2].split(" ")[5];
2903
+ return getRelationName(functionName);
2904
+ }
2905
+ joiningTable(related, instance = null) {
2906
+ return [instance ? instance.joiningTableSegment() : snakeCase(related.name), this.joiningTableSegment()].sort().join("_").toLocaleLowerCase();
2907
+ }
2908
+ joiningTableSegment() {
2909
+ return snakeCase(this.constructor.name);
2910
+ }
2911
+ hasOne(related, foreignKey = null, localKey = null) {
2912
+ const query = related.query();
2913
+ const instance = new related();
2914
+ foreignKey = foreignKey || this.getForeignKey();
2915
+ localKey = localKey || this.getKeyName();
2916
+ return new has_one_default(query, this, instance.getTable() + "." + foreignKey, localKey);
2917
+ }
2918
+ hasMany(related, foreignKey = null, localKey = null) {
2919
+ const query = related.query();
2920
+ const instance = new related();
2921
+ foreignKey = foreignKey || this.getForeignKey();
2922
+ localKey = localKey || this.getKeyName();
2923
+ return new has_many_default(query, this, instance.getTable() + "." + foreignKey, localKey);
2924
+ }
2925
+ belongsTo(related, foreignKey = null, ownerKey = null, relation = null) {
2926
+ const query = related.query();
2927
+ const instance = new related();
2928
+ foreignKey = foreignKey || instance.getForeignKey();
2929
+ ownerKey = ownerKey || instance.getKeyName();
2930
+ relation = relation || this.guessBelongsToRelation();
2931
+ return new belongs_to_default(query, this, foreignKey, ownerKey, relation);
2932
+ }
2933
+ belongsToMany(related, table = null, foreignPivotKey = null, relatedPivotKey = null, parentKey = null, relatedKey = null) {
2934
+ const query = related.query();
2935
+ const instance = new related();
2936
+ table = table || this.joiningTable(related, instance);
2937
+ foreignPivotKey = foreignPivotKey || this.getForeignKey();
2938
+ relatedPivotKey = relatedPivotKey || instance.getForeignKey();
2939
+ parentKey = parentKey || this.getKeyName();
2940
+ relatedKey = relatedKey || instance.getKeyName();
2941
+ return new belongs_to_many_default(query, this, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey);
2942
+ }
2943
+ hasOneThrough(related, through, firstKey = null, secondKey = null, localKey = null, secondLocalKey = null) {
2944
+ through = new through();
2945
+ const query = related.query();
2946
+ firstKey = firstKey || this.getForeignKey();
2947
+ secondKey = secondKey || through.getForeignKey();
2948
+ return new has_one_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
2949
+ }
2950
+ hasManyThrough(related, through, firstKey = null, secondKey = null, localKey = null, secondLocalKey = null) {
2951
+ through = new through();
2952
+ const query = related.query();
2953
+ firstKey = firstKey || this.getForeignKey();
2954
+ secondKey = secondKey || through.getForeignKey();
2955
+ return new has_many_through_default(query, this, through, firstKey, secondKey, localKey || this.getKeyName(), secondLocalKey || through.getKeyName());
2956
+ }
2957
+ };
2958
+ };
2959
+ var has_relations_default = HasRelations;
2960
+
2961
+ //#endregion
2962
+ //#region src/concerns/has-timestamps.ts
2963
+ const HasTimestamps = (Model$1) => {
2964
+ return class extends Model$1 {
2965
+ static CREATED_AT = "created_at";
2966
+ static UPDATED_AT = "updated_at";
2967
+ static DELETED_AT = "deleted_at";
2968
+ timestamps = true;
2969
+ dateFormat = "YYYY-MM-DD HH:mm:ss";
2970
+ usesTimestamps() {
2971
+ return this.timestamps;
2972
+ }
2973
+ updateTimestamps() {
2974
+ const time = this.freshTimestampString();
2975
+ const updatedAtColumn = this.getUpdatedAtColumn();
2976
+ if (updatedAtColumn && !this.isDirty(updatedAtColumn)) this.setUpdatedAt(time);
2977
+ const createdAtColumn = this.getCreatedAtColumn();
2978
+ if (!this.exists && createdAtColumn && !this.isDirty(createdAtColumn)) this.setCreatedAt(time);
2979
+ return this;
2980
+ }
2981
+ getCreatedAtColumn() {
2982
+ return this.constructor.CREATED_AT;
2983
+ }
2984
+ getUpdatedAtColumn() {
2985
+ return this.constructor.UPDATED_AT;
2986
+ }
2987
+ setCreatedAt(value) {
2988
+ this.attributes[this.getCreatedAtColumn()] = value;
2989
+ return this;
2990
+ }
2991
+ setUpdatedAt(value) {
2992
+ this.attributes[this.getUpdatedAtColumn()] = value;
2993
+ return this;
2994
+ }
2995
+ freshTimestamp() {
2996
+ const time = /* @__PURE__ */ new Date();
2997
+ time.setMilliseconds(0);
2998
+ return time;
2999
+ }
3000
+ freshTimestampString() {
3001
+ return this.fromDateTime(this.freshTimestamp());
3002
+ }
3003
+ };
3004
+ };
3005
+ var has_timestamps_default = HasTimestamps;
3006
+
3007
+ //#endregion
3008
+ //#region src/concerns/hides-attributes.ts
3009
+ const HidesAttributes = (Model$1) => {
3010
+ return class extends Model$1 {
3011
+ hidden = [];
3012
+ visible = [];
3013
+ makeVisible(...keys) {
3014
+ const visible = flattenDeep(keys);
3015
+ if (this.visible.length > 0) this.visible = [...this.visible, ...visible];
3016
+ this.hidden = diff(this.hidden, visible);
3017
+ return this;
3018
+ }
3019
+ makeHidden(key, ...keys) {
3020
+ const hidden = flattenDeep([...key, ...keys]);
3021
+ if (this.hidden.length > 0) this.hidden = [...this.hidden, ...hidden];
3022
+ return this;
3023
+ }
3024
+ getHidden() {
3025
+ return this.hidden;
3026
+ }
3027
+ getVisible() {
3028
+ return this.visible;
3029
+ }
3030
+ setHidden(hidden) {
3031
+ this.hidden = hidden;
3032
+ return this;
3033
+ }
3034
+ setVisible(visible) {
3035
+ this.visible = visible;
3036
+ return this;
3037
+ }
3038
+ };
3039
+ };
3040
+ var hides_attributes_default = HidesAttributes;
3041
+
3042
+ //#endregion
3043
+ //#region src/concerns/unique-ids.ts
3044
+ const UniqueIds = (Model$1) => {
3045
+ return class extends Model$1 {
3046
+ useUniqueIds = false;
3047
+ usesUniqueIds() {
3048
+ return this.useUniqueIds;
3049
+ }
3050
+ uniqueIds() {
3051
+ return [];
3052
+ }
3053
+ newUniqueId() {
3054
+ return null;
3055
+ }
3056
+ setUniqueIds() {
3057
+ const uniqueIds = this.uniqueIds();
3058
+ for (const column of uniqueIds) if (this[column] === null || this[column] === void 0) this[column] = this.newUniqueId();
3059
+ }
3060
+ };
3061
+ };
3062
+ var unique_ids_default = UniqueIds;
3063
+
3064
+ //#endregion
3065
+ //#region src/model.ts
3066
+ const BaseModel = compose(class {}, has_attributes_default, hides_attributes_default, has_relations_default, has_timestamps_default, has_hooks_default, has_global_scopes_default, unique_ids_default);
3067
+ var Model = class Model extends BaseModel {
3068
+ primaryKey = "id";
3069
+ builder = null;
3070
+ table = null;
3071
+ keyType = "int";
3072
+ incrementing = true;
3073
+ withCount = [];
3074
+ perPage = 15;
3075
+ static globalScopes = {};
3076
+ static pluginInitializers = {};
3077
+ static _booted = {};
3078
+ static resolver;
3079
+ connection = null;
3080
+ eagerLoad = {};
3081
+ exists = false;
3082
+ with = [];
3083
+ trx = null;
3084
+ constructor(attributes = {}) {
3085
+ super();
3086
+ this.bootIfNotBooted();
3087
+ this.initializePlugins();
3088
+ this.syncOriginal();
3089
+ this.fill(attributes);
3090
+ return this.asProxy();
3091
+ }
3092
+ static query(trx = null) {
3093
+ return new this().newQuery(trx);
3094
+ }
3095
+ static on(connection = null) {
3096
+ const instance = new this();
3097
+ instance.setConnection(connection);
3098
+ return instance.newQuery();
3099
+ }
3100
+ static init(attributes = {}) {
3101
+ return new this(attributes);
3102
+ }
3103
+ static extend(plugin, options) {
3104
+ plugin(this, options);
3105
+ }
3106
+ static make(attributes = {}) {
3107
+ const instance = new this();
3108
+ for (const attribute in attributes) if (typeof instance[getRelationMethod(attribute)] !== "function") instance.setAttribute(attribute, attributes[attribute]);
3109
+ else {
3110
+ const relation = instance[getRelationMethod(attribute)]();
3111
+ const related = relation.getRelated().constructor;
3112
+ if (relation instanceof has_one_default || relation instanceof belongs_to_default) instance.setRelation(attribute, related.make(attributes[attribute]));
3113
+ else if ((relation instanceof has_many_default || relation instanceof belongs_to_many_default) && Array.isArray(attributes[attribute])) instance.setRelation(attribute, new collection_default(attributes[attribute].map((item) => related.make(item))));
3114
+ }
3115
+ return instance;
3116
+ }
3117
+ getConstructor() {
3118
+ return this.constructor;
3119
+ }
3120
+ bootIfNotBooted() {
3121
+ if (this.constructor._booted[this.constructor.name] === void 0) {
3122
+ this.constructor._booted[this.constructor.name] = true;
3123
+ this.constructor.booting();
3124
+ this.initialize();
3125
+ this.constructor.boot();
3126
+ this.constructor.booted();
3127
+ }
3128
+ }
3129
+ static booting() {}
3130
+ static boot() {}
3131
+ static booted() {}
3132
+ static setConnectionResolver(resolver) {
3133
+ this.resolver = resolver;
3134
+ }
3135
+ initialize() {}
3136
+ initializePlugins() {
3137
+ if (typeof this.constructor.pluginInitializers[this.constructor.name] === "undefined") return;
3138
+ for (const method of this.constructor.pluginInitializers[this.constructor.name]) this[method]();
3139
+ }
3140
+ addPluginInitializer(method) {
3141
+ if (!this.constructor.pluginInitializers[this.constructor.name]) this.constructor.pluginInitializers[this.constructor.name] = [];
3142
+ this.constructor.pluginInitializers[this.constructor.name].push(method);
3143
+ }
3144
+ newInstance(attributes = {}, exists = false) {
3145
+ const model = new this.constructor();
3146
+ model.exists = exists;
3147
+ model.setConnection(this.getConnectionName());
3148
+ model.setTable(this.getTable());
3149
+ model.fill(attributes);
3150
+ return model;
3151
+ }
3152
+ newFromBuilder(attributes = {}, connection = null) {
3153
+ const model = this.newInstance({}, true);
3154
+ model.setRawAttributes(attributes, true);
3155
+ model.setConnection(connection || this.getConnectionName());
3156
+ return model;
3157
+ }
3158
+ asProxy() {
3159
+ return new Proxy(this, {
3160
+ get: function(target, prop) {
3161
+ if (target[prop] !== void 0) return target[prop];
3162
+ if (typeof prop === "string") return target.getAttribute(prop);
3163
+ },
3164
+ set: function(target, prop, value) {
3165
+ if (target[prop] !== void 0 && typeof target !== "function") {
3166
+ target[prop] = value;
3167
+ return target;
3168
+ }
3169
+ if (typeof prop === "string") return target.setAttribute(prop, value);
3170
+ return target;
3171
+ }
3172
+ });
3173
+ }
3174
+ getKey() {
3175
+ return this.getAttribute(this.getKeyName());
3176
+ }
3177
+ getKeyName() {
3178
+ return this.primaryKey;
3179
+ }
3180
+ getForeignKey() {
3181
+ return snakeCase(this.constructor.name) + "_" + this.getKeyName();
3182
+ }
3183
+ getConnectionName() {
3184
+ return this.connection;
3185
+ }
3186
+ getTable() {
3187
+ return this.table || pluralize(snakeCase(this.constructor.name));
3188
+ }
3189
+ getConnection() {
3190
+ if (this.constructor.resolver) return this.constructor.resolver.getConnection(this.connection);
3191
+ return arquebus_default.fire(this.connection);
3192
+ }
3193
+ setConnection(connection) {
3194
+ this.connection = connection;
3195
+ return this;
3196
+ }
3197
+ getKeyType() {
3198
+ return this.keyType;
3199
+ }
3200
+ newQuery(trx = null) {
3201
+ return this.addGlobalScopes(this.newQueryWithoutScopes(trx));
3202
+ }
3203
+ newQueryWithoutScopes(trx = null) {
3204
+ return this.newModelQuery(trx).with(this.with).withCount(this.withCount);
3205
+ }
3206
+ newModelQuery(trx = null) {
3207
+ return new builder_default(trx || this.getConnection()).setModel(this);
3208
+ }
3209
+ addGlobalScopes(builder) {
3210
+ const globalScopes = this.getGlobalScopes();
3211
+ for (const identifier in globalScopes) {
3212
+ const scope = globalScopes[identifier];
3213
+ builder.withGlobalScope(identifier, scope);
3214
+ }
3215
+ return builder;
3216
+ }
3217
+ hasNamedScope(name$1) {
3218
+ const scope = getScopeMethod(name$1);
3219
+ return typeof this[scope] === "function";
3220
+ }
3221
+ callNamedScope(scope, parameters) {
3222
+ const scopeMethod = getScopeMethod(scope);
3223
+ return this[scopeMethod](...parameters);
3224
+ }
3225
+ setTable(table) {
3226
+ this.table = table;
3227
+ return this;
3228
+ }
3229
+ newCollection(models = []) {
3230
+ return new collection_default(models);
3231
+ }
3232
+ async load(...relations) {
3233
+ await this.constructor.query().with(...relations).eagerLoadRelations([this]);
3234
+ return this;
3235
+ }
3236
+ async loadAggregate(relations, column, callback = null) {
3237
+ console.log(relations);
3238
+ await new collection_default([this]).loadAggregate(relations, column, callback);
3239
+ return this;
3240
+ }
3241
+ async loadCount(...relations) {
3242
+ relations = flattenDeep(relations);
3243
+ return await this.loadAggregate(relations, "*", "count");
3244
+ }
3245
+ async loadMax(relations, column) {
3246
+ return await this.loadAggregate(relations, column, "max");
3247
+ }
3248
+ async loadMin(relations, column) {
3249
+ return await this.loadAggregate(relations, column, "min");
3250
+ }
3251
+ async loadSum(relations, column) {
3252
+ return await this.loadAggregate(relations, column, "sum");
3253
+ }
3254
+ async increment(column, amount = 1, extra = {}, options = {}) {
3255
+ return await this.incrementOrDecrement(column, amount, extra, "increment", options);
3256
+ }
3257
+ async decrement(column, amount = 1, extra = {}, options = {}) {
3258
+ return await this.incrementOrDecrement(column, amount, extra, "decrement", options);
3259
+ }
3260
+ async incrementOrDecrement(column, amount, extra, method, options) {
3261
+ const query = this.newModelQuery(options.client);
3262
+ if (!this.exists) return await query[method](column, amount, extra);
3263
+ this.attributes[column] = this[column] + (method === "increment" ? amount : amount * -1);
3264
+ for (const key in extra) this.attributes[key] = extra[key];
3265
+ await this.execHooks("updating", options);
3266
+ return await tap(await query.where(this.getKeyName(), this.getKey())[method](column, amount, extra), async () => {
3267
+ this.syncChanges();
3268
+ await this.execHooks("updated", options);
3269
+ this.syncOriginalAttribute(column);
3270
+ });
3271
+ }
3272
+ toData() {
3273
+ return assign(this.attributesToData(), this.relationsToData());
3274
+ }
3275
+ toJSON() {
3276
+ return this.toData();
3277
+ }
3278
+ toJson(...args) {
3279
+ return JSON.stringify(this.toData(), ...args);
3280
+ }
3281
+ toString() {
3282
+ return this.toJson();
3283
+ }
3284
+ fill(attributes) {
3285
+ for (const key in attributes) this.setAttribute(key, attributes[key]);
3286
+ return this;
3287
+ }
3288
+ transacting(trx) {
3289
+ this.trx = trx;
3290
+ return this;
3291
+ }
3292
+ trashed() {
3293
+ return this[this.getDeletedAtColumn()] !== null;
3294
+ }
3295
+ getIncrementing() {
3296
+ return this.incrementing;
3297
+ }
3298
+ setIncrementing(value) {
3299
+ this.incrementing = value;
3300
+ return this;
3301
+ }
3302
+ async save(options = {}) {
3303
+ const query = this.newModelQuery(options.client);
3304
+ let saved;
3305
+ await this.execHooks("saving", options);
3306
+ if (this.exists) if (this.isDirty() === false) saved = true;
3307
+ else {
3308
+ await this.execHooks("updating", options);
3309
+ if (this.usesTimestamps()) this.updateTimestamps();
3310
+ const dirty = this.getDirty();
3311
+ if (Object.keys(dirty).length > 0) {
3312
+ await query.where(this.getKeyName(), this.getKey()).query.update(dirty);
3313
+ this.syncChanges();
3314
+ await this.execHooks("updated", options);
3315
+ }
3316
+ saved = true;
3317
+ }
3318
+ else {
3319
+ if (this.usesUniqueIds()) this.setUniqueIds();
3320
+ await this.execHooks("creating", options);
3321
+ if (this.usesTimestamps()) this.updateTimestamps();
3322
+ const attributes = this.getAttributes();
3323
+ if (this.getIncrementing()) {
3324
+ var _data$;
3325
+ const keyName = this.getKeyName();
3326
+ const data = await query.insert([attributes], [keyName]);
3327
+ this.setAttribute(keyName, ((_data$ = data[0]) === null || _data$ === void 0 ? void 0 : _data$[keyName]) || data[0]);
3328
+ } else if (Object.keys(attributes).length > 0) await query.insert(attributes);
3329
+ this.exists = true;
3330
+ await this.execHooks("created", options);
3331
+ saved = true;
3332
+ }
3333
+ if (saved) {
3334
+ await this.execHooks("saved", options);
3335
+ this.syncOriginal();
3336
+ }
3337
+ return saved;
3338
+ }
3339
+ async update(attributes = {}, options = {}) {
3340
+ if (!this.exists) return false;
3341
+ for (const key in attributes) this[key] = attributes[key];
3342
+ return await this.save(options);
3343
+ }
3344
+ async delete(options = {}) {
3345
+ await this.execHooks("deleting", options);
3346
+ await this.performDeleteOnModel(options);
3347
+ await this.execHooks("deleted", options);
3348
+ return true;
3349
+ }
3350
+ async performDeleteOnModel(options = {}) {
3351
+ await this.setKeysForSaveQuery(this.newModelQuery(options.client)).delete();
3352
+ this.exists = false;
3353
+ }
3354
+ setKeysForSaveQuery(query) {
3355
+ query.where(this.getKeyName(), "=", this.getKey());
3356
+ return query;
3357
+ }
3358
+ async forceDelete(options = {}) {
3359
+ return await this.delete(options);
3360
+ }
3361
+ fresh() {
3362
+ if (!this.exists) return;
3363
+ return this.constructor.query().where(this.getKeyName(), this.getKey()).first();
3364
+ }
3365
+ async refresh() {
3366
+ if (!this.exists) return Promise.resolve(void 0);
3367
+ this.attributes = { ...(await this.constructor.query().where(this.getKeyName(), this.getKey()).first()).attributes };
3368
+ await this.load(collect(this.relations).reject((relation) => {
3369
+ return relation instanceof Pivot;
3370
+ }).keys().all());
3371
+ this.syncOriginal();
3372
+ return this;
3373
+ }
3374
+ newPivot(parent, attributes, table, exists, using = null) {
3375
+ return using ? using.fromRawAttributes(parent, attributes, table, exists) : Pivot.fromAttributes(parent, attributes, table, exists);
3376
+ }
3377
+ qualifyColumn(column) {
3378
+ if (column.includes(".")) return column;
3379
+ return `${this.getTable()}.${column}`;
3380
+ }
3381
+ getQualifiedKeyName() {
3382
+ return this.qualifyColumn(this.getKeyName());
3383
+ }
3384
+ async push(options = {}) {
3385
+ if (!await this.save(options)) return false;
3386
+ for (const relation in this.relations) {
3387
+ let models = this.relations[relation];
3388
+ models = models instanceof collection_default ? models.all() : [models];
3389
+ for (const model of models) if (!await model.push(options)) return false;
3390
+ }
3391
+ return true;
3392
+ }
3393
+ is(model) {
3394
+ return model && model instanceof Model && this.getKey() === model.getKey() && this.getTable() === model.getTable() && this.getConnectionName() === model.getConnectionName();
3395
+ }
3396
+ isNot(model) {
3397
+ return !this.is(model);
3398
+ }
3399
+ };
3400
+ var Pivot = class extends Model {
3401
+ incrementing = false;
3402
+ guarded = [];
3403
+ pivotParent = null;
3404
+ foreignKey = null;
3405
+ relatedKey = null;
3406
+ setPivotKeys(foreignKey, relatedKey) {
3407
+ this.foreignKey = foreignKey;
3408
+ this.relatedKey = relatedKey;
3409
+ return this;
3410
+ }
3411
+ static fromRawAttributes(parent, attributes, table, exists = false) {
3412
+ const instance = this.fromAttributes(parent, {}, table, exists);
3413
+ instance.timestamps = instance.hasTimestampAttributes(attributes);
3414
+ instance.attributes = attributes;
3415
+ instance.exists = exists;
3416
+ return instance;
3417
+ }
3418
+ static fromAttributes(parent, attributes, table, exists = false) {
3419
+ const instance = new this();
3420
+ instance.timestamps = instance.hasTimestampAttributes(attributes);
3421
+ instance.setConnection(parent.connection).setTable(table).fill(attributes).syncOriginal();
3422
+ instance.pivotParent = parent;
3423
+ instance.exists = exists;
3424
+ return instance;
3425
+ }
3426
+ hasTimestampAttributes(attributes = null) {
3427
+ return (attributes || this.attributes)[this.constructor.CREATED_AT] !== void 0;
3428
+ }
3429
+ };
3430
+ var model_default = Model;
3431
+
3432
+ //#endregion
3433
+ //#region src/query-builder.ts
3434
+ const Inference = class {};
3435
+ var QueryBuilder = class QueryBuilder extends Inference {
3436
+ model;
3437
+ schema;
3438
+ connector;
3439
+ constructor(config$1, connector) {
3440
+ super();
3441
+ this.connector = connector(config$1);
3442
+ return this.asProxy();
3443
+ }
3444
+ asProxy() {
3445
+ return new Proxy(this, {
3446
+ get: function(target, prop) {
3447
+ if (typeof target[prop] !== "undefined") return target[prop];
3448
+ if (["destroy", "schema"].includes(prop)) return target.connector.schema;
3449
+ if ([
3450
+ "select",
3451
+ "from",
3452
+ "where",
3453
+ "orWhere",
3454
+ "whereColumn",
3455
+ "whereRaw",
3456
+ "whereNot",
3457
+ "orWhereNot",
3458
+ "whereIn",
3459
+ "orWhereIn",
3460
+ "whereNotIn",
3461
+ "orWhereNotIn",
3462
+ "whereNull",
3463
+ "orWhereNull",
3464
+ "whereNotNull",
3465
+ "orWhereNotNull",
3466
+ "whereExists",
3467
+ "orWhereExists",
3468
+ "whereNotExists",
3469
+ "orWhereNotExists",
3470
+ "whereBetween",
3471
+ "orWhereBetween",
3472
+ "whereNotBetween",
3473
+ "orWhereNotBetween",
3474
+ "whereLike",
3475
+ "orWhereLike",
3476
+ "whereILike",
3477
+ "orWhereILike",
3478
+ "whereJsonObject",
3479
+ "whereJsonPath",
3480
+ "whereJsonSupersetOf",
3481
+ "whereJsonSubsetOf",
3482
+ "join",
3483
+ "joinRaw",
3484
+ "leftJoin",
3485
+ "leftOuterJoin",
3486
+ "rightJoin",
3487
+ "rightOuterJoin",
3488
+ "crossJoin",
3489
+ "transacting",
3490
+ "groupBy",
3491
+ "groupByRaw",
3492
+ "returning",
3493
+ "having",
3494
+ "havingRaw",
3495
+ "havingBetween",
3496
+ "limit",
3497
+ "offset",
3498
+ "orderBy",
3499
+ "orderByRaw",
3500
+ "union",
3501
+ "insert",
3502
+ "forUpdate",
3503
+ "forShare",
3504
+ "distinct",
3505
+ "clearOrder",
3506
+ "clear",
3507
+ "clearSelect",
3508
+ "clearWhere",
3509
+ "clearHaving",
3510
+ "clearGroup"
3511
+ ].includes(prop)) return (...args) => {
3512
+ target.connector[prop](...args);
3513
+ return target.asProxy();
3514
+ };
3515
+ return target.connector[prop];
3516
+ },
3517
+ set: function(target, prop, value) {
3518
+ if (typeof target[prop] !== "undefined") {
3519
+ target[prop] = value;
3520
+ return target;
3521
+ }
3522
+ target.connector[prop] = value;
3523
+ return target;
3524
+ }
3525
+ });
3526
+ }
3527
+ async beginTransaction() {
3528
+ return await this.connector.transaction();
3529
+ }
3530
+ table(table) {
3531
+ const c = this.connector.table(table);
3532
+ return new QueryBuilder(null, () => c);
3533
+ }
3534
+ transaction(callback) {
3535
+ if (callback) return this.connector.transaction((trx) => {
3536
+ return callback(new QueryBuilder(null, () => trx));
3537
+ });
3538
+ return callback;
3539
+ }
3540
+ async find(id, columns = ["*"]) {
3541
+ return await this.connector.where("id", id).first(...columns);
3542
+ }
3543
+ async get(_columns = ["*"]) {
3544
+ return await this.connector;
3545
+ }
3546
+ async exists() {
3547
+ return await this.connector.first() !== null;
3548
+ }
3549
+ skip(...args) {
3550
+ return this.offset(...args);
3551
+ }
3552
+ take(...args) {
3553
+ return this.limit(...args);
3554
+ }
3555
+ async chunk(count, callback) {
3556
+ if (this.connector._statements.filter((item) => item.grouping === "order").length === 0) throw new Error("You must specify an orderBy clause when using this function.");
3557
+ let page = 1;
3558
+ let countResults;
3559
+ do {
3560
+ const results = await this.clone().forPage(page, count).get();
3561
+ countResults = results.length;
3562
+ if (countResults == 0) break;
3563
+ if (await callback(results, page) === false) return false;
3564
+ page++;
3565
+ } while (countResults === count);
3566
+ return true;
3567
+ }
3568
+ async paginate(page = 1, perPage = 15) {
3569
+ const total = await this.clone().clearOrder().count("*");
3570
+ let results;
3571
+ if (total > 0) {
3572
+ const skip = (page - 1) * perPage;
3573
+ this.take(perPage).skip(skip);
3574
+ results = await this.get();
3575
+ } else results = [];
3576
+ return new paginator_default(results, parseInt(total), perPage, page);
3577
+ }
3578
+ forPage(page = 1, perPage = 15) {
3579
+ return this.offset((page - 1) * perPage).limit(perPage);
3580
+ }
3581
+ toSQL(...args) {
3582
+ return this.connector.toSQL(...args);
3583
+ }
3584
+ async count(column) {
3585
+ const [{ aggregate }] = await this.connector.count(column, { as: "aggregate" });
3586
+ return Number(aggregate);
3587
+ }
3588
+ async min(column) {
3589
+ const [{ aggregate }] = await this.connector.min(column, { as: "aggregate" });
3590
+ return Number(aggregate);
3591
+ }
3592
+ async max(column) {
3593
+ const [{ aggregate }] = await this.connector.max(column, { as: "aggregate" });
3594
+ return Number(aggregate);
3595
+ }
3596
+ async sum(column) {
3597
+ const [{ aggregate }] = await this.connector.sum(column, { as: "aggregate" });
3598
+ return Number(aggregate);
3599
+ }
3600
+ async avg(column) {
3601
+ const [{ aggregate }] = await this.connector.avg(column, { as: "aggregate" });
3602
+ return Number(aggregate);
3603
+ }
3604
+ clone() {
3605
+ const c = this.connector.clone();
3606
+ return new QueryBuilder(null, () => c);
3607
+ }
3608
+ async delete() {
3609
+ return await this.connector.delete();
3610
+ }
3611
+ async insert(...args) {
3612
+ return await this.connector.insert(...args);
3613
+ }
3614
+ async update(...args) {
3615
+ return await this.connector.update(...args);
3616
+ }
3617
+ destroy(...args) {
3618
+ return this.connector.destroy(...args);
3619
+ }
3620
+ get _statements() {
3621
+ return this.connector._statements;
3622
+ }
3623
+ get _single() {
3624
+ return this.connector._single;
3625
+ }
3626
+ get from() {
3627
+ return this.connector.from;
3628
+ }
3629
+ };
3630
+ var query_builder_default = QueryBuilder;
3631
+
3632
+ //#endregion
3633
+ //#region src/arquebus.ts
3634
+ var arquebus = class arquebus {
3635
+ static connectorFactory = null;
3636
+ static instance = null;
3637
+ manager;
3638
+ connections;
3639
+ models;
3640
+ constructor() {
3641
+ this.manager = {};
3642
+ this.connections = {};
3643
+ this.models = {};
3644
+ }
3645
+ getConstructor() {
3646
+ return this.constructor;
3647
+ }
3648
+ static getInstance() {
3649
+ if (this.instance === null) this.instance = new arquebus();
3650
+ return this.instance;
3651
+ }
3652
+ /**
3653
+ * Initialize a new database connection
3654
+ *
3655
+ * @returns
3656
+ */
3657
+ static fire(connection = null) {
3658
+ return this.getInstance().getConnection(connection);
3659
+ }
3660
+ /**
3661
+ * Initialize a new database connection
3662
+ *
3663
+ * This is an alias of `arquebus.fire()` and will be removed in the future
3664
+ *
3665
+ * @deprecated since version 0.3.0
3666
+ * @alias fire
3667
+ *
3668
+ * @returns
3669
+ */
3670
+ static connection(connection = null) {
3671
+ return this.fire(connection);
3672
+ }
3673
+ static setConnectorFactory(connectorFactory) {
3674
+ this.connectorFactory = connectorFactory;
3675
+ }
3676
+ static getConnectorFactory() {
3677
+ return this.connectorFactory ?? Knex;
3678
+ }
3679
+ static addConnection(config$1, name$1 = "default") {
3680
+ return this.getInstance().addConnection(config$1, name$1);
3681
+ }
3682
+ static beginTransaction(connection = null) {
3683
+ return this.getInstance().beginTransaction(connection);
3684
+ }
3685
+ static transaction(callback, connection = null) {
3686
+ return this.getInstance().transaction(callback, connection);
3687
+ }
3688
+ static table(name$1, connection = null) {
3689
+ return this.getInstance().table(name$1, connection);
3690
+ }
3691
+ static schema(connection = null) {
3692
+ return this.getInstance().schema(connection);
3693
+ }
3694
+ static async destroyAll() {
3695
+ await this.getInstance().destroyAll();
3696
+ }
3697
+ static createModel(name$1, options) {
3698
+ return this.getInstance().createModel(name$1, options);
3699
+ }
3700
+ connection(connection = null) {
3701
+ return this.getConnection(connection);
3702
+ }
3703
+ getConnection(name$1 = null) {
3704
+ name$1 = name$1 || "default";
3705
+ if (this.manager[name$1] === void 0) {
3706
+ const queryBuilder = new query_builder_default(this.connections[name$1], arquebus.getConnectorFactory());
3707
+ this.manager[name$1] = queryBuilder;
3708
+ }
3709
+ return this.manager[name$1];
3710
+ }
3711
+ addConnection(config$1, name$1 = "default") {
3712
+ this.connections[name$1] = {
3713
+ ...config$1,
3714
+ connection: {
3715
+ ...config$1.connection,
3716
+ dateStrings: true,
3717
+ typeCast: function(field, next) {
3718
+ if (field.type === "JSON") return field.string("utf8");
3719
+ return next();
3720
+ }
3721
+ }
3722
+ };
3723
+ }
3724
+ /**
3725
+ * Autoload the config file
3726
+ *
3727
+ * @param addConnection
3728
+ * @default true
3729
+ * If set to `false` we will no attempt add the connection, we
3730
+ * will just go ahead and return the config
3731
+ *
3732
+ * @returns
3733
+ */
3734
+ static async autoLoad(addConnection = true) {
3735
+ let config$1;
3736
+ const jsPath = path.resolve("arquebus.config.js");
3737
+ const tsPath = path.resolve("arquebus.config.ts");
3738
+ const instance = this.getInstance();
3739
+ if (existsSync(jsPath)) {
3740
+ config$1 = (await import(jsPath)).default;
3741
+ if (addConnection) instance.addConnection(config$1, config$1.client);
3742
+ return config$1;
3743
+ }
3744
+ if (existsSync(tsPath)) if (process.env.NODE_ENV !== "production") {
3745
+ config$1 = (await import(tsPath)).default;
3746
+ if (addConnection) instance.addConnection(config$1, config$1.client);
3747
+ return config$1;
3748
+ } else throw new Error("arquebus.config.ts found in production without build step");
3749
+ return {};
3750
+ }
3751
+ beginTransaction(connection = null) {
3752
+ return this.connection(connection).beginTransaction();
3753
+ }
3754
+ transaction(callback, connection = null) {
3755
+ return this.connection(connection).transaction(callback);
3756
+ }
3757
+ table(name$1, connection = null) {
3758
+ return this.connection(connection).table(name$1);
3759
+ }
3760
+ schema(connection = null) {
3761
+ return this.connection(connection).schema;
3762
+ }
3763
+ async destroyAll() {
3764
+ await Promise.all(Object.values(this.manager).map((connection) => {
3765
+ return connection === null || connection === void 0 ? void 0 : connection.destroy();
3766
+ }));
3767
+ }
3768
+ createModel(name$1, options = {}) {
3769
+ let BaseModel$1 = Model;
3770
+ if ("plugins" in options) BaseModel$1 = compose(BaseModel$1, ...options.plugins ?? []);
3771
+ this.models = {
3772
+ ...this.models,
3773
+ [name$1]: class extends BaseModel$1 {
3774
+ table = (options === null || options === void 0 ? void 0 : options.table) ?? null;
3775
+ connection = (options === null || options === void 0 ? void 0 : options.connection) ?? null;
3776
+ timestamps = (options === null || options === void 0 ? void 0 : options.timestamps) ?? true;
3777
+ primaryKey = (options === null || options === void 0 ? void 0 : options.primaryKey) ?? "id";
3778
+ keyType = (options === null || options === void 0 ? void 0 : options.keyType) ?? "int";
3779
+ incrementing = (options === null || options === void 0 ? void 0 : options.incrementing) ?? true;
3780
+ with = (options === null || options === void 0 ? void 0 : options.with) ?? [];
3781
+ casts = (options === null || options === void 0 ? void 0 : options.casts) ?? {};
3782
+ static CREATED_AT = (options === null || options === void 0 ? void 0 : options.CREATED_AT) ?? "created_at";
3783
+ static UPDATED_AT = (options === null || options === void 0 ? void 0 : options.UPDATED_AT) ?? "updated_at";
3784
+ static DELETED_AT = (options === null || options === void 0 ? void 0 : options.DELETED_AT) ?? "deleted_at";
3785
+ }
3786
+ };
3787
+ if ("attributes" in options) for (const attribute in options.attributes) {
3788
+ if (options.attributes[attribute] instanceof attribute_default === false) throw new Error("Attribute must be an instance of \"Attribute\"");
3789
+ this.models[name$1].prototype[getAttrMethod(attribute)] = () => {
3790
+ var _options$attributes;
3791
+ return (_options$attributes = options.attributes) === null || _options$attributes === void 0 ? void 0 : _options$attributes[attribute];
3792
+ };
3793
+ }
3794
+ if ("relations" in options) for (const relation in options.relations) this.models[name$1].prototype[getRelationMethod(relation)] = function() {
3795
+ var _options$relations;
3796
+ return (_options$relations = options.relations) === null || _options$relations === void 0 ? void 0 : _options$relations[relation](this);
3797
+ };
3798
+ if ("scopes" in options) for (const scope in options.scopes) this.models[name$1].prototype[getScopeMethod(scope)] = options.scopes[scope];
3799
+ this.models[name$1].setConnectionResolver(this);
3800
+ return this.models[name$1];
3801
+ }
3802
+ };
3803
+ var arquebus_default = arquebus;
3804
+
3805
+ //#endregion
3806
+ //#region src/migrate.ts
3807
+ var Migrate = class {
3808
+ callback;
3809
+ constructor(basePath, customStubPath, callback) {
3810
+ this.basePath = basePath;
3811
+ this.customStubPath = customStubPath;
3812
+ this.callback = callback ?? ((_ = "") => {});
3813
+ }
3814
+ /**
3815
+ * Runs all pending migrations
3816
+ *
3817
+ * @param config
3818
+ * @param options
3819
+ * @param destroyAll
3820
+ */
3821
+ async run(config$1, options = {}, destroyAll = false) {
3822
+ const { arquebus: arquebus$1, migrator } = await this.setupConnection(config$1);
3823
+ await this.prepareDatabase(migrator);
3824
+ const paths = await Utils.getMigrationPaths(this.basePath ?? process.cwd(), migrator, config$1.migrations.path, options.path);
3825
+ await migrator.setOutput(true).run(paths, {
3826
+ step: options.step,
3827
+ pretend: options.pretend
3828
+ });
3829
+ if (destroyAll) await arquebus$1.destroyAll();
3830
+ }
3831
+ /**
3832
+ * Rollback the last migration
3833
+ *
3834
+ * @param config
3835
+ * @param options
3836
+ * @param destroyAll
3837
+ */
3838
+ async rollback(config$1, options = {}, destroyAll = false) {
3839
+ const { arquebus: arquebus$1, migrator } = await this.setupConnection(config$1);
3840
+ const paths = await Utils.getMigrationPaths(this.basePath ?? process.cwd(), migrator, config$1.migrations.path, options.path);
3841
+ await migrator.setOutput(true).rollback(paths, {
3842
+ step: options.step || 0,
3843
+ pretend: options.pretend,
3844
+ batch: options.batch || 0
3845
+ });
3846
+ if (destroyAll) await arquebus$1.destroyAll();
3847
+ }
3848
+ /**
3849
+ * Prepares the database for migration
3850
+ *
3851
+ * @param migrator
3852
+ */
3853
+ async prepareDatabase(migrator) {
3854
+ if (!await migrator.repositoryExists()) {
3855
+ this.callback("INFO: Preparing database.", "info");
3856
+ this.callback("INFO: Creating migration table...", "info");
3857
+ await migrator.repository.createRepository();
3858
+ this.callback("SUCCESS: Migration table created successfully.", "success");
3859
+ }
3860
+ }
3861
+ /**
3862
+ * Check the status of available migrations
3863
+ *
3864
+ * @param config
3865
+ * @param options
3866
+ * @param destroyAll
3867
+ * @returns
3868
+ */
3869
+ async status(config$1, options = {}, destroyAll = false) {
3870
+ const { arquebus: arquebus$1, migrator } = await this.setupConnection(config$1);
3871
+ const getAllMigrationFiles = async () => {
3872
+ return await migrator.getMigrationFiles(await Utils.getMigrationPaths(this.basePath ?? process.cwd(), migrator, config$1.migrations.path, options.path));
3873
+ };
3874
+ async function getStatusFor(ran$1, batches$1) {
3875
+ const files$1 = await getAllMigrationFiles();
3876
+ return Object.values(files$1).map((migration) => {
3877
+ const migrationName = migrator.getMigrationName(migration);
3878
+ return {
3879
+ name: migrationName,
3880
+ ran: ran$1.includes(migrationName),
3881
+ batch: ran$1.includes(migrationName) ? batches$1[migrationName] : null
3882
+ };
3883
+ });
3884
+ }
3885
+ if (!await migrator.repositoryExists()) this.callback("ERROR: Migration table does not exist.", "error");
3886
+ const ran = await migrator.repository.getRan();
3887
+ const batches = await migrator.getRepository().getMigrationBatches();
3888
+ const migrations = await getStatusFor(ran, batches);
3889
+ if (destroyAll) await arquebus$1.destroyAll();
3890
+ return migrations;
3891
+ }
3892
+ /**
3893
+ * Setup the database connection
3894
+ *
3895
+ * @param config
3896
+ * @returns
3897
+ */
3898
+ async setupConnection(config$1) {
3899
+ var _config$migrations;
3900
+ const table = (config$1 === null || config$1 === void 0 || (_config$migrations = config$1.migrations) === null || _config$migrations === void 0 ? void 0 : _config$migrations.table) || "migrations";
3901
+ if (config$1.skipConnection !== true) {
3902
+ arquebus_default.addConnection(config$1, "default");
3903
+ Object.entries(config$1.connections || {}).forEach(([name$1, connection]) => {
3904
+ arquebus_default.addConnection(connection, name$1);
3905
+ });
3906
+ }
3907
+ const repository$1 = new migration_repository_default(arquebus_default, table);
3908
+ const migrator = new migrator_default(repository$1, arquebus_default);
3909
+ return {
3910
+ arquebus: arquebus_default,
3911
+ migrator
3912
+ };
3913
+ }
3914
+ };
3915
+
3916
+ //#endregion
3917
+ //#region src/migrations/migration-creator.ts
3918
+ var MigrationCreator = class {
3919
+ postCreate = [];
3920
+ constructor(customStubPath, type$1 = "js") {
3921
+ this.customStubPath = customStubPath;
3922
+ this.type = type$1;
3923
+ }
3924
+ /**
3925
+ * Create a new migration file
3926
+ *
3927
+ * @param name
3928
+ * @param dir
3929
+ * @param table
3930
+ * @param create
3931
+ * @returns
3932
+ */
3933
+ async create(name$1, dir, table, create = false) {
3934
+ const stub = this.getStub(table, create);
3935
+ const filePath = this.getPath(name$1, dir);
3936
+ await this.ensureDirectoryExists(path.dirname(filePath));
3937
+ await fs.writeFile(filePath, this.populateStub(stub, table));
3938
+ await this.firePostCreateHooks(table, filePath);
3939
+ return filePath;
3940
+ }
3941
+ /**
3942
+ * Publish migrations from third party vendors
3943
+ *
3944
+ * @param dir
3945
+ * @param callback
3946
+ */
3947
+ async publish(dir, callback) {
3948
+ const migrationFiles = await fs.readdir(this.customStubPath ?? "");
3949
+ await this.ensureDirectoryExists(dir);
3950
+ for (const migrationFile of migrationFiles) {
3951
+ const sourceFilePath = path.join(this.customStubPath ?? "", migrationFile);
3952
+ const destinationFilePath = path.join(dir, migrationFile);
3953
+ await fs.copyFile(sourceFilePath, destinationFilePath);
3954
+ if (callback) callback(migrationFile, sourceFilePath, destinationFilePath);
3955
+ }
3956
+ }
3957
+ getStub(table, create = false) {
3958
+ let stub;
3959
+ if (!table) {
3960
+ const customPath = path.join(this.customStubPath ?? "", `migration-${this.type}.stub`);
3961
+ console.log("\n", customPath, "---");
3962
+ stub = existsSync$1(customPath) ? customPath : this.stubPath(`/migration-${this.type}.stub`);
3963
+ } else if (create) {
3964
+ const customPath = path.join(this.customStubPath ?? "", `migration.create-${this.type}.stub`);
3965
+ stub = existsSync$1(customPath) ? customPath : this.stubPath(`/migration.create-${this.type}.stub`);
3966
+ } else {
3967
+ const customPath = path.join(this.customStubPath ?? "", `migration.update-${this.type}.stub`);
3968
+ stub = existsSync$1(customPath) ? customPath : this.stubPath(`/migration.update-${this.type}.stub`);
3969
+ }
3970
+ return readFileSync(stub, "utf-8");
3971
+ }
3972
+ populateStub(stub, table) {
3973
+ if (table !== null) stub = stub.replace(/DummyTable|{{\s*table\s*}}/g, table);
3974
+ return stub;
3975
+ }
3976
+ getClassName(name$1) {
3977
+ return name$1.replace(/_+([a-z])/g, (match, char) => char.toUpperCase());
3978
+ }
3979
+ getPath(name$1, dir) {
3980
+ const datePrefix = dayjs().format("YYYY_MM_DD_HHmmss");
3981
+ return path.join(dir, `${datePrefix}_${name$1}.${this.type}`);
3982
+ }
3983
+ async firePostCreateHooks(table, filePath) {
3984
+ for (const callback of this.postCreate) await callback(table, filePath);
3985
+ }
3986
+ afterCreate(callback) {
3987
+ this.postCreate.push(callback);
3988
+ }
3989
+ async ensureDirectoryExists(dir) {
3990
+ await fs.mkdir(dir, { recursive: true });
3991
+ }
3992
+ stubPath(stub = "") {
3993
+ const __dirname$1 = this.getDirname(import.meta);
3994
+ return path.join(__dirname$1, "stubs", stub);
3995
+ }
3996
+ getDirname(meta) {
3997
+ if (typeof __dirname !== "undefined") return __dirname;
3998
+ if (meta && meta.url) return dirname(fileURLToPath(meta.url));
3999
+ throw new Error("Unable to determine dirname");
4000
+ }
4001
+ };
4002
+ var migration_creator_default = MigrationCreator;
4003
+
4004
+ //#endregion
4005
+ //#region package.json
4006
+ var name = "@h3ravel/arquebus";
4007
+ var version = "0.3.1";
4008
+ var packageManager = "pnpm@10.14.0";
4009
+ var description = "Arquebus ORM is a Beautiful, expressive ORM inspired by Laravel's Eloquent, designed for TypeScript applications and for the H3ravel Framework.";
4010
+ var homepage = "https://h3ravel.toneflix.net/arquebus";
4011
+ var bin = { "arquebus": "./bin/index.js" };
4012
+ var publishConfig = { "access": "public" };
4013
+ var main = "./dist/index.cjs";
4014
+ var module = "./dist/index.js";
4015
+ var type = "module";
4016
+ var types = "./dist/index.d.ts";
4017
+ var files = [
4018
+ "dist",
4019
+ "bin",
4020
+ "src/stubs",
4021
+ "src/migrations/stubs",
4022
+ "types"
4023
+ ];
4024
+ var exports = {
4025
+ ".": {
4026
+ "cli": {
4027
+ "import": {
4028
+ "types": "./bin/index.d.ts",
4029
+ "default": "./bin/index.js"
4030
+ },
4031
+ "require": {
4032
+ "types": "./bin/index.d.cts",
4033
+ "default": "./bin/index.cjs"
4034
+ }
4035
+ },
4036
+ "worker": {
4037
+ "import": {
4038
+ "types": "./dist/index.d.ts",
4039
+ "default": "./dist/index.js"
4040
+ },
4041
+ "require": {
4042
+ "types": "./dist/index.d.cts",
4043
+ "default": "./dist/index.cjs"
4044
+ }
4045
+ },
4046
+ "node": {
4047
+ "import": {
4048
+ "types": "./dist/index.d.ts",
4049
+ "default": "./dist/index.js"
4050
+ },
4051
+ "require": {
4052
+ "types": "./dist/index.d.cts",
4053
+ "default": "./dist/index.cjs"
4054
+ }
4055
+ },
4056
+ "browser": {
4057
+ "import": {
4058
+ "types": "./dist/browser/index.d.ts",
4059
+ "default": "./dist/browser/index.js"
4060
+ },
4061
+ "require": {
4062
+ "types": "./dist/browser/index.d.cts",
4063
+ "default": "./dist/browser/index.cjs"
4064
+ }
4065
+ },
4066
+ "default": {
4067
+ "import": {
4068
+ "types": "./dist/index.d.ts",
4069
+ "default": "./dist/index.js"
4070
+ },
4071
+ "require": {
4072
+ "types": "./dist/index.d.cts",
4073
+ "default": "./dist/index.cjs"
4074
+ }
4075
+ }
4076
+ },
4077
+ "./migrations": {
4078
+ "import": {
4079
+ "types": "./dist/migrations/index.d.ts",
4080
+ "default": "./dist/migrations/index.js"
4081
+ },
4082
+ "require": {
4083
+ "types": "./dist/migrations/index.d.cts",
4084
+ "default": "./dist/migrations/index.cjs"
4085
+ }
4086
+ },
4087
+ "./browser": {
4088
+ "import": {
4089
+ "types": "./dist/browser/index.d.ts",
4090
+ "default": "./dist/browser/index.js"
4091
+ },
4092
+ "require": {
4093
+ "types": "./dist/browser/index.d.cts",
4094
+ "default": "./dist/browser/index.cjs"
4095
+ }
4096
+ },
4097
+ "./package.json": "./package.json"
4098
+ };
4099
+ var repository = {
4100
+ "type": "git",
4101
+ "url": "https://github.com/h3ravel/arquebus.git"
4102
+ };
4103
+ var engines = {
4104
+ "node": ">=14",
4105
+ "pnpm": ">=4"
4106
+ };
4107
+ var scripts = {
4108
+ "build": "tsdown",
4109
+ "lint": "eslint . --ext .ts",
4110
+ "cmd": "cross-env TEST=true tsx --experimental-specifier-resolution=node src/cli",
4111
+ "cmd:watch": "cross-env TEST=true tsx watch --experimental-specifier-resolution=node src/cli",
4112
+ "test:mysql": "cross-env DB=mysql vitest --project node",
4113
+ "test:postgres": "cross-env DB=postgres vitest --project node",
4114
+ "test:sqlite": "cross-env DB=sqlite vitest --project node",
4115
+ "test:browser": "vitest --project browser",
4116
+ "release:patch": "pnpm build && git add . && git commit -m \"version: bump version and publish\" && pnpm version patch && pnpm publish --tag latest"
4117
+ };
4118
+ var husky = { "hooks": { "pre-commit": "lint-staged" } };
4119
+ var lint_staged = { "*.{js,json}": ["prettier --write", "git add"] };
4120
+ var dependencies = {
4121
+ "chalk": "^5.6.0",
4122
+ "collect.js": "^4.36.1",
4123
+ "commander": "^14.0.0",
4124
+ "cross-env": "^10.0.0",
4125
+ "dayjs": "^1.11.13",
4126
+ "dotenv": "^17.2.1",
4127
+ "escalade": "^3.2.0",
4128
+ "husky": "^9.1.7",
4129
+ "knex": "^3.1.0",
4130
+ "lint-staged": "^16.1.5",
4131
+ "mysql2": "^3.14.3",
4132
+ "pg": "^8.16.3",
4133
+ "pluralize": "^8.0.0",
4134
+ "prettier": "^3.6.2",
4135
+ "radashi": "^12.6.2",
4136
+ "resolve-from": "^5.0.0",
4137
+ "tedious": "^19.0.0"
4138
+ };
4139
+ var devDependencies = {
4140
+ "@eslint/js": "^9.33.0",
4141
+ "@types/node": "^24.3.0",
4142
+ "@types/pluralize": "^0.0.33",
4143
+ "@typescript-eslint/eslint-plugin": "^8.40.0",
4144
+ "@typescript-eslint/parser": "^8.40.0",
4145
+ "@vitest/coverage-v8": "^3.2.4",
4146
+ "eslint": "^9.33.0",
4147
+ "jsdom": "^26.1.0",
4148
+ "sqlite3": "5.1.7",
4149
+ "terser": "^5.43.1",
4150
+ "ts-node": "^10.9.2",
4151
+ "tsdown": "^0.15.4",
4152
+ "tsx": "^4.20.4",
4153
+ "typescript": "^5.9.2",
4154
+ "typescript-eslint": "^8.40.0",
4155
+ "vite-tsconfig-paths": "^5.1.4",
4156
+ "vitest": "^3.2.4"
4157
+ };
4158
+ var keywords = [
4159
+ "arquebus",
4160
+ "ORM",
4161
+ "mysql",
4162
+ "mariadb",
4163
+ "sqlite",
4164
+ "postgresql",
4165
+ "postgres",
4166
+ "pg",
4167
+ "mssql",
4168
+ "active record"
4169
+ ];
4170
+ var pnpm = { "onlyBuiltDependencies": ["sqlite3"] };
4171
+ var readmeFilename = "README.md";
4172
+ var license = "MIT";
4173
+ var package_default = {
4174
+ name,
4175
+ version,
4176
+ packageManager,
4177
+ description,
4178
+ homepage,
4179
+ bin,
4180
+ publishConfig,
4181
+ main,
4182
+ module,
4183
+ type,
4184
+ types,
4185
+ files,
4186
+ exports,
4187
+ repository,
4188
+ engines,
4189
+ scripts,
4190
+ husky,
4191
+ "lint-staged": lint_staged,
4192
+ dependencies,
4193
+ devDependencies,
4194
+ keywords,
4195
+ pnpm,
4196
+ readmeFilename,
4197
+ license
4198
+ };
4199
+
4200
+ //#endregion
4201
+ //#region src/cli/cli.ts
4202
+ var Cli = class Cli {
4203
+ cwd;
4204
+ output = Utils.output();
4205
+ config = {};
4206
+ basePath = "";
4207
+ modulePath;
4208
+ configPath;
4209
+ modulePackage;
4210
+ constructor(basePath) {
4211
+ this.basePath = basePath ?? (process.env.TEST === "true" ? "test/cli" : "");
4212
+ }
4213
+ terminateNotFound() {
4214
+ this.output.error(`ERROR: Arquebus config not found. Run ${chalk.italic.black.bgGray("arquebus init")} first.`);
4215
+ }
4216
+ static init() {
4217
+ config({ quiet: true });
4218
+ const instance = new Cli();
4219
+ Promise.all([instance.loadPaths(), instance.loadConfig()]).then(([_, e]) => e.run());
4220
+ }
4221
+ async loadPaths() {
4222
+ this.cwd = path.join(process.cwd(), this.basePath);
4223
+ this.configPath = Utils.findUpConfig(this.cwd, "arquebus.config", [
4224
+ "js",
4225
+ "ts",
4226
+ "cjs"
4227
+ ]) ?? void 0;
4228
+ this.modulePath = Utils.findModulePkg("@h3ravel/arquebus", this.cwd) ?? "";
4229
+ try {
4230
+ this.modulePackage = await import(path.join(this.modulePath, "package.json"));
4231
+ } catch {
4232
+ this.modulePackage = { version: "N/A" };
4233
+ }
4234
+ return this;
4235
+ }
4236
+ async loadConfig() {
4237
+ try {
4238
+ var _this$config$migratio;
4239
+ this.config = (await import(this.configPath ?? "----")).default;
4240
+ if ((_this$config$migratio = this.config.migrations) === null || _this$config$migratio === void 0 ? void 0 : _this$config$migratio.path) {
4241
+ var _this$config$migratio2;
4242
+ await mkdir(path.join(this.cwd, (_this$config$migratio2 = this.config.migrations) === null || _this$config$migratio2 === void 0 ? void 0 : _this$config$migratio2.path), { recursive: true });
4243
+ }
4244
+ } catch {
4245
+ this.config = {};
4246
+ }
4247
+ return this;
4248
+ }
4249
+ async run() {
4250
+ const cliVersion = ["Arquebus CLI version:", chalk.green(package_default.version)].join(" ");
4251
+ const localVersion = ["Arquebus Local version:", chalk.green(this.modulePackage.version || "None")].join(" ");
4252
+ program.name("arquebus").version(`${cliVersion}\n${localVersion}`);
4253
+ program.command("init").description("Create a fresh Arquebus config.").addArgument(new Argument("[type]", "Type of config to generate.").choices(["js", "ts"]).default("js", "generates a js config")).action(async (type$1) => {
4254
+ if (!this.modulePath) this.output.error(["ERROR: No local arquebus install found", " Try running: npm install arquebus --save"]);
4255
+ if (this.configPath) this.output.error(`ERROR: ${this.configPath} already exists`);
4256
+ try {
4257
+ const stubPath = `./arquebus.config.${type$1}`;
4258
+ const code = await readFile(path.join(this.modulePath, `/src/stubs/arquebus.config-${type$1}.stub`), { encoding: "utf8" });
4259
+ await writeFile(path.join(this.cwd, stubPath), code);
4260
+ this.output.success(`Initialized: Arquebus has been initialized as ${stubPath}`);
4261
+ } catch (e) {
4262
+ this.output.error("ERROR: " + e);
4263
+ }
4264
+ });
4265
+ program.command("migrate:make <name>").description("Create a new migration file.").addOption(new Option("-l, --type [string]", "Type of migration file to generate.").choices(["js", "ts"]).default("js", "generates a js migration file")).option("-t, --table [string]", "The table to migrate").option("-c, --create [string]", "The table to be created").option("-p, --path [path]", "The path to the migrations directory.").action(async (name$1, opts) => {
4266
+ if (!this.configPath) this.terminateNotFound();
4267
+ try {
4268
+ var _this$config$migratio3;
4269
+ name$1 = snake(name$1);
4270
+ const migrationPath = path.join(this.cwd, opts.path ?? ((_this$config$migratio3 = this.config.migrations) === null || _this$config$migratio3 === void 0 ? void 0 : _this$config$migratio3.path) ?? "./migrations");
4271
+ let table = opts.table;
4272
+ let create = opts.create || false;
4273
+ if (!table && typeof create === "string") {
4274
+ table = create;
4275
+ create = true;
4276
+ }
4277
+ if (!table) {
4278
+ const guessed = TableGuesser.guess(name$1);
4279
+ table = guessed[0];
4280
+ create = !!guessed[1];
4281
+ }
4282
+ this.output.info("INFO: Creating Migration");
4283
+ const fileName = await new migration_creator_default(void 0, opts.type).create(name$1, migrationPath, table, create);
4284
+ this.output.success(`INFO: Migration Created \n ${chalk.gray(path.basename(fileName))}`, true);
4285
+ } catch (e) {
4286
+ this.output.error("ERROR: " + e);
4287
+ }
4288
+ });
4289
+ /**
4290
+ * Publish migrations from third party vendors
4291
+ */
4292
+ program.command("migrate:publish <package>").description("Publish any migration files from packages.").option("-p, --path [path]", "The path to the migrations directory.").action(async (pkg, opts) => {
4293
+ if (!this.configPath) this.terminateNotFound();
4294
+ try {
4295
+ var _this$config$migratio4;
4296
+ const packagePath = Utils.findModulePkg(pkg) ?? "";
4297
+ const basePath = path.join(this.cwd, opts.path ?? ((_this$config$migratio4 = this.config.migrations) === null || _this$config$migratio4 === void 0 ? void 0 : _this$config$migratio4.path) ?? "./migrations");
4298
+ const pkgJson = await import(path.join(packagePath, "package.json"));
4299
+ if (!packagePath) this.output.error(`ERROR: package ${pkg} not found`);
4300
+ const creator = new migration_creator_default(path.join(packagePath, pkgJson.migrations ?? "migrations"));
4301
+ this.output.info(`INFO: Publishing migrations from ${chalk.italic.gray(pkgJson.name + "@" + pkgJson.version)}`);
4302
+ await creator.publish(basePath, (fileName) => {
4303
+ Utils.twoColumnDetail(fileName, chalk.green("PUBLISHED"));
4304
+ });
4305
+ } catch (e) {
4306
+ this.output.error("ERROR: " + e);
4307
+ }
4308
+ });
4309
+ /**
4310
+ * Run all pending migrations
4311
+ */
4312
+ program.command("migrate").description("Run all pending migrations.").option("-s, --step [number]", "Force the migrations to be run so they can be rolled back individually.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
4313
+ if (!this.configPath) this.terminateNotFound();
4314
+ const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
4315
+ try {
4316
+ await new Migrate(basePath).run(this.config, opts, true);
4317
+ } catch (e) {
4318
+ this.output.error("ERROR: " + e);
4319
+ }
4320
+ });
4321
+ /**
4322
+ * Rollaback the last migration
4323
+ */
4324
+ program.command("migrate:rollback").description("Rollback the last database migration.").option("-s, --step [number]", "The number of migrations to be reverted.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
4325
+ if (!this.configPath) this.terminateNotFound();
4326
+ const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
4327
+ try {
4328
+ await new Migrate(basePath, void 0, (msg, sts) => {
4329
+ if (sts) this.output[sts](msg);
4330
+ }).rollback(this.config, opts, true);
4331
+ } catch (e) {
4332
+ this.output.error("ERROR: " + e);
4333
+ }
4334
+ });
4335
+ /**
4336
+ * Check the migration status
4337
+ */
4338
+ program.command("migrate:status").description("Show the status of each migration.").option("-p, --path [path]", "The path to the migrations directory.").action(async (opts) => {
4339
+ if (!this.configPath) this.terminateNotFound();
4340
+ const basePath = opts.path ? path.join(this.cwd, opts.path) : this.cwd;
4341
+ try {
4342
+ const migrations = await new Migrate(basePath, void 0, (msg, sts) => {
4343
+ if (sts) this.output[sts](msg);
4344
+ }).status(this.config, opts, true);
4345
+ if (migrations.length > 0) {
4346
+ Utils.twoColumnDetail(chalk.gray("Migration name"), chalk.gray("Batch / Status"));
4347
+ migrations.forEach((migration) => {
4348
+ const status = migration.ran ? `[${migration.batch}] ${chalk.green("Ran")}` : chalk.yellow("Pending");
4349
+ Utils.twoColumnDetail(migration.name, status);
4350
+ });
4351
+ } else console.log("No migrations found");
4352
+ } catch (e) {
4353
+ this.output.error("ERROR: " + e);
4354
+ }
4355
+ });
4356
+ /**
4357
+ * Create a new model file
4358
+ */
4359
+ program.command("model:make <name>").description("Create a new Model file.").addOption(new Option("-l, --type [string]", "Type of migration file to generate.").choices(["js", "ts"]).default("js", "generates a js migration file")).option("--force", "Force creation if model already exists.", false).option("-p, --path [path]", "The path to the models directory.").action(async (name$1, opts) => {
4360
+ var _this$config$models;
4361
+ if (!this.configPath) this.terminateNotFound();
4362
+ const modelPath = path.join(this.cwd, opts.path ?? ((_this$config$models = this.config.models) === null || _this$config$models === void 0 ? void 0 : _this$config$models.path) ?? "./models", name$1.toLowerCase() + "." + opts.type);
4363
+ try {
4364
+ if (!opts.force && await Utils.fileExists(modelPath)) this.output.error("ERROR: Model already exists.");
4365
+ await mkdir(path.dirname(modelPath), { recursive: true });
4366
+ const stubPath = path.join(this.modulePath, `src/stubs/model-${opts.type}.stub`);
4367
+ let stub = await readFile(stubPath, "utf-8");
4368
+ stub = stub.replace(/{{ name }}/g, name$1);
4369
+ await writeFile(modelPath, stub);
4370
+ this.output.success(`Created Model: ${modelPath}`);
4371
+ } catch (e) {
4372
+ this.output.error("ERROR: " + e);
4373
+ }
4374
+ });
4375
+ await program.parseAsync(process.argv);
4376
+ process.exit(0);
4377
+ }
4378
+ };
4379
+
4380
+ //#endregion
4381
+ //#region src/cli/index.ts
4382
+ Cli.init();
4383
+
4384
+ //#endregion
4385
+ export { };