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