@h3ravel/arquebus 0.2.13 → 0.2.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/index.cjs +1 -1
- package/bin/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/migrations/index.cjs +1 -1
- package/dist/migrations/index.d.cts +4 -7
- package/dist/migrations/index.d.ts +4 -7
- package/dist/migrations/index.js +1 -1
- package/package.json +2 -2
package/dist/migrations/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"chalk";import e,{access as s}from"fs/promises";import i,{dirname as r}from"path";import n from"escalade/sync";import a from"resolve-from";import{omit as o,isEqual as h,trim as c,assign as l,diff as u,isArray as g,pick as d,isEmpty as y,flat as m,set as p,get as f,camel as w,snake as b,isString as C}from"radashi";import v from"dayjs/plugin/advancedFormat.js";import K from"dayjs";import P from"knex";import N,{collect as A,Collection as x}from"collect.js";import S from"pluralize";import{existsSync as D,readFileSync as R}from"fs";import{fileURLToPath as T}from"url";var q=Object.defineProperty,M=(t,e)=>{for(var s in e)q(t,s,{get:e[s],enumerable:!0})},k={};M(k,{default:()=>E});var E=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 I(t){const s=await e.readdir(t),i=[];for(const r of s){const s=`${t}/${r}`,n=await e.stat(s);if(n.isFile())i.push(s);else if(n.isDirectory()){const t=await I(s);i.push(...t)}}return i}M(_,{default:()=>F});var F=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(e,s,i){const r=[],n=await this.getMigrationFiles(s);this.write("Rolling back migrations.");for(const s of e){const e=n[s.migration];e?(r.push(e),await this.runDown(e,s,i.pretend||!1)):this.writeTwoColumns(s.migration,t.yellow("Migration not found"))}return r}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 I(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return i.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(e,...s){const i=s.join(" "),r=/\x1b\[\d+m/g,n=Math.min(process.stdout.columns,100),a=Math.max(n-e.replace(r,"").length-i.replace(r,"").length-10,0);this.write(e,t.gray(".".repeat(a)),i)}async writeTask(e,s){const i=process.hrtime();let r=!1;try{r=await(s||(()=>!0))()}finally{const s=process.hrtime(i),n=(1e9*s[0]+s[1])/1e6;this.writeTwoColumns(t.green(e),t.gray(`${Math.floor(n)}ms`),!1!==r?t.green("✔"):t.red("✘"))}}},Q=i.join,O=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:(e,s=!1)=>{console.log(t.green("✓"),this.textFormat(e,t.bgGreen),"\n"),s&&process.exit(0)},info:(e,s=!1)=>{console.log(t.blue("ℹ"),this.textFormat(e,t.bgBlue),"\n"),s&&process.exit(0)},error:(e,s=!0)=>{e instanceof Error?(e.message&&console.error(t.red("✖"),this.textFormat(e.message,t.bgRed)),console.error(t.red(`${e.detail?`${e.detail}\n`:""}${e.stack}`),"\n")):console.error(t.red("✖"),this.textFormat(e,t.bgRed),"\n"),s&&process.exit(1)},quiet:()=>{process.exit(0)}}}static findModulePkg(t,e){const s=t.replace(/\\/g,"/").split("/");let r="";s.length>0&&"@"===s[0][0]&&(r+=s.shift()+"/"),r+=s.shift();const n=i.join(r,"package.json"),o=a.silent(e??process.cwd(),n);if(o)return i.join(i.dirname(o),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[Q(t,i)]:[...e.getPaths(),Q(t,s)]}static twoColumnDetail(e,s){const i=/\x1b\[\d+m/g,r=Math.min(process.stdout.columns,100),n=Math.max(r-e.replace(i,"").length-s.replace(i,"").length-10,0);return console.log(e,t.gray(".".repeat(n)),s)}static async fileExists(t){try{return await s(t),!0}catch{return!1}}static findUpConfig(t,e,s){return n(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},W={};function j(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)}M(W,{compose:()=>j}),K.extend(v);var B=t=>w(`relation_${t}`),L=t=>w(`scope_${t}`),H=t=>w(`attribute_${t}`),$=t=>w(`get_${t}_attribute`),U=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:J}=W,z=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat(z(e)),[]):[t],G=t=>c(b(t.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),V=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}},Y=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?.()}},Z=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}},X=class extends(J(Y,Z)){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 xt?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof xt?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()}},tt=class t extends x{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=u(Object.keys(i.first().getAttributes()),[i.first().getKeyName()]);return this.each(t=>{const e=d(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 Dt?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=o(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(y(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 Dt&&(t=t.getKey()),g(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(A(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=d(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}}}},et=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=u(n,Object.keys(s=this.formatRecordsList(this.parseIds(t))));return e&&a.length>0&&(await this.detach(a),i.detached=this.castKeys(a)),i=l(i,await this.attachNew(s,n,!1)),i}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(A(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(g(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 A(t).mapWithKeys((t,e)=>(g(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||St).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 l(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 g(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof xt?[t[this.relatedKey]]:t instanceof tt?t.pluck(this.relatedKey).all():g(t)?t:[t]}},st=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},it=class extends st{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=g(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}},rt=class extends st{},nt=class extends st{},at=class extends(J(Y,et)){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 tt([]))}),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 tt([])}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 tt(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 it).setModel(this.related.constructor)}async paginate(t=1,e=15,s=["*"]){return this.query.select(this.shouldSelect(s)),U(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=o(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 h(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return A(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 tt([])),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)}},ot=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 tt([]),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 tt?t:new tt(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)}},ht=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},ct=class{},lt=class t extends ct{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=b(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=l({[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 U(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 ht?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=L(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=o(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=l(this.eagerLoad,e),this}const s=z(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=l(e,s)}return this.eagerLoad=l(this.eagerLoad,this.parseWithRelations(e)),this}has(t,e=">=",s=1,i="and",r=null){if(C(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(B(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=z([t]);let i={};for(const e of t){let t;"string"==typeof e?t={[e]:t=>t}:"object"==typeof e&&(t=e),i=l(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(B(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 l=c.getRelationExistenceQuery(c.getRelated().newModelQuery(),this,r.raw(h));i(l),o=o||b(`${t} ${s} ${e}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===s?this.select(r.raw(`exists(${l.toSql().sql}) as ${o}`)):this.selectSub(s?l:l.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 Y)return[e.toSql().sql,e.toSql().bindings];if(C(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 Y.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate(z(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(C(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=o(t,[i])}for(const i in t){const r=t[i];let n=i,a=r;C(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 at?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[B(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new rt(e)}return this.model[B(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 it).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(g(t[0])){if(e.count()!==t[0].length)throw(new it).setModel(this.model.constructor.name,u(t[0],e.modelKeys()));return e}if(null===e)throw(new it).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(l(t,e))}async firstOrCreate(t={},e={}){const s=await this.where(t).first();return null!==s?s:U(this.newModelInstance(l(t,e)),async t=>{await t.save({client:this.query})})}async updateOrCreate(t,e={}){return await U(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 g(t)||t instanceof tt?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof tt&&(t=t.modelKeys()),0===(t=g(t)?t:[t]).length?new tt([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new tt(e)}async destroy(t){if(t instanceof tt&&(t=t.modelKeys()),t instanceof x&&(t=t.all()),0===(t=g(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 tt(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 ot(r,parseInt(i),e,t)}async getModels(...t){return(t=m(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[B(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new rt(e)}const e=Y.noConstraints(()=>this.model.newInstance(this.model.attributes)[B(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 tt(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},ut=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")}},gt=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=z(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=z(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=z(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=w(`set_${t}_attribute`);if("function"==typeof this[s])return this[s](e),this;const i=H(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=$(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=H(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 N(JSON.parse(e))}catch{return N([])}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=o(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=o(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]=K(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[$(t)])return this[$(t)](e);if("function"==typeof this[H(t)]){return this[H(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?K(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 ut&&(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=m(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return K(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof ut}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 K(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 K(e).startOf("day").toDate()}},dt=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof ht)return this.globalScopes=p(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof ht)return this.globalScopes=p(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new nt("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return f(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 f(this.constructor.globalScopes,this.constructor.name,{})}},yt=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}},mt=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof yt==!1&&(this.hooks=new yt),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 yt!=!1)return await this.constructor.hooks.exec(t,[this,e])}},pt=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new tt(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 N(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 tt?t:new tt(t)}async create(t={}){return await U(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 tt?e:new tt(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)}}},ft=class extends(J(Y,pt)){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 tt([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new tt([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return A(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))}},wt=class extends(J(Y,pt,Z)){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])}},bt=class extends Y{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 U(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 it).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 g(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 it).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}},Ct=class extends(J(bt,Z)){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()}},vt=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=o(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[B(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new rt(e)}return this[B(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 b(t.substring(8))}joiningTable(t,e=null){return[e?e.joiningTableSegment():G(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return G(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 wt(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 ft(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 X(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 at(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 Ct(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 bt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},Kt=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())}},Pt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=z(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=u(this.hidden,e),this}makeHidden(t,...e){const s=z([...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}},Nt=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())}},At=J(class{},gt,Pt,vt,Kt,mt,dt,Nt),xt=class t extends At{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[B(s)])e.setAttribute(s,t[s]);else{const i=e[B(s)](),r=i.getRelated().constructor;i instanceof wt||i instanceof X?e.setRelation(s,r.make(t[s])):(i instanceof ft||i instanceof at)&&Array.isArray(t[s])&&e.setRelation(s,new tt(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 G(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||S(G(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):qt.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 lt(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[L(t)]}callNamedScope(t,e){return this[L(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new tt(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 tt([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=z(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 U(await n.where(this.getKeyName(),this.getKey())[i](t,e,s),async()=>{this.syncChanges(),await this.execHooks("updated",r),this.syncOriginalAttribute(t)})}toData(){return l(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(N(this.relations).reject(t=>t instanceof St).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):St.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 tt?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)}},St=class extends xt{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]}},Dt=xt,Rt=class{},Tt=class t extends Rt{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 ot(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}},qt=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 connection(t=null){return this.getInstance().getConnection(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??P}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 Tt(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=i.resolve("arquebus.config.js"),r=i.resolve("arquebus.config.ts"),n=this.getInstance();if(D(s))return e=(await import(s)).default,t&&n.addConnection(e,e.client),e;if(D(r)){if("production"!==process.env.NODE_ENV)return e=(await import(r)).default,t&&n.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=xt;if("plugins"in e&&(s=J(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 V==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[H(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[B(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[L(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},Mt=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 O.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 O.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 O.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";t.skipConnection||(qt.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{qt.addConnection(e,t)}));const s=new E(qt,e),i=new F(s,qt);return{arquebus:qt,migrator:i}}},kt={};M(kt,{Migration:()=>_t,default:()=>It});var Et=class{},_t=class extends Et{connection;withinTransaction=!0;getConnection(){return this.connection}},It=_t,Ft={};M(Ft,{default:()=>Qt});var Qt=class{constructor(t,e="js"){this.customStubPath=t,this.type=e}postCreate=[];async create(t,s,r,n=!1){const a=this.getStub(r,n),o=this.getPath(t,s);return await this.ensureDirectoryExists(i.dirname(o)),await e.writeFile(o,this.populateStub(a,r)),await this.firePostCreateHooks(r,o),o}async publish(t,s){const r=await e.readdir(this.customStubPath??"");await this.ensureDirectoryExists(t);for(const n of r){const r=i.join(this.customStubPath??"",n),a=i.join(t,n);await e.copyFile(r,a),s&&s(n,r,a)}}getStub(t,e=!1){let s;if(t)if(e){const t=i.join(this.customStubPath??"",`migration.create-${this.type}.stub`);s=D(t)?t:this.stubPath(`/migration.create-${this.type}.stub`)}else{const t=i.join(this.customStubPath??"",`migration.update-${this.type}.stub`);s=D(t)?t:this.stubPath(`/migration.update-${this.type}.stub`)}else{const t=i.join(this.customStubPath??"",`migration-${this.type}.stub`);console.log("\n",t,"---"),s=D(t)?t:this.stubPath(`/migration-${this.type}.stub`)}return R(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=K().format("YYYY_MM_DD_HHmmss");return i.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 e.mkdir(t,{recursive:!0})}stubPath(t=""){const e=this.getDirname(import.meta);return i.join(e,"stubs",t)}getDirname(t){if("undefined"!=typeof __dirname)return __dirname;if(t&&t.url)return r(T(t.url));throw new Error("Unable to determine dirname")}};export{Mt as Migrate,kt as Migration,Ft as MigrationCreator,k as MigrationRepository,_ as Migrator};
|
|
1
|
+
import t from"chalk";import e,{access as s}from"fs/promises";import i,{dirname as r}from"path";import n from"escalade/sync";import a from"resolve-from";import{omit as o,isEqual as h,trim as c,assign as l,diff as u,isArray as g,pick as d,isEmpty as y,flat as m,set as p,get as f,camel as w,snake as b,isString as C}from"radashi";import v from"dayjs/plugin/advancedFormat.js";import K from"dayjs";import P from"knex";import N,{collect as A,Collection as x}from"collect.js";import S from"pluralize";import{existsSync as D,readFileSync as R}from"fs";import{fileURLToPath as T}from"url";var q=Object.defineProperty,M=(t,e)=>{for(var s in e)q(t,s,{get:e[s],enumerable:!0})},k={};M(k,{default:()=>E});var E=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 I(t){const s=await e.readdir(t),i=[];for(const r of s){const s=`${t}/${r}`,n=await e.stat(s);if(n.isFile())i.push(s);else if(n.isDirectory()){const t=await I(s);i.push(...t)}}return i}M(_,{default:()=>F});var F=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(e,s,i){const r=[],n=await this.getMigrationFiles(s);this.write("Rolling back migrations.");for(const s of e){const e=n[s.migration];e?(r.push(e),await this.runDown(e,s,i.pretend||!1)):this.writeTwoColumns(s.migration,t.yellow("Migration not found"))}return r}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 I(s));return e.filter(Boolean).reduce((t,e)=>(t[this.getMigrationName(e)]=e,t),{})}getMigrationName(t){return i.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(e,...s){const i=s.join(" "),r=/\x1b\[\d+m/g,n=Math.min(process.stdout.columns,100),a=Math.max(n-e.replace(r,"").length-i.replace(r,"").length-10,0);this.write(e,t.gray(".".repeat(a)),i)}async writeTask(e,s){const i=process.hrtime();let r=!1;try{r=await(s||(()=>!0))()}finally{const s=process.hrtime(i),n=(1e9*s[0]+s[1])/1e6;this.writeTwoColumns(t.green(e),t.gray(`${Math.floor(n)}ms`),!1!==r?t.green("✔"):t.red("✘"))}}},Q=i.join,O=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:(e,s=!1)=>{console.log(t.green("✓"),this.textFormat(e,t.bgGreen),"\n"),s&&process.exit(0)},info:(e,s=!1)=>{console.log(t.blue("ℹ"),this.textFormat(e,t.bgBlue),"\n"),s&&process.exit(0)},error:(e,s=!0)=>{e instanceof Error?(e.message&&console.error(t.red("✖"),this.textFormat(e.message,t.bgRed)),console.error(t.red(`${e.detail?`${e.detail}\n`:""}${e.stack}`),"\n")):console.error(t.red("✖"),this.textFormat(e,t.bgRed),"\n"),s&&process.exit(1)},quiet:()=>{process.exit(0)}}}static findModulePkg(t,e){const s=t.replace(/\\/g,"/").split("/");let r="";s.length>0&&"@"===s[0][0]&&(r+=s.shift()+"/"),r+=s.shift();const n=i.join(r,"package.json"),o=a.silent(e??process.cwd(),n);if(o)return i.join(i.dirname(o),s.join("/"))}static async getMigrationPaths(t,e,s,i){return i?[Q(t,i)]:[...e.getPaths(),Q(t,s)]}static twoColumnDetail(e,s){const i=/\x1b\[\d+m/g,r=Math.min(process.stdout.columns,100),n=Math.max(r-e.replace(i,"").length-s.replace(i,"").length-10,0);return console.log(e,t.gray(".".repeat(n)),s)}static async fileExists(t){try{return await s(t),!0}catch{return!1}}static findUpConfig(t,e,s){return n(t,(t,i)=>{for(const t of s){const s=`${e}.${t}`;if(i.includes(s))return s}return!1})}},W={};function j(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)}M(W,{compose:()=>j}),K.extend(v);var B=t=>w(`relation_${t}`),L=t=>w(`scope_${t}`),H=t=>w(`attribute_${t}`),$=t=>w(`get_${t}_attribute`),U=(t,e)=>{const s=e(t);return s instanceof Promise?s.then(()=>t):t},{compose:J}=W,z=t=>Array.isArray(t)?t.reduce((t,e)=>t.concat(z(e)),[]):[t],G=t=>c(b(t.replace(/[^a-zA-Z0-9_-]/g,"-")),"_-"),V=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}},Y=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?.()}},Z=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}},X=class extends(J(Y,Z)){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 xt?t.attributes[this.ownerKey]:t;return this.child[this.foreignKey]=e,t instanceof xt?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()}},tt=class t extends x{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=u(Object.keys(i.first().getAttributes()),[i.first().getKeyName()]);return this.each(t=>{const e=d(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 Dt?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=o(this.getDictionary(),t);return new this.constructor(Object.values(e))}intersect(t){const e=new this.constructor;if(y(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 Dt&&(t=t.getKey()),g(t)?this.isEmpty()?new this.constructor:this.whereIn(this.first().getKeyName(),t):(A(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=d(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}}}},et=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=u(n,Object.keys(s=this.formatRecordsList(this.parseIds(t))));return e&&a.length>0&&(await this.detach(a),i.detached=this.castKeys(a)),i=l(i,await this.attachNew(s,n,!1)),i}syncWithoutDetaching(t){return this.sync(t,!1)}syncWithPivotValues(t,e,s=!0){return this.sync(A(this.parseIds(t)).mapWithKeys(t=>[t,e]),s)}withPivot(t){return this.pivotColumns=this.pivotColumns.concat(g(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 A(t).mapWithKeys((t,e)=>(g(t)||([e,t]=[t,{}]),[e,t])).all()}async getCurrentlyAttachedPivots(){const t=this.newPivotQuery();return(await t.get()).map(t=>(this.using||St).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 l(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 g(e)?[t,{...e,...s}]:[e,s]}hasPivotColumn(t){return this.pivotColumns.includes(t)}parseIds(t){return t instanceof xt?[t[this.relatedKey]]:t instanceof tt?t.pluck(this.relatedKey).all():g(t)?t:[t]}},st=class extends Error{constructor(t,e){super(t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=t}},it=class extends st{model;ids=[];constructor(){super("")}setModel(t,e=[]){return this.model=t,this.ids=g(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}},rt=class extends st{},nt=class extends st{},at=class extends(J(Y,et)){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 tt([]))}),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 tt([])}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 tt(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 it).setModel(this.related.constructor)}async paginate(t=1,e=15,s=["*"]){return this.query.select(this.shouldSelect(s)),U(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=o(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 h(t,["*"])&&(t=[this.related.getTable()+".*"]),t.concat(this.aliasedPivotColumns())}aliasedPivotColumns(){const t=[this.foreignPivotKey,this.relatedPivotKey];return A(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 tt([])),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)}},ot=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 tt([]),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 tt?t:new tt(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)}},ht=class t{constructor(){if(this.constructor===t)throw new Error("Scope cannot be instantiated")}apply(t,e){throw new Error("apply not implemented")}},ct=class{},lt=class t extends ct{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=b(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=l({[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 U(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 ht?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=L(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=o(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=l(this.eagerLoad,e),this}const s=z(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=l(e,s)}return this.eagerLoad=l(this.eagerLoad,this.parseWithRelations(e)),this}has(t,e=">=",s=1,i="and",r=null){if(C(t)){if(t.includes("."))return this.hasNested(t,e,s,i,r);t=this.getRelationWithoutConstraints(B(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=z([t]);let i={};for(const e of t){let t;"string"==typeof e?t={[e]:t=>t}:"object"==typeof e&&(t=e),i=l(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(B(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 l=c.getRelationExistenceQuery(c.getRelated().newModelQuery(),this,r.raw(h));i(l),o=o||b(`${t} ${s} ${e}`.replace("/[^[:alnum:][:space:]_]/u","")),"exists"===s?this.select(r.raw(`exists(${l.toSql().sql}) as ${o}`)):this.selectSub(s?l:l.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 Y)return[e.toSql().sql,e.toSql().bindings];if(C(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 Y.noConstraints(()=>this.getModel()[t]())}withCount(...t){return this.withAggregate(z(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(C(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=o(t,[i])}for(const i in t){const r=t[i];let n=i,a=r;C(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 at?e.related.getTable()+"."+t:t))}]}related(t){if("function"!=typeof this.model[B(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new rt(e)}return this.model[B(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 it).setModel(this.model.constructor.name);return e}async findOrFail(...t){const e=await this.find(...t);if(g(t[0])){if(e.count()!==t[0].length)throw(new it).setModel(this.model.constructor.name,u(t[0],e.modelKeys()));return e}if(null===e)throw(new it).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(l(t,e))}async firstOrCreate(t={},e={}){const s=await this.where(t).first();return null!==s?s:U(this.newModelInstance(l(t,e)),async t=>{await t.save({client:this.query})})}async updateOrCreate(t,e={}){return await U(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 g(t)||t instanceof tt?await this.findMany(t,e):await this.where(this.model.getKeyName(),t).first(e)}async findMany(t,e=["*"]){return t instanceof tt&&(t=t.modelKeys()),0===(t=g(t)?t:[t]).length?new tt([]):await this.whereIn(this.model.getKeyName(),t).get(e)}async pluck(t){const e=await this.query.pluck(t);return new tt(e)}async destroy(t){if(t instanceof tt&&(t=t.modelKeys()),t instanceof x&&(t=t.all()),0===(t=g(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 tt(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 ot(r,parseInt(i),e,t)}async getModels(...t){return(t=m(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[B(t)]){const e=`Model [${this.model.constructor.name}]'s relation [${t}] doesn't exist.`;throw new rt(e)}const e=Y.noConstraints(()=>this.model.newInstance(this.model.attributes)[B(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 tt(t.map(t=>{if(!this.model)return t;return this.model.newFromBuilder(t)}))}},ut=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")}},gt=t=>class extends t{static castTypeCache={};attributes={};original={};casts={};changes={};appends=[];setAppends(t){return this.appends=t,this}append(...t){const e=z(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=z(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=z(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=w(`set_${t}_attribute`);if("function"==typeof this[s])return this[s](e),this;const i=H(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=$(t);if("function"==typeof this[e])return this[e](this.attributes[t],this.attributes);const s=H(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 N(JSON.parse(e))}catch{return N([])}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=o(t,[e])),this.visible.length>0&&!1===this.visible.includes(e)&&(t=o(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]=K(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[$(t)])return this[$(t)](e);if("function"==typeof this[H(t)]){return this[H(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?K(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 ut&&(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=m(e)).length>0)||e.includes(this.getCastType(t)))}withDayjs(t){return K(t)}isCustomCast(t){return"function"==typeof t&&new t instanceof ut}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 K(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 K(e).startOf("day").toDate()}},dt=t=>class extends t{static globalScopes;static addGlobalScope(t,e=null){if("string"==typeof t&&e instanceof ht)return this.globalScopes=p(this.globalScopes??{},this.name+"."+t,e),e;if(t instanceof ht)return this.globalScopes=p(this.globalScopes??{},this.name+"."+t.constructor.name,t),t;throw new nt("Global scope must be an instance of Scope.")}static hasGlobalScope(t){return null!==this.getGlobalScope(t)}static getGlobalScope(t){return f(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 f(this.constructor.globalScopes,this.constructor.name,{})}},yt=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}},mt=t=>class extends t{static hooks=null;static addHook(t,e){this.hooks instanceof yt==!1&&(this.hooks=new yt),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 yt!=!1)return await this.constructor.hooks.exec(t,[this,e])}},pt=t=>class extends t{getRelationValue(t,e,s){const i=t[e];return"one"===s?i[0]:new tt(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 N(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 tt?t:new tt(t)}async create(t={}){return await U(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 tt?e:new tt(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)}}},ft=class extends(J(Y,pt)){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 tt([]))}),t}async getResults(){return null!==this.getParentKey()?await this.query.get():new tt([])}getForeignKeyName(){const t=this.foreignKey?.split(".");return t?.pop()}buildDictionary(t){const e=this.getForeignKeyName();return A(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))}},wt=class extends(J(Y,pt,Z)){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])}},bt=class extends Y{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 U(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 it).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 g(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 it).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}},Ct=class extends(J(bt,Z)){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()}},vt=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=o(this.relations,[t]),this}relationLoaded(t){return void 0!==this.relations[t]}related(t){if("function"!=typeof this[B(t)]){const e=`Model [${this.constructor.name}]'s relation [${t}] doesn't exist.`;throw new rt(e)}return this[B(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 b(t.substring(8))}joiningTable(t,e=null){return[e?e.joiningTableSegment():G(t.name),this.joiningTableSegment()].sort().join("_").toLocaleLowerCase()}joiningTableSegment(){return G(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 wt(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 ft(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 X(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 at(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 Ct(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 bt(a,this,e,s,i,r||this.getKeyName(),n||e.getKeyName())}},Kt=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())}},Pt=t=>class extends t{hidden=[];visible=[];makeVisible(...t){const e=z(t);return this.visible.length>0&&(this.visible=[...this.visible,...e]),this.hidden=u(this.hidden,e),this}makeHidden(t,...e){const s=z([...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}},Nt=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())}},At=J(class{},gt,Pt,vt,Kt,mt,dt,Nt),xt=class t extends At{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[B(s)])e.setAttribute(s,t[s]);else{const i=e[B(s)](),r=i.getRelated().constructor;i instanceof wt||i instanceof X?e.setRelation(s,r.make(t[s])):(i instanceof ft||i instanceof at)&&Array.isArray(t[s])&&e.setRelation(s,new tt(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 G(this.constructor.name)+"_"+this.getKeyName()}getConnectionName(){return this.connection}getTable(){return this.table||S(G(this.constructor.name))}getConnection(){return this.constructor.resolver?this.constructor.resolver.getConnection(this.connection):qt.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 lt(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[L(t)]}callNamedScope(t,e){return this[L(t)](...e)}setTable(t){return this.table=t,this}newCollection(t=[]){return new tt(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 tt([this]).loadAggregate(t,e,s),this}async loadCount(...t){return t=z(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 U(await n.where(this.getKeyName(),this.getKey())[i](t,e,s),async()=>{this.syncChanges(),await this.execHooks("updated",r),this.syncOriginalAttribute(t)})}toData(){return l(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(N(this.relations).reject(t=>t instanceof St).keys().all()),this.syncOriginal(),this}newPivot(t,e,s,i,r=null){return r?r.fromRawAttributes(t,e,s,i):St.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 tt?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)}},St=class extends xt{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]}},Dt=xt,Rt=class{},Tt=class t extends Rt{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 ot(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}},qt=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 connection(t=null){return this.getInstance().getConnection(t)}static setConnectorFactory(t){this.connectorFactory=t}static getConnectorFactory(){return this.connectorFactory??P}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 Tt(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=i.resolve("arquebus.config.js"),r=i.resolve("arquebus.config.ts"),n=this.getInstance();if(D(s))return e=(await import(s)).default,t&&n.addConnection(e,e.client),e;if(D(r)){if("production"!==process.env.NODE_ENV)return e=(await import(r)).default,t&&n.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=xt;if("plugins"in e&&(s=J(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 V==!1)throw new Error('Attribute must be an instance of "Attribute"');this.models[t].prototype[H(s)]=()=>e.attributes?.[s]}if("relations"in e)for(const s in e.relations)this.models[t].prototype[B(s)]=function(){return e.relations?.[s](this)};if("scopes"in e)for(const s in e.scopes)this.models[t].prototype[L(s)]=e.scopes[s];return this.models[t].setConnectionResolver(this),this.models[t]}},Mt=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 O.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 O.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 O.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&&(qt.addConnection(t,"default"),Object.entries(t.connections||{}).forEach(([t,e])=>{qt.addConnection(e,t)}));const s=new E(qt,e),i=new F(s,qt);return{arquebus:qt,migrator:i}}},kt={};M(kt,{Migration:()=>_t,default:()=>It});var Et=class{},_t=class extends Et{connection;withinTransaction=!0;getConnection(){return this.connection}},It=_t,Ft={};M(Ft,{default:()=>Qt});var Qt=class{constructor(t,e="js"){this.customStubPath=t,this.type=e}postCreate=[];async create(t,s,r,n=!1){const a=this.getStub(r,n),o=this.getPath(t,s);return await this.ensureDirectoryExists(i.dirname(o)),await e.writeFile(o,this.populateStub(a,r)),await this.firePostCreateHooks(r,o),o}async publish(t,s){const r=await e.readdir(this.customStubPath??"");await this.ensureDirectoryExists(t);for(const n of r){const r=i.join(this.customStubPath??"",n),a=i.join(t,n);await e.copyFile(r,a),s&&s(n,r,a)}}getStub(t,e=!1){let s;if(t)if(e){const t=i.join(this.customStubPath??"",`migration.create-${this.type}.stub`);s=D(t)?t:this.stubPath(`/migration.create-${this.type}.stub`)}else{const t=i.join(this.customStubPath??"",`migration.update-${this.type}.stub`);s=D(t)?t:this.stubPath(`/migration.update-${this.type}.stub`)}else{const t=i.join(this.customStubPath??"",`migration-${this.type}.stub`);console.log("\n",t,"---"),s=D(t)?t:this.stubPath(`/migration-${this.type}.stub`)}return R(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=K().format("YYYY_MM_DD_HHmmss");return i.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 e.mkdir(t,{recursive:!0})}stubPath(t=""){const e=this.getDirname(import.meta);return i.join(e,"stubs",t)}getDirname(t){if("undefined"!=typeof __dirname)return __dirname;if(t&&t.url)return r(T(t.url));throw new Error("Unable to determine dirname")}};export{Mt as Migrate,kt as Migration,Ft as MigrationCreator,k as MigrationRepository,_ as Migrator};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@h3ravel/arquebus",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.14",
|
|
4
4
|
"description": "Arquebus ORM is a Beautiful, expressive ORM inspired by Laravel's Eloquent, designed for TypeScript applications and for the H3ravel Framework.",
|
|
5
5
|
"homepage": "https://h3ravel.net/arquebus",
|
|
6
6
|
"bin": {
|
|
@@ -175,6 +175,6 @@
|
|
|
175
175
|
"test:postgres": "cross-env DB=postgres vitest --project node",
|
|
176
176
|
"test:sqlite": "cross-env DB=sqlite vitest --project node",
|
|
177
177
|
"test:browser": "vitest --project browser",
|
|
178
|
-
"release:patch": "git add . && git commit -m \"version: bump version and publish\" && pnpm version patch && pnpm publish --tag latest"
|
|
178
|
+
"release:patch": "pnpm build && git add . && git commit -m \"version: bump version and publish\" && pnpm version patch && pnpm publish --tag latest"
|
|
179
179
|
}
|
|
180
180
|
}
|