@cyberskill/shared 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const q=require("lodash-es"),B=require("migrate-mongo"),K=require("mongoose"),Q=require("mongoose-aggregate-paginate-v2"),W=require("mongoose-paginate-v2"),$=require("uuid"),H=require("./mongo.constant.cjs"),V=require("../../util/object/object.util.cjs"),k=require("../../util/common/common.util.cjs"),F=require("../fs/fs.util.cjs"),A=require("../path/path.constant.cjs"),J=require("../../util/validate/validate.util.cjs"),j=require("../../util/string/string.util.cjs"),D=require("../../constant/response-status.cjs"),d=require("../log/log.util.cjs");var X=Object.defineProperty,Y=Object.defineProperties,Z=Object.getOwnPropertyDescriptors,G=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,te=Object.prototype.propertyIsEnumerable,U=(s,t,e)=>t in s?X(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O=(s,t)=>{for(var e in t||(t={}))ee.call(t,e)&&U(s,e,t[e]);if(G)for(var e of G(t))te.call(t,e)&&U(s,e,t[e]);return s},P=(s,t)=>Y(s,Z(t)),re=(s,t,e)=>U(s,typeof t!="symbol"?t+"":t,e),l=(s,t,e)=>new Promise((r,n)=>{var c=i=>{try{u(e.next(i))}catch(a){n(a)}},o=i=>{try{u(e.throw(i))}catch(a){n(a)}},u=i=>i.done?r(i.value):Promise.resolve(i.value).then(c,o);u((e=e.apply(s,t)).next())});function ne(s){return s===s.toUpperCase()?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():s}const M={createGenericFields(){return{id:$.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(s,t){t.filter(e=>typeof e=="function").forEach(e=>s.plugin(e))},applyMiddlewares(s,t){t.forEach(({method:e,pre:r,post:n})=>{e&&r&&s.pre(e,r),e&&n&&s.post(e,n)})},createGenericSchema(s){return new s.Schema({id:{type:String,default:$.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:s,schema:t,virtuals:e=[],standalone:r=!1}){const n=new s.Schema(t,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return e.forEach(({name:c,options:o,get:u})=>{if(M.isDynamicVirtual(o)){const i=n.statics;i._dynamicVirtuals||(i._dynamicVirtuals=[]),i._dynamicVirtuals.push({name:c,options:o});const a=n.virtual(c);u?a.get(u):a.get(function(){var f;return((f=this._populated)==null?void 0:f[c])||(o!=null&&o.count?0:o!=null&&o.justOne?null:[])})}else{const i=n.virtual(c,o);u&&i.get(u)}}),r||n.add(M.createGenericSchema(s)),n},createModel({mongoose:s,name:t,schema:e,virtuals:r=[],pagination:n=!0,aggregate:c=!0,middlewares:o=[]}){if(!t)throw new Error("Model name is required.");if(s.models[t])return s.models[t];const u=M.createSchema({mongoose:s,schema:e,virtuals:r});return(n||c)&&M.applyPlugins(u,[n&&W,c&&Q]),M.applyMiddlewares(u,o),s.model(t,u)},validator:{isRequired(){return function(s){return l(this,null,function*(){return!J.validate.isEmpty(s)})}},isUnique(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:s.map(n=>({[n]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return s.every(e=>e.test(t))})}}},migrate:P(O({},B),{setConfig:s=>{const t=`// This file is automatically generated by the Cyberskill CLI.
2
- module.exports = ${JSON.stringify(s,null,4)}`;F.writeFileSync(A.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("lodash-es"),K=require("migrate-mongo"),Q=require("mongoose-aggregate-paginate-v2"),W=require("mongoose-paginate-v2"),G=require("uuid"),H=require("./mongo.constant.cjs"),T=require("./mongo.type.cjs"),b=require("../../util/object/object.util.cjs"),k=require("../../util/common/common.util.cjs"),P=require("../fs/fs.util.cjs"),A=require("../path/path.constant.cjs"),J=require("../../util/validate/validate.util.cjs"),I=require("../../util/string/string.util.cjs"),R=require("../../constant/response-status.cjs"),d=require("../log/log.util.cjs");var X=Object.defineProperty,Y=Object.defineProperties,Z=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,te=Object.prototype.propertyIsEnumerable,U=(s,t,e)=>t in s?X(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,O=(s,t)=>{for(var e in t||(t={}))ee.call(t,e)&&U(s,e,t[e]);if(z)for(var e of z(t))te.call(t,e)&&U(s,e,t[e]);return s},x=(s,t)=>Y(s,Z(t)),re=(s,t,e)=>U(s,typeof t!="symbol"?t+"":t,e),l=(s,t,e)=>new Promise((r,n)=>{var c=i=>{try{u(e.next(i))}catch(a){n(a)}},o=i=>{try{u(e.throw(i))}catch(a){n(a)}},u=i=>i.done?r(i.value):Promise.resolve(i.value).then(c,o);u((e=e.apply(s,t)).next())});function ne(s){return s===s.toUpperCase()?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():s}const M={createGenericFields(){return{id:G.v4(),isDel:!1,createdAt:new Date,updatedAt:new Date}},applyPlugins(s,t){t.filter(e=>typeof e=="function").forEach(e=>s.plugin(e))},applyMiddlewares(s,t){t.forEach(({method:e,pre:r,post:n})=>{e&&r&&s.pre(e,r),e&&n&&s.post(e,n)})},createGenericSchema(s){return new s.Schema({id:{type:String,default:G.v4,unique:!0},isDel:{type:Boolean,default:!1}},{timestamps:!0})},createSchema({mongoose:s,schema:t,virtuals:e=[],standalone:r=!1}){const n=new s.Schema(t,{toJSON:{virtuals:!0},toObject:{virtuals:!0}});return e.forEach(({name:c,options:o,get:u})=>{if(M.isDynamicVirtual(o)){const i=n.statics;i._dynamicVirtuals||(i._dynamicVirtuals=[]),i._dynamicVirtuals.push({name:c,options:o});const a=n.virtual(c);u?a.get(u):a.get(function(){var f;return((f=this._populated)==null?void 0:f[c])||(o!=null&&o.count?0:o!=null&&o.justOne?null:[])})}else{const i=n.virtual(c,o);u&&i.get(u)}}),r||n.add(M.createGenericSchema(s)),n},createModel({mongoose:s,name:t,schema:e,virtuals:r=[],pagination:n=!0,aggregate:c=!0,middlewares:o=[]}){if(!t)throw new Error("Model name is required.");if(s.models[t])return s.models[t];const u=M.createSchema({mongoose:s,schema:e,virtuals:r});return(n||c)&&M.applyPlugins(u,[n&&W,c&&Q]),M.applyMiddlewares(u,o),s.model(t,u)},validator:{isRequired(){return function(s){return l(this,null,function*(){return!J.validate.isEmpty(s)})}},isUnique(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.length===0)throw new Error("Fields must be a non-empty array of strings.");const e={$or:s.map(n=>({[n]:t}))};return!(yield this.constructor.exists(e))})}},matchesRegex(s){return function(t){return l(this,null,function*(){if(!Array.isArray(s)||s.some(e=>!(e instanceof RegExp)))throw new Error("regexArray must be an array of valid RegExp objects.");return s.every(e=>e.test(t))})}}},migrate:x(O({},K),{setConfig:s=>{const t=`// This file is automatically generated by the Cyberskill CLI.
2
+ module.exports = ${JSON.stringify(s,null,4)}`;P.writeFileSync(A.PATH.MIGRATE_MONGO_CONFIG,t);const e=`
3
3
  ${A.MIGRATE_MONGO_CONFIG}
4
- `;F.pathExistsSync(A.PATH.GIT_IGNORE)?F.readFileSync(A.PATH.GIT_IGNORE,"utf-8").split(`
5
- `).includes(A.MIGRATE_MONGO_CONFIG)||F.appendFileSync(A.PATH.GIT_IGNORE,e):F.writeFileSync(A.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=q.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=V.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const o={$regex:`.*${k.regexSearchMapper(c)}.*`,$options:"i"};e=V.setNestedValue(e,n,o)}}return e},isDynamicVirtual(s){return!!(s&&typeof s.ref=="function")},getNewRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?t.filter(c=>!r.result.some(o=>e(o,c))):t})},getExistingRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?r.result.filter(c=>t.some(o=>e(c,o))):[]})}};function se(s){return s!==null&&typeof s=="object"&&"toObject"in s&&typeof s.toObject=="function"}function I(s,t){if(!s||!t||t.length===0)return s;const e=new Set(t.map(r=>r.name));if(Array.isArray(s)){const r=s.filter(n=>{if(typeof n=="string")return!e.has(n);if(typeof n=="object"&&n!==null){const c=n;return!e.has(c.path||c.populate||"")}return!0});return r.length>0?r:void 0}if(typeof s=="string")return e.has(s)?void 0:s;if(typeof s=="object"&&s!==null){const r=s,n=r.path||r.populate||"";return e.has(n)?void 0:s}return s}function ce(s,t,e){if(!s.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return s.forEach(n=>{try{const c=e.ref(n);if(c==null)return;const o=typeof c=="string"?c:String(c);if(o&&o.trim()!==""){const u=ne(o);r.has(u)||r.set(u,[]),r.get(u).push(n)}}catch(c){d.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error?c.message:String(c)}`))}}),Array.from(r.entries()).map(([n,c])=>({model:n,docs:c}))}function z(s,t,e,r,n){return l(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(i=>{if(Array.isArray(r))return r.length>0&&r.some(a=>typeof a=="string"?a===i.name:a.path===i.name);if(typeof r=="string")return r===i.name;if(typeof r=="object"&&r!==null){const a=r;return a.path&&a.path===i.name||a.populate&&a.populate===i.name}return!1});if(c.length===0)return t;const o=q.cloneDeep(t.map(i=>se(i)?i.toObject():i));o.forEach(i=>{c.forEach(({name:a,options:f})=>{if(!(a in i)){const S=i;S[a]=f.count?0:f.justOne?null:[]}})});const u=new Map;for(const i of c){const{name:a,options:f}=i,S=ce(o,a,f);for(const h of S){u.has(h.model)||u.set(h.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const y=u.get(h.model);y.virtuals.find(T=>T.name===a)||(y.virtuals.push(i),y.localValueSets.set(a,new Set));const N=y.localValueSets.get(a);h.docs.forEach(T=>{const x=T[f.localField];if(x!=null){const _=String(x);N.add(_);let R=-1;const v=T;v.id!==void 0?R=o.findIndex(b=>b.id===v.id):v._id!==void 0&&(R=o.findIndex(b=>{var E,m,p,g;return((m=(E=b._id)==null?void 0:E.toString)==null?void 0:m.call(E))===((g=(p=v._id)==null?void 0:p.toString)==null?void 0:g.call(p))})),R!==-1&&(y.docsByLocalValue.has(_)||y.docsByLocalValue.set(_,[]),y.docsByLocalValue.get(_).push(R))}})}}return yield Promise.all(Array.from(u.entries()).map(i=>l(null,[i],function*([a,f]){const S=s.models[a];if(!S)return;const h=new Set;if(f.localValueSets.forEach(_=>{_.forEach(R=>h.add(R))}),h.size===0)return;const y=[...new Set(f.virtuals.map(_=>_.options.foreignField))],N=Array.from(h);let T;y.length===1?T={[String(y[0])]:{$in:N}}:T={$or:y.map(_=>({[_]:{$in:N}}))};const x=yield S.find(T,n).lean();for(const _ of f.virtuals){const{name:R,options:v}=_,b=x.filter(E=>{const m=E[v.foreignField];return m!=null&&h.has(String(m))});if(v.count){const E=new Map;b.forEach(m=>{var p;const g=(p=m[v.foreignField])==null?void 0:p.toString();g&&E.set(g,(E.get(g)||0)+1)}),f.localValueSets.get(R).forEach(m=>{const p=f.docsByLocalValue.get(m)||[],g=E.get(m)||0;p.forEach(w=>{const C=o[w];C[R]===void 0&&(C[R]=g)})})}else{const E=new Map;b.forEach(m=>{var p;const g=(p=m[v.foreignField])==null?void 0:p.toString();g&&(E.has(g)||E.set(g,[]),E.get(g).push(m))}),f.localValueSets.get(R).forEach(m=>{const p=f.docsByLocalValue.get(m)||[],g=E.get(m)||[],w=v.justOne?g[0]||null:g;p.forEach(C=>{const L=o[C];L[R]=w})})}}}))),o})}class oe{constructor(t,e){re(this,"collection"),this.collection=t.collection(e)}createOne(t){return l(this,null,function*(){try{const e=O(O({},M.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,null,function*(){try{const e=t.map(n=>O(O({},M.createGenericFields()),n)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:e}}catch(e){return d.catchError(e)}})}findOne(t){return l(this,null,function*(){try{const e=yield this.collection.findOne(t);return e?{success:!0,message:"Document found",result:e}:{success:!1,message:"Document not found",code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return d.catchError(e)}})}findAll(){return l(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return d.catchError(e)}})}count(){return l(this,arguments,function*(t={}){try{const e=yield this.collection.countDocuments(t);return{success:!0,message:`${e} documents counted successfully`,result:e}}catch(e){return d.catchError(e)}})}updateOne(t,e){return l(this,null,function*(){try{const r=yield this.collection.updateOne(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return d.catchError(r)}})}updateMany(t,e){return l(this,null,function*(){try{const r=yield this.collection.updateMany(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return d.catchError(r)}})}deleteOne(t){return l(this,null,function*(){try{const e=yield this.collection.deleteOne(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return d.catchError(e)}})}deleteMany(t){return l(this,null,function*(){try{const e=yield this.collection.deleteMany(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return d.catchError(e)}})}}class ue{constructor(t){this.model=t}getModelName(){return this.model.modelName}getDynamicVirtuals(){return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();if(r&&r.length>0){const n=yield z(this.model.base,[t],r,e);return n&&n[0]?n[0]:t}return t})}populateDynamicVirtualsForDocuments(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();return r&&r.length>0&&t.length>0?yield z(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=V.normalizeMongoFilter(t),o=this.model.findOne(c,e,r),u=this.getDynamicVirtuals(),i=I(n,u);i&&o.populate(i);const a=yield o.exec();return a?{success:!0,result:yield this.populateDynamicVirtualsForDocument(a,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return d.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=V.normalizeMongoFilter(t),o=this.model.find(c,e,r),u=this.getDynamicVirtuals(),i=I(n,u);i&&o.populate(i);const a=yield o.exec();return{success:!0,result:yield this.populateDynamicVirtualsForDocuments(a,n)}}catch(c){return d.catchError(c)}})}findPaging(){return l(this,arguments,function*(t={},e={}){try{const r=V.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),c=O({},e);e.populate&&(c.populate=I(e.populate,n));const o=yield this.model.paginate(r,c),u=yield this.populateDynamicVirtualsForDocuments(o.docs,e.populate);return{success:!0,result:P(O({},o),{docs:u})}}catch(r){return d.catchError(r)}})}findPagingAggregate(t){return l(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),c=O({},r);r.populate&&(c.populate=I(r.populate,n));const o=yield this.model.aggregatePaginate(this.model.aggregate(e),c),u=yield this.populateDynamicVirtualsForDocuments(o.docs,r.populate);return{success:!0,result:P(O({},o),{docs:u})}}catch(n){return d.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{const e=V.normalizeMongoFilter(t);return{success:!0,result:yield this.model.countDocuments(e)}}catch(e){return d.catchError(e)}})}createOne(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.create(t)}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,arguments,function*(e,r={}){try{return{success:!0,result:(yield this.model.insertMany(e,r)).map(o=>o instanceof K.Document?o.toObject():null).filter(o=>o!==null)}}catch(n){return d.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=V.normalizeMongoFilter(t),c=yield this.model.findOneAndUpdate(n,e,O({new:!0},r)).exec();return c?{success:!0,result:c}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return d.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{const n=V.normalizeMongoFilter(t);return{success:!0,result:yield this.model.updateMany(n,e,r).exec()}}catch(n){return d.catchError(n)}})}deleteOne(){return l(this,arguments,function*(t={},e={}){try{const r=V.normalizeMongoFilter(t),n=yield this.model.findOneAndDelete(r,e).exec();return n?{success:!0,result:n}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:D.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return d.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=V.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:D.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:n}}catch(r){return d.catchError(r)}})}createShortId(t,e=4){return l(this,null,function*(){try{const n=Array.from({length:10},(u,i)=>j.generateShortId(t,i+e)),o=(yield Promise.all(n.map(u=>this.model.exists({shortId:u})))).findIndex(u=>!u);if(o!==-1){const u=n[o];if(u)return{success:!0,result:u}}return{success:!1,message:"Failed to create a unique shortId",code:D.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return d.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,haveHistory:n=!1,filter:c}){const o=O({},c!=null?c:{});return r?P(O({},o),{$or:[{[`slug.${e}`]:t},...n?[{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]:[]]}):P(O({},o),{$or:[{slug:t},...n?[{slugHistory:t}]:[]]})}createUniqueSlug(t){return l(this,arguments,function*({slug:e,field:r,isObject:n,haveHistory:c,filter:o}){if(!e||typeof e!="string")throw new Error("Invalid slug provided: must be a non-empty string");const u=j.generateSlug(e);if(!(yield this.model.exists(this.createSlugQuery({slug:u,field:r,isObject:n,haveHistory:c,filter:o}))))return u;for(let S=1;S<=H.MONGO_SLUG_MAX_ATTEMPTS;S++){const h=`${u}-${S}`;if(!(yield this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,haveHistory:c,filter:o}))))return h}const a=Date.now(),f=Math.random().toString(36).substring(2,8);return`${u}-${a}-${f}`})}createSlug(t){return l(this,arguments,function*({field:e,from:r,filter:n,haveHistory:c}){try{const o=r[e];return q.isObject(o)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(o).map(f=>l(this,[f],function*([S,h]){const y=yield this.createUniqueSlug({slug:h,field:S,isObject:!0,haveHistory:c,filter:n});return[S,y]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:o,field:e,isObject:!1,haveHistory:c,filter:n})}}catch(o){return d.catchError(o)}})}checkSlug(t){return l(this,arguments,function*({slug:e,field:r,from:n,filter:c,haveHistory:o}){try{const u=n[r];if(q.isObject(u)){const h=Object.values(u).map(N=>j.generateSlug(N));return(yield Promise.all(h.map(N=>this.model.exists(this.createSlugQuery({slug:N,field:r,isObject:!0,haveHistory:o,filter:c}))))).some(N=>N)?{success:!0,result:!0}:{success:!0,result:!1}}const a=j.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:a,field:r,isObject:!1,filter:c})))!==null}}catch(u){return d.catchError(u)}})}aggregate(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return d.catchError(e)}})}distinct(t){return l(this,arguments,function*(e,r={},n={}){try{return{success:!0,result:yield this.model.distinct(e,r,n)}}catch(c){return d.catchError(c)}})}}exports.MongoController=oe;exports.MongooseController=ue;exports.mongo=M;
4
+ `;P.pathExistsSync(A.PATH.GIT_IGNORE)?P.readFileSync(A.PATH.GIT_IGNORE,"utf-8").split(`
5
+ `).includes(A.MIGRATE_MONGO_CONFIG)||P.appendFileSync(A.PATH.GIT_IGNORE,e):P.writeFileSync(A.PATH.GIT_IGNORE,e)}}),regexify(s,t){if(!s)return{};let e=$.cloneDeep(s);if(!t||t.length===0)return e;for(const r of t){const n=r.toString().split("."),c=b.getNestedValue(e,n);if(typeof c=="string"&&c.length>0){const o={$regex:`.*${k.regexSearchMapper(c)}.*`,$options:"i"};e=b.setNestedValue(e,n,o)}}return e},isDynamicVirtual(s){return!!(s&&typeof s.ref=="function")},getNewRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?t.filter(c=>!r.result.some(o=>e(o,c))):t})},getExistingRecords(s,t,e){return l(this,null,function*(){const r=yield s.findAll({});return r.success?r.result.filter(c=>t.some(o=>e(c,o))):[]})}};function q(s,t){if(!s||!t||t.length===0)return s;const e=new Set(t.map(r=>r.name));if(Array.isArray(s)){const r=s.filter(n=>{if(typeof n=="string")return!e.has(n);if(typeof n=="object"&&n!==null){const c=n;return!e.has(c.path||c.populate||"")}return!0});return r.length>0?r:void 0}if(typeof s=="string")return e.has(s)?void 0:s;if(typeof s=="object"&&s!==null){const r=s,n=r.path||r.populate||"";return e.has(n)?void 0:s}return s}function se(s,t,e){if(!s.length||!t||!(e!=null&&e.ref))return[];const r=new Map;return s.forEach(n=>{try{const c=e.ref(n);if(c==null)return;const o=typeof c=="string"?c:String(c);if(o&&o.trim()!==""){const u=ne(o);r.has(u)||r.set(u,[]),r.get(u).push(n)}}catch(c){d.catchError(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error?c.message:String(c)}`))}}),Array.from(r.entries()).map(([n,c])=>({model:n,docs:c}))}function L(s,t,e,r,n){return l(this,null,function*(){if(!t.length||!e.length||!r)return t;const c=e.filter(i=>{if(Array.isArray(r))return r.length>0&&r.some(a=>typeof a=="string"?a===i.name:a.path===i.name);if(typeof r=="string")return r===i.name;if(typeof r=="object"&&r!==null){const a=r;return a.path&&a.path===i.name||a.populate&&a.populate===i.name}return!1});if(c.length===0)return t;const o=$.cloneDeep(t);o.forEach(i=>{c.forEach(({name:a,options:f})=>{a in i||(i[a]=f.count?0:f.justOne?null:[])})});const u=new Map;for(const i of c){const{name:a,options:f}=i,m=se(o,a,f);for(const h of m){u.has(h.model)||u.set(h.model,{virtuals:[],localValueSets:new Map,docsByLocalValue:new Map});const E=u.get(h.model);E.virtuals.find(V=>V.name===a)||(E.virtuals.push(i),E.localValueSets.set(a,new Set));const N=E.localValueSets.get(a);h.docs.forEach(V=>{const C=V[f.localField];if(C!=null){const _=String(C);N.add(_);let D=-1;const v=V;v.id!==void 0?D=o.findIndex(F=>F.id===v.id):v._id!==void 0&&(D=o.findIndex(F=>{var S,g,p,y;return((g=(S=F._id)==null?void 0:S.toString)==null?void 0:g.call(S))===((y=(p=v._id)==null?void 0:p.toString)==null?void 0:y.call(p))})),D!==-1&&(E.docsByLocalValue.has(_)||E.docsByLocalValue.set(_,[]),E.docsByLocalValue.get(_).push(D))}})}}return yield Promise.all(Array.from(u.entries()).map(i=>l(null,[i],function*([a,f]){const m=s.models[a];if(!m)return;const h=new Set;if(f.localValueSets.forEach(_=>{_.forEach(D=>h.add(D))}),h.size===0)return;const E=[...new Set(f.virtuals.map(_=>_.options.foreignField))],N=Array.from(h);let V;E.length===1?V={[String(E[0])]:{$in:N}}:V={$or:E.map(_=>({[_]:{$in:N}}))};const C=yield m.find(V,n).lean();for(const _ of f.virtuals){const{name:D,options:v}=_,F=C.filter(S=>{const g=S[v.foreignField];return g!=null&&h.has(String(g))});if(v.count){const S=new Map;F.forEach(g=>{var p;const y=(p=g[v.foreignField])==null?void 0:p.toString();y&&S.set(y,(S.get(y)||0)+1)}),f.localValueSets.get(D).forEach(g=>{const p=f.docsByLocalValue.get(g)||[],y=S.get(g)||0;p.forEach(w=>{const j=o[w];j[D]===void 0&&(j[D]=y)})})}else{const S=new Map;F.forEach(g=>{var p;const y=(p=g[v.foreignField])==null?void 0:p.toString();y&&(S.has(y)||S.set(y,[]),S.get(y).push(g))}),f.localValueSets.get(D).forEach(g=>{const p=f.docsByLocalValue.get(g)||[],y=S.get(g)||[],w=v.justOne?y[0]||null:y;p.forEach(j=>{const B=o[j];B[D]=w})})}}}))),o})}class ce{constructor(t,e){re(this,"collection"),this.collection=t.collection(e)}createOne(t){return l(this,null,function*(){try{const e=O(O({},M.createGenericFields()),t);return(yield this.collection.insertOne(e)).acknowledged?{success:!0,message:"Document created successfully",result:e}:{success:!1,message:"Document creation failed",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,null,function*(){try{const e=t.map(n=>O(O({},M.createGenericFields()),n)),r=yield this.collection.insertMany(e);return r.insertedCount===0?{success:!1,message:"No documents were inserted",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:`${r.insertedCount} documents created successfully`,result:e}}catch(e){return d.catchError(e)}})}findOne(t){return l(this,null,function*(){try{const e=yield this.collection.findOne(t);return e?{success:!0,message:"Document found",result:e}:{success:!1,message:"Document not found",code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(e){return d.catchError(e)}})}findAll(){return l(this,arguments,function*(t={}){try{return{success:!0,message:"Documents retrieved successfully",result:yield this.collection.find(t).toArray()}}catch(e){return d.catchError(e)}})}count(){return l(this,arguments,function*(t={}){try{const e=yield this.collection.countDocuments(t);return{success:!0,message:`${e} documents counted successfully`,result:e}}catch(e){return d.catchError(e)}})}updateOne(t,e){return l(this,null,function*(){try{const r=yield this.collection.updateOne(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document updated successfully",result:r}}catch(r){return d.catchError(r)}})}updateMany(t,e){return l(this,null,function*(){try{const r=yield this.collection.updateMany(t,{$set:e});return r.matchedCount===0?{success:!1,message:"No documents matched the filter",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents updated successfully",result:r}}catch(r){return d.catchError(r)}})}deleteOne(t){return l(this,null,function*(){try{const e=yield this.collection.deleteOne(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Document deleted successfully",result:e}}catch(e){return d.catchError(e)}})}deleteMany(t){return l(this,null,function*(){try{const e=yield this.collection.deleteMany(t);return e.deletedCount===0?{success:!1,message:"No documents matched the filter",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}:{success:!0,message:"Documents deleted successfully",result:e}}catch(e){return d.catchError(e)}})}}class oe{constructor(t){this.model=t}getModelName(){return this.model.modelName}getDynamicVirtuals(){return this.model.schema.statics._dynamicVirtuals}populateDynamicVirtualsForDocument(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();if(r&&r.length>0){const n=yield L(this.model.base,[t],r,e);return n&&n[0]?n[0]:t}return t})}populateDynamicVirtualsForDocuments(t,e){return l(this,null,function*(){const r=this.getDynamicVirtuals();return r&&r.length>0&&t.length>0?yield L(this.model.base,t,r,e):t})}findOne(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=b.normalizeMongoFilter(t),o=this.model.findOne(c,e,r),u=this.getDynamicVirtuals(),i=q(n,u);i&&o.populate(i);const a=yield o.exec().then(m=>m instanceof T.C_Document?m.toObject():m);return a?{success:!0,result:yield this.populateDynamicVirtualsForDocument(a,n)}:{success:!1,message:`No ${this.getModelName()} found.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(c){return d.catchError(c)}})}findAll(){return l(this,arguments,function*(t={},e={},r={},n){try{const c=b.normalizeMongoFilter(t),o=this.model.find(c,e,r),u=this.getDynamicVirtuals(),i=q(n,u);i&&o.populate(i);const a=yield o.exec().then(m=>m==null?void 0:m.map(h=>h instanceof T.C_Document?h.toObject():h));return{success:!0,result:yield this.populateDynamicVirtualsForDocuments(a,n)}}catch(c){return d.catchError(c)}})}findPaging(){return l(this,arguments,function*(t={},e={}){try{const r=b.normalizeMongoFilter(t),n=this.getDynamicVirtuals(),c=O({},e);e.populate&&(c.populate=q(e.populate,n));const o=yield this.model.paginate(r,c),u=yield this.populateDynamicVirtualsForDocuments(o.docs.map(i=>i instanceof T.C_Document?i.toObject():i),e.populate);return{success:!0,result:x(O({},o),{docs:u})}}catch(r){return d.catchError(r)}})}findPagingAggregate(t){return l(this,arguments,function*(e,r={}){try{const n=this.getDynamicVirtuals(),c=O({},r);r.populate&&(c.populate=q(r.populate,n));const o=yield this.model.aggregatePaginate(this.model.aggregate(e),c),u=yield this.populateDynamicVirtualsForDocuments(o.docs.map(i=>i instanceof T.C_Document?i.toObject():i),r.populate);return{success:!0,result:x(O({},o),{docs:u})}}catch(n){return d.catchError(n)}})}count(){return l(this,arguments,function*(t={}){try{const e=b.normalizeMongoFilter(t);return{success:!0,result:yield this.model.countDocuments(e)}}catch(e){return d.catchError(e)}})}createOne(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.create(t).then(r=>r instanceof T.C_Document?r.toObject():r)}}catch(e){return d.catchError(e)}})}createMany(t){return l(this,arguments,function*(e,r={}){try{return{success:!0,result:yield this.model.insertMany(e,r).then(c=>c.map(o=>o instanceof T.C_Document?o.toObject():o))}}catch(n){return d.catchError(n)}})}updateOne(){return l(this,arguments,function*(t={},e={},r={}){try{const n=b.normalizeMongoFilter(t),c=yield this.model.findOneAndUpdate(n,e,O({new:!0},r)).exec().then(o=>o instanceof T.C_Document?o.toObject():o);return c?{success:!0,result:c}:{success:!1,message:`Failed to update ${this.getModelName()}.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(n){return d.catchError(n)}})}updateMany(){return l(this,arguments,function*(t={},e={},r={}){try{const n=b.normalizeMongoFilter(t);return{success:!0,result:yield this.model.updateMany(n,e,r).exec()}}catch(n){return d.catchError(n)}})}deleteOne(){return l(this,arguments,function*(t={},e={}){try{const r=b.normalizeMongoFilter(t),n=yield this.model.findOneAndDelete(r,e).exec().then(c=>c instanceof T.C_Document?c.toObject():c);return n?{success:!0,result:n}:{success:!1,message:`No ${this.getModelName()} found to delete.`,code:R.RESPONSE_STATUS.NOT_FOUND.CODE}}catch(r){return d.catchError(r)}})}deleteMany(){return l(this,arguments,function*(t={},e={}){try{const r=b.normalizeMongoFilter(t),n=yield this.model.deleteMany(r,e).exec();return n.deletedCount===0?{success:!1,message:"No documents found to delete.",code:R.RESPONSE_STATUS.NOT_FOUND.CODE}:{success:!0,result:n}}catch(r){return d.catchError(r)}})}createShortId(t,e=4){return l(this,null,function*(){try{const n=Array.from({length:10},(u,i)=>I.generateShortId(t,i+e)),o=(yield Promise.all(n.map(u=>this.model.exists({shortId:u})))).findIndex(u=>!u);if(o!==-1){const u=n[o];if(u)return{success:!0,result:u}}return{success:!1,message:"Failed to create a unique shortId",code:R.RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE}}catch(r){return d.catchError(r)}})}createSlugQuery({slug:t,field:e,isObject:r,haveHistory:n=!1,filter:c}){const o=O({},c!=null?c:{});return r?x(O({},o),{$or:[{[`slug.${e}`]:t},...n?[{slugHistory:{$elemMatch:{[`slug.${e}`]:t}}}]:[]]}):x(O({},o),{$or:[{slug:t},...n?[{slugHistory:t}]:[]]})}createUniqueSlug(t){return l(this,arguments,function*({slug:e,field:r,isObject:n,haveHistory:c,filter:o}){if(!e||typeof e!="string")throw new Error("Invalid slug provided: must be a non-empty string");const u=I.generateSlug(e);if(!(yield this.model.exists(this.createSlugQuery({slug:u,field:r,isObject:n,haveHistory:c,filter:o}))))return u;for(let m=1;m<=H.MONGO_SLUG_MAX_ATTEMPTS;m++){const h=`${u}-${m}`;if(!(yield this.model.exists(this.createSlugQuery({slug:h,field:r,isObject:n,haveHistory:c,filter:o}))))return h}const a=Date.now(),f=Math.random().toString(36).substring(2,8);return`${u}-${a}-${f}`})}createSlug(t){return l(this,arguments,function*({field:e,from:r,filter:n,haveHistory:c}){try{const o=r[e];return $.isObject(o)?{success:!0,result:Object.fromEntries(yield Promise.all(Object.entries(o).map(f=>l(this,[f],function*([m,h]){const E=yield this.createUniqueSlug({slug:h,field:m,isObject:!0,haveHistory:c,filter:n});return[m,E]}))))}:{success:!0,result:yield this.createUniqueSlug({slug:o,field:e,isObject:!1,haveHistory:c,filter:n})}}catch(o){return d.catchError(o)}})}checkSlug(t){return l(this,arguments,function*({slug:e,field:r,from:n,filter:c,haveHistory:o}){try{const u=n[r];if($.isObject(u)){const h=Object.values(u).map(N=>I.generateSlug(N));return(yield Promise.all(h.map(N=>this.model.exists(this.createSlugQuery({slug:N,field:r,isObject:!0,haveHistory:o,filter:c}))))).some(N=>N)?{success:!0,result:!0}:{success:!0,result:!1}}const a=I.generateSlug(e);return{success:!0,result:(yield this.model.exists(this.createSlugQuery({slug:a,field:r,isObject:!1,filter:c})))!==null}}catch(u){return d.catchError(u)}})}aggregate(t){return l(this,null,function*(){try{return{success:!0,result:yield this.model.aggregate(t)}}catch(e){return d.catchError(e)}})}distinct(t){return l(this,arguments,function*(e,r={},n={}){try{return{success:!0,result:yield this.model.distinct(e,r,n)}}catch(c){return d.catchError(c)}})}}exports.MongoController=ce;exports.MongooseController=oe;exports.mongo=M;
@@ -1,7 +1,7 @@
1
1
  import { default as mongooseRaw } from 'mongoose';
2
2
  import { default as migrate } from 'migrate-mongo';
3
3
  import { I_Return } from '../../typescript/index.js';
4
- import { C_Db, C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DeleteOptionsExtended, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_MongooseModelMiddleware, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Filter, T_FilterQuery, T_Input_Populate, T_InsertManyOptions, T_MongoosePlugin, T_MongooseShema, T_PaginateResult, T_PipelineStage, T_ProjectionType, T_QueryOptions, T_UpdateQuery, T_UpdateResult, T_VirtualOptions, T_WithId } from './mongo.type.js';
4
+ import { C_Db, I_CreateModelOptions, I_CreateSchemaOptions, I_DeleteOptionsExtended, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_MongooseModelMiddleware, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Filter, T_FilterQuery, T_Input_Populate, T_InsertManyOptions, T_MongoosePlugin, T_MongooseShema, T_PaginateResult, T_PipelineStage, T_ProjectionType, T_QueryOptions, T_UpdateQuery, T_UpdateResult, T_VirtualOptions, T_WithId, C_Document } from './mongo.type.js';
5
5
  /**
6
6
  * MongoDB utility object providing comprehensive database operations and utilities.
7
7
  * This object contains methods for creating generic fields, applying plugins and middlewares,
@@ -412,6 +412,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
412
412
  * @param options.slug - The slug string to check for existence.
413
413
  * @param options.field - The field name for object-based slug checking.
414
414
  * @param options.isObject - Whether the slug is stored as an object with nested fields.
415
+ * @param options.haveHistory - Whether to check historical slug fields for existence.
415
416
  * @param options.filter - Additional filter conditions to apply to the query.
416
417
  * @returns A MongoDB query object for checking slug existence.
417
418
  */
@@ -579,6 +580,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
579
580
  * @param options.slug - The base slug string to make unique.
580
581
  * @param options.field - The field name for object-based slug checking.
581
582
  * @param options.isObject - Whether the slug is stored as an object with nested fields.
583
+ * @param options.haveHistory - Whether to check historical slug fields for uniqueness.
582
584
  * @param options.filter - Additional filter conditions to apply when checking slug existence.
583
585
  * @returns A promise that resolves to a unique slug string.
584
586
  */
@@ -590,6 +592,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
590
592
  * @param options - Configuration for slug creation including field, source document, and filter.
591
593
  * @param options.field - The field name to create a slug for.
592
594
  * @param options.from - The source document containing the field value.
595
+ * @param options.haveHistory - Whether to check historical slug fields for uniqueness.
593
596
  * @param options.filter - Additional filter conditions to apply when checking slug existence.
594
597
  * @returns A promise that resolves to a standardized response with the created slug(s).
595
598
  */
@@ -602,6 +605,7 @@ export declare class MongooseController<T extends Partial<C_Document>> {
602
605
  * @param options.slug - The slug string to check for existence.
603
606
  * @param options.field - The field name for object-based slug checking.
604
607
  * @param options.from - The source document containing the field value.
608
+ * @param options.haveHistory - Whether to check historical slug fields for existence.
605
609
  * @param options.filter - Additional filter conditions to apply to the query.
606
610
  * @returns A promise that resolves to a standardized response indicating whether the slug exists.
607
611
  */
@@ -1,45 +1,45 @@
1
- import { cloneDeep as B, isObject as $ } from "lodash-es";
2
- import Q from "migrate-mongo";
3
- import { Document as W } from "mongoose";
1
+ import { cloneDeep as K, isObject as G } from "lodash-es";
2
+ import W from "migrate-mongo";
4
3
  import k from "mongoose-aggregate-paginate-v2";
5
4
  import J from "mongoose-paginate-v2";
6
- import { v4 as G } from "uuid";
5
+ import { v4 as q } from "uuid";
7
6
  import { MONGO_SLUG_MAX_ATTEMPTS as X } from "./mongo.constant.js";
8
- import { getNestedValue as H, setNestedValue as Y, normalizeMongoFilter as b } from "../../util/object/object.util.js";
7
+ import { C_Document as b } from "./mongo.type.js";
8
+ import { getNestedValue as H, setNestedValue as Y, normalizeMongoFilter as x } from "../../util/object/object.util.js";
9
9
  import { regexSearchMapper as Z } from "../../util/common/common.util.js";
10
- import { writeFileSync as q, pathExistsSync as ee, readFileSync as te, appendFileSync as re } from "../fs/fs.util.js";
11
- import { PATH as w, MIGRATE_MONGO_CONFIG as L } from "../path/path.constant.js";
10
+ import { writeFileSync as L, pathExistsSync as ee, readFileSync as te, appendFileSync as re } from "../fs/fs.util.js";
11
+ import { PATH as M, MIGRATE_MONGO_CONFIG as U } from "../path/path.constant.js";
12
12
  import { validate as se } from "../../util/validate/validate.util.js";
13
- import { generateShortId as ne, generateSlug as I } from "../../util/string/string.util.js";
13
+ import { generateShortId as ne, generateSlug as $ } from "../../util/string/string.util.js";
14
14
  import { RESPONSE_STATUS as R } from "../../constant/response-status.js";
15
15
  import { catchError as d } from "../log/log.util.js";
16
- var ue = Object.defineProperty, ce = Object.defineProperties, ie = Object.getOwnPropertyDescriptors, U = Object.getOwnPropertySymbols, oe = Object.prototype.hasOwnProperty, le = Object.prototype.propertyIsEnumerable, T = (n, t, e) => t in n ? ue(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e, S = (n, t) => {
16
+ var ce = Object.defineProperty, ue = Object.defineProperties, oe = Object.getOwnPropertyDescriptors, z = Object.getOwnPropertySymbols, ie = Object.prototype.hasOwnProperty, le = Object.prototype.propertyIsEnumerable, T = (n, t, e) => t in n ? ce(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e, S = (n, t) => {
17
17
  for (var e in t || (t = {}))
18
- oe.call(t, e) && T(n, e, t[e]);
19
- if (U)
20
- for (var e of U(t))
18
+ ie.call(t, e) && T(n, e, t[e]);
19
+ if (z)
20
+ for (var e of z(t))
21
21
  le.call(t, e) && T(n, e, t[e]);
22
22
  return n;
23
- }, F = (n, t) => ce(n, ie(t)), ae = (n, t, e) => T(n, typeof t != "symbol" ? t + "" : t, e), l = (n, t, e) => new Promise((r, s) => {
24
- var u = (o) => {
23
+ }, j = (n, t) => ue(n, oe(t)), ae = (n, t, e) => T(n, typeof t != "symbol" ? t + "" : t, e), l = (n, t, e) => new Promise((r, s) => {
24
+ var c = (i) => {
25
25
  try {
26
- i(e.next(o));
26
+ o(e.next(i));
27
27
  } catch (a) {
28
28
  s(a);
29
29
  }
30
- }, c = (o) => {
30
+ }, u = (i) => {
31
31
  try {
32
- i(e.throw(o));
32
+ o(e.throw(i));
33
33
  } catch (a) {
34
34
  s(a);
35
35
  }
36
- }, i = (o) => o.done ? r(o.value) : Promise.resolve(o.value).then(u, c);
37
- i((e = e.apply(n, t)).next());
36
+ }, o = (i) => i.done ? r(i.value) : Promise.resolve(i.value).then(c, u);
37
+ o((e = e.apply(n, t)).next());
38
38
  });
39
39
  function de(n) {
40
40
  return n === n.toUpperCase() ? n.charAt(0).toUpperCase() + n.slice(1).toLowerCase() : n;
41
41
  }
42
- const x = {
42
+ const w = {
43
43
  /**
44
44
  * Creates generic fields that are commonly used across MongoDB documents.
45
45
  * This function generates standard fields including a UUID, deletion flag, and timestamps
@@ -49,7 +49,7 @@ const x = {
49
49
  */
50
50
  createGenericFields() {
51
51
  return {
52
- id: G(),
52
+ id: q(),
53
53
  isDel: !1,
54
54
  createdAt: /* @__PURE__ */ new Date(),
55
55
  updatedAt: /* @__PURE__ */ new Date()
@@ -89,7 +89,7 @@ const x = {
89
89
  createGenericSchema(n) {
90
90
  return new n.Schema(
91
91
  {
92
- id: { type: String, default: G, unique: !0 },
92
+ id: { type: String, default: q, unique: !0 },
93
93
  isDel: { type: Boolean, default: !1 }
94
94
  },
95
95
  { timestamps: !0 }
@@ -119,23 +119,23 @@ const x = {
119
119
  toObject: { virtuals: !0 }
120
120
  // So `console.log()` and other functions that use `toObject()` include virtuals
121
121
  });
122
- return e.forEach(({ name: u, options: c, get: i }) => {
123
- if (x.isDynamicVirtual(c)) {
124
- const o = s.statics;
125
- o._dynamicVirtuals || (o._dynamicVirtuals = []), o._dynamicVirtuals.push({
126
- name: u,
127
- options: c
122
+ return e.forEach(({ name: c, options: u, get: o }) => {
123
+ if (w.isDynamicVirtual(u)) {
124
+ const i = s.statics;
125
+ i._dynamicVirtuals || (i._dynamicVirtuals = []), i._dynamicVirtuals.push({
126
+ name: c,
127
+ options: u
128
128
  });
129
- const a = s.virtual(u);
130
- i ? a.get(i) : a.get(function() {
129
+ const a = s.virtual(c);
130
+ o ? a.get(o) : a.get(function() {
131
131
  var f;
132
- return ((f = this._populated) == null ? void 0 : f[u]) || (c != null && c.count ? 0 : c != null && c.justOne ? null : []);
132
+ return ((f = this._populated) == null ? void 0 : f[c]) || (u != null && u.count ? 0 : u != null && u.justOne ? null : []);
133
133
  });
134
134
  } else {
135
- const o = s.virtual(u, c);
136
- i && o.get(i);
135
+ const i = s.virtual(c, u);
136
+ o && i.get(o);
137
137
  }
138
- }), r || s.add(x.createGenericSchema(n)), s;
138
+ }), r || s.add(w.createGenericSchema(n)), s;
139
139
  },
140
140
  /**
141
141
  * Creates a Mongoose model with plugins, middleware, and pagination support.
@@ -159,18 +159,18 @@ const x = {
159
159
  schema: e,
160
160
  virtuals: r = [],
161
161
  pagination: s = !0,
162
- aggregate: u = !0,
163
- middlewares: c = []
162
+ aggregate: c = !0,
163
+ middlewares: u = []
164
164
  }) {
165
165
  if (!t)
166
166
  throw new Error("Model name is required.");
167
167
  if (n.models[t])
168
168
  return n.models[t];
169
- const i = x.createSchema({ mongoose: n, schema: e, virtuals: r });
170
- return (s || u) && x.applyPlugins(i, [
169
+ const o = w.createSchema({ mongoose: n, schema: e, virtuals: r });
170
+ return (s || c) && w.applyPlugins(o, [
171
171
  s && J,
172
- u && k
173
- ]), x.applyMiddlewares(i, c), n.model(t, i);
172
+ c && k
173
+ ]), w.applyMiddlewares(o, u), n.model(t, o);
174
174
  },
175
175
  /**
176
176
  * Validation utilities for Mongoose schemas.
@@ -233,7 +233,7 @@ const x = {
233
233
  * Migration utilities for MongoDB.
234
234
  * This object extends the migrate-mongo library with additional configuration utilities.
235
235
  */
236
- migrate: F(S({}, Q), {
236
+ migrate: j(S({}, W), {
237
237
  /**
238
238
  * Sets the migration configuration and updates .gitignore.
239
239
  * This function creates a migration configuration file and ensures it's properly
@@ -244,12 +244,12 @@ const x = {
244
244
  setConfig: (n) => {
245
245
  const t = `// This file is automatically generated by the Cyberskill CLI.
246
246
  module.exports = ${JSON.stringify(n, null, 4)}`;
247
- q(w.MIGRATE_MONGO_CONFIG, t);
247
+ L(M.MIGRATE_MONGO_CONFIG, t);
248
248
  const e = `
249
- ${L}
249
+ ${U}
250
250
  `;
251
- ee(w.GIT_IGNORE) ? te(w.GIT_IGNORE, "utf-8").split(`
252
- `).includes(L) || re(w.GIT_IGNORE, e) : q(w.GIT_IGNORE, e);
251
+ ee(M.GIT_IGNORE) ? te(M.GIT_IGNORE, "utf-8").split(`
252
+ `).includes(U) || re(M.GIT_IGNORE, e) : L(M.GIT_IGNORE, e);
253
253
  }
254
254
  }),
255
255
  /**
@@ -264,17 +264,17 @@ ${L}
264
264
  regexify(n, t) {
265
265
  if (!n)
266
266
  return {};
267
- let e = B(n);
267
+ let e = K(n);
268
268
  if (!t || t.length === 0)
269
269
  return e;
270
270
  for (const r of t) {
271
- const s = r.toString().split("."), u = H(e, s);
272
- if (typeof u == "string" && u.length > 0) {
273
- const c = {
274
- $regex: `.*${Z(u)}.*`,
271
+ const s = r.toString().split("."), c = H(e, s);
272
+ if (typeof c == "string" && c.length > 0) {
273
+ const u = {
274
+ $regex: `.*${Z(c)}.*`,
275
275
  $options: "i"
276
276
  };
277
- e = Y(e, s, c);
277
+ e = Y(e, s, u);
278
278
  }
279
279
  }
280
280
  return e;
@@ -299,8 +299,8 @@ ${L}
299
299
  return l(this, null, function* () {
300
300
  const r = yield n.findAll({});
301
301
  return r.success ? t.filter(
302
- (u) => !r.result.some(
303
- (c) => e(c, u)
302
+ (c) => !r.result.some(
303
+ (u) => e(u, c)
304
304
  )
305
305
  ) : t;
306
306
  });
@@ -316,17 +316,14 @@ ${L}
316
316
  return l(this, null, function* () {
317
317
  const r = yield n.findAll({});
318
318
  return r.success ? r.result.filter(
319
- (u) => t.some(
320
- (c) => e(u, c)
319
+ (c) => t.some(
320
+ (u) => e(c, u)
321
321
  )
322
322
  ) : [];
323
323
  });
324
324
  }
325
325
  };
326
- function fe(n) {
327
- return n !== null && typeof n == "object" && "toObject" in n && typeof n.toObject == "function";
328
- }
329
- function j(n, t) {
326
+ function I(n, t) {
330
327
  if (!n || !t || t.length === 0)
331
328
  return n;
332
329
  const e = new Set(t.map((r) => r.name));
@@ -335,8 +332,8 @@ function j(n, t) {
335
332
  if (typeof s == "string")
336
333
  return !e.has(s);
337
334
  if (typeof s == "object" && s !== null) {
338
- const u = s;
339
- return !e.has(u.path || u.populate || "");
335
+ const c = s;
336
+ return !e.has(c.path || c.populate || "");
340
337
  }
341
338
  return !0;
342
339
  });
@@ -350,130 +347,125 @@ function j(n, t) {
350
347
  }
351
348
  return n;
352
349
  }
353
- function me(n, t, e) {
350
+ function fe(n, t, e) {
354
351
  if (!n.length || !t || !(e != null && e.ref))
355
352
  return [];
356
353
  const r = /* @__PURE__ */ new Map();
357
354
  return n.forEach((s) => {
358
355
  try {
359
- const u = e.ref(s);
360
- if (u == null)
356
+ const c = e.ref(s);
357
+ if (c == null)
361
358
  return;
362
- const c = typeof u == "string" ? u : String(u);
363
- if (c && c.trim() !== "") {
364
- const i = de(c);
365
- r.has(i) || r.set(i, []), r.get(i).push(s);
359
+ const u = typeof c == "string" ? c : String(c);
360
+ if (u && u.trim() !== "") {
361
+ const o = de(u);
362
+ r.has(o) || r.set(o, []), r.get(o).push(s);
366
363
  }
367
- } catch (u) {
368
- d(new Error(`Dynamic ref function failed for virtual "${t}": ${u instanceof Error ? u.message : String(u)}`));
364
+ } catch (c) {
365
+ d(new Error(`Dynamic ref function failed for virtual "${t}": ${c instanceof Error ? c.message : String(c)}`));
369
366
  }
370
- }), Array.from(r.entries()).map(([s, u]) => ({ model: s, docs: u }));
367
+ }), Array.from(r.entries()).map(([s, c]) => ({ model: s, docs: c }));
371
368
  }
372
- function z(n, t, e, r, s) {
369
+ function B(n, t, e, r, s) {
373
370
  return l(this, null, function* () {
374
371
  if (!t.length || !e.length || !r)
375
372
  return t;
376
- const u = e.filter((o) => {
373
+ const c = e.filter((i) => {
377
374
  if (Array.isArray(r))
378
- return r.length > 0 && r.some((a) => typeof a == "string" ? a === o.name : a.path === o.name);
375
+ return r.length > 0 && r.some((a) => typeof a == "string" ? a === i.name : a.path === i.name);
379
376
  if (typeof r == "string")
380
- return r === o.name;
377
+ return r === i.name;
381
378
  if (typeof r == "object" && r !== null) {
382
379
  const a = r;
383
- return a.path && a.path === o.name || a.populate && a.populate === o.name;
380
+ return a.path && a.path === i.name || a.populate && a.populate === i.name;
384
381
  }
385
382
  return !1;
386
383
  });
387
- if (u.length === 0)
384
+ if (c.length === 0)
388
385
  return t;
389
- const c = B(t.map(
390
- (o) => fe(o) ? o.toObject() : o
391
- ));
392
- c.forEach((o) => {
393
- u.forEach(({ name: a, options: f }) => {
394
- if (!(a in o)) {
395
- const O = o;
396
- O[a] = f.count ? 0 : f.justOne ? null : [];
397
- }
386
+ const u = K(t);
387
+ u.forEach((i) => {
388
+ c.forEach(({ name: a, options: f }) => {
389
+ a in i || (i[a] = f.count ? 0 : f.justOne ? null : []);
398
390
  });
399
391
  });
400
- const i = /* @__PURE__ */ new Map();
401
- for (const o of u) {
402
- const { name: a, options: f } = o, O = me(c, a, f);
403
- for (const m of O) {
404
- i.has(m.model) || i.set(m.model, {
392
+ const o = /* @__PURE__ */ new Map();
393
+ for (const i of c) {
394
+ const { name: a, options: f } = i, h = fe(u, a, f);
395
+ for (const m of h) {
396
+ o.has(m.model) || o.set(m.model, {
405
397
  virtuals: [],
406
398
  localValueSets: /* @__PURE__ */ new Map(),
407
399
  docsByLocalValue: /* @__PURE__ */ new Map()
408
400
  });
409
- const g = i.get(m.model);
410
- g.virtuals.find((V) => V.name === a) || (g.virtuals.push(o), g.localValueSets.set(a, /* @__PURE__ */ new Set()));
411
- const v = g.localValueSets.get(a);
401
+ const p = o.get(m.model);
402
+ p.virtuals.find((V) => V.name === a) || (p.virtuals.push(i), p.localValueSets.set(a, /* @__PURE__ */ new Set()));
403
+ const v = p.localValueSets.get(a);
412
404
  m.docs.forEach((V) => {
413
405
  const A = V[f.localField];
414
406
  if (A != null) {
415
- const D = String(A);
416
- v.add(D);
417
- let _ = -1;
407
+ const _ = String(A);
408
+ v.add(_);
409
+ let D = -1;
418
410
  const N = V;
419
- N.id !== void 0 ? _ = c.findIndex((M) => M.id === N.id) : N._id !== void 0 && (_ = c.findIndex((M) => {
420
- var p, h, E, y;
421
- return ((h = (p = M._id) == null ? void 0 : p.toString) == null ? void 0 : h.call(p)) === ((y = (E = N._id) == null ? void 0 : E.toString) == null ? void 0 : y.call(E));
422
- })), _ !== -1 && (g.docsByLocalValue.has(D) || g.docsByLocalValue.set(D, []), g.docsByLocalValue.get(D).push(_));
411
+ N.id !== void 0 ? D = u.findIndex((F) => F.id === N.id) : N._id !== void 0 && (D = u.findIndex((F) => {
412
+ var O, y, E, g;
413
+ return ((y = (O = F._id) == null ? void 0 : O.toString) == null ? void 0 : y.call(O)) === ((g = (E = N._id) == null ? void 0 : E.toString) == null ? void 0 : g.call(E));
414
+ })), D !== -1 && (p.docsByLocalValue.has(_) || p.docsByLocalValue.set(_, []), p.docsByLocalValue.get(_).push(D));
423
415
  }
424
416
  });
425
417
  }
426
418
  }
427
- return yield Promise.all(Array.from(i.entries()).map((o) => l(null, [o], function* ([a, f]) {
428
- const O = n.models[a];
429
- if (!O)
419
+ return yield Promise.all(Array.from(o.entries()).map((i) => l(null, [i], function* ([a, f]) {
420
+ const h = n.models[a];
421
+ if (!h)
430
422
  return;
431
423
  const m = /* @__PURE__ */ new Set();
432
- if (f.localValueSets.forEach((D) => {
433
- D.forEach((_) => m.add(_));
424
+ if (f.localValueSets.forEach((_) => {
425
+ _.forEach((D) => m.add(D));
434
426
  }), m.size === 0)
435
427
  return;
436
- const g = [...new Set(f.virtuals.map((D) => D.options.foreignField))], v = Array.from(m);
428
+ const p = [...new Set(f.virtuals.map((_) => _.options.foreignField))], v = Array.from(m);
437
429
  let V;
438
- g.length === 1 ? V = { [String(g[0])]: { $in: v } } : V = { $or: g.map((D) => ({ [D]: { $in: v } })) };
439
- const A = yield O.find(V, s).lean();
440
- for (const D of f.virtuals) {
441
- const { name: _, options: N } = D, M = A.filter((p) => {
442
- const h = p[N.foreignField];
443
- return h != null && m.has(String(h));
430
+ p.length === 1 ? V = { [String(p[0])]: { $in: v } } : V = { $or: p.map((_) => ({ [_]: { $in: v } })) };
431
+ const A = yield h.find(V, s).lean();
432
+ for (const _ of f.virtuals) {
433
+ const { name: D, options: N } = _, F = A.filter((O) => {
434
+ const y = O[N.foreignField];
435
+ return y != null && m.has(String(y));
444
436
  });
445
437
  if (N.count) {
446
- const p = /* @__PURE__ */ new Map();
447
- M.forEach((h) => {
438
+ const O = /* @__PURE__ */ new Map();
439
+ F.forEach((y) => {
448
440
  var E;
449
- const y = (E = h[N.foreignField]) == null ? void 0 : E.toString();
450
- y && p.set(y, (p.get(y) || 0) + 1);
451
- }), f.localValueSets.get(_).forEach((h) => {
452
- const E = f.docsByLocalValue.get(h) || [], y = p.get(h) || 0;
453
- E.forEach((P) => {
454
- const C = c[P];
455
- C[_] === void 0 && (C[_] = y);
441
+ const g = (E = y[N.foreignField]) == null ? void 0 : E.toString();
442
+ g && O.set(g, (O.get(g) || 0) + 1);
443
+ }), f.localValueSets.get(D).forEach((y) => {
444
+ const E = f.docsByLocalValue.get(y) || [], g = O.get(y) || 0;
445
+ E.forEach((C) => {
446
+ const P = u[C];
447
+ P[D] === void 0 && (P[D] = g);
456
448
  });
457
449
  });
458
450
  } else {
459
- const p = /* @__PURE__ */ new Map();
460
- M.forEach((h) => {
451
+ const O = /* @__PURE__ */ new Map();
452
+ F.forEach((y) => {
461
453
  var E;
462
- const y = (E = h[N.foreignField]) == null ? void 0 : E.toString();
463
- y && (p.has(y) || p.set(y, []), p.get(y).push(h));
464
- }), f.localValueSets.get(_).forEach((h) => {
465
- const E = f.docsByLocalValue.get(h) || [], y = p.get(h) || [], P = N.justOne ? y[0] || null : y;
466
- E.forEach((C) => {
467
- const K = c[C];
468
- K[_] = P;
454
+ const g = (E = y[N.foreignField]) == null ? void 0 : E.toString();
455
+ g && (O.has(g) || O.set(g, []), O.get(g).push(y));
456
+ }), f.localValueSets.get(D).forEach((y) => {
457
+ const E = f.docsByLocalValue.get(y) || [], g = O.get(y) || [], C = N.justOne ? g[0] || null : g;
458
+ E.forEach((P) => {
459
+ const Q = u[P];
460
+ Q[D] = C;
469
461
  });
470
462
  });
471
463
  }
472
464
  }
473
- }))), c;
465
+ }))), u;
474
466
  });
475
467
  }
476
- class Me {
468
+ class xe {
477
469
  /**
478
470
  * Creates a new MongoDB controller instance.
479
471
  *
@@ -493,7 +485,7 @@ class Me {
493
485
  createOne(t) {
494
486
  return l(this, null, function* () {
495
487
  try {
496
- const e = S(S({}, x.createGenericFields()), t);
488
+ const e = S(S({}, w.createGenericFields()), t);
497
489
  return (yield this.collection.insertOne(e)).acknowledged ? {
498
490
  success: !0,
499
491
  message: "Document created successfully",
@@ -518,7 +510,7 @@ class Me {
518
510
  createMany(t) {
519
511
  return l(this, null, function* () {
520
512
  try {
521
- const e = t.map((s) => S(S({}, x.createGenericFields()), s)), r = yield this.collection.insertMany(e);
513
+ const e = t.map((s) => S(S({}, w.createGenericFields()), s)), r = yield this.collection.insertMany(e);
522
514
  return r.insertedCount === 0 ? {
523
515
  success: !1,
524
516
  message: "No documents were inserted",
@@ -727,7 +719,7 @@ class we {
727
719
  return l(this, null, function* () {
728
720
  const r = this.getDynamicVirtuals();
729
721
  if (r && r.length > 0) {
730
- const s = yield z(this.model.base, [t], r, e);
722
+ const s = yield B(this.model.base, [t], r, e);
731
723
  return s && s[0] ? s[0] : t;
732
724
  }
733
725
  return t;
@@ -743,7 +735,7 @@ class we {
743
735
  populateDynamicVirtualsForDocuments(t, e) {
744
736
  return l(this, null, function* () {
745
737
  const r = this.getDynamicVirtuals();
746
- return r && r.length > 0 && t.length > 0 ? yield z(this.model.base, t, r, e) : t;
738
+ return r && r.length > 0 && t.length > 0 ? yield B(this.model.base, t, r, e) : t;
747
739
  });
748
740
  }
749
741
  /**
@@ -759,16 +751,16 @@ class we {
759
751
  findOne() {
760
752
  return l(this, arguments, function* (t = {}, e = {}, r = {}, s) {
761
753
  try {
762
- const u = b(t), c = this.model.findOne(u, e, r), i = this.getDynamicVirtuals(), o = j(s, i);
763
- o && c.populate(o);
764
- const a = yield c.exec();
754
+ const c = x(t), u = this.model.findOne(c, e, r), o = this.getDynamicVirtuals(), i = I(s, o);
755
+ i && u.populate(i);
756
+ const a = yield u.exec().then((h) => h instanceof b ? h.toObject() : h);
765
757
  return a ? { success: !0, result: yield this.populateDynamicVirtualsForDocument(a, s) } : {
766
758
  success: !1,
767
759
  message: `No ${this.getModelName()} found.`,
768
760
  code: R.NOT_FOUND.CODE
769
761
  };
770
- } catch (u) {
771
- return d(u);
762
+ } catch (c) {
763
+ return d(c);
772
764
  }
773
765
  });
774
766
  }
@@ -785,12 +777,12 @@ class we {
785
777
  findAll() {
786
778
  return l(this, arguments, function* (t = {}, e = {}, r = {}, s) {
787
779
  try {
788
- const u = b(t), c = this.model.find(u, e, r), i = this.getDynamicVirtuals(), o = j(s, i);
789
- o && c.populate(o);
790
- const a = yield c.exec();
780
+ const c = x(t), u = this.model.find(c, e, r), o = this.getDynamicVirtuals(), i = I(s, o);
781
+ i && u.populate(i);
782
+ const a = yield u.exec().then((h) => h == null ? void 0 : h.map((m) => m instanceof b ? m.toObject() : m));
791
783
  return { success: !0, result: yield this.populateDynamicVirtualsForDocuments(a, s) };
792
- } catch (u) {
793
- return d(u);
784
+ } catch (c) {
785
+ return d(c);
794
786
  }
795
787
  });
796
788
  }
@@ -805,10 +797,10 @@ class we {
805
797
  findPaging() {
806
798
  return l(this, arguments, function* (t = {}, e = {}) {
807
799
  try {
808
- const r = b(t), s = this.getDynamicVirtuals(), u = S({}, e);
809
- e.populate && (u.populate = j(e.populate, s));
810
- const c = yield this.model.paginate(r, u), i = yield this.populateDynamicVirtualsForDocuments(c.docs, e.populate);
811
- return { success: !0, result: F(S({}, c), { docs: i }) };
800
+ const r = x(t), s = this.getDynamicVirtuals(), c = S({}, e);
801
+ e.populate && (c.populate = I(e.populate, s));
802
+ const u = yield this.model.paginate(r, c), o = yield this.populateDynamicVirtualsForDocuments(u.docs.map((i) => i instanceof b ? i.toObject() : i), e.populate);
803
+ return { success: !0, result: j(S({}, u), { docs: o }) };
812
804
  } catch (r) {
813
805
  return d(r);
814
806
  }
@@ -824,13 +816,13 @@ class we {
824
816
  findPagingAggregate(t) {
825
817
  return l(this, arguments, function* (e, r = {}) {
826
818
  try {
827
- const s = this.getDynamicVirtuals(), u = S({}, r);
828
- r.populate && (u.populate = j(r.populate, s));
829
- const c = yield this.model.aggregatePaginate(
819
+ const s = this.getDynamicVirtuals(), c = S({}, r);
820
+ r.populate && (c.populate = I(r.populate, s));
821
+ const u = yield this.model.aggregatePaginate(
830
822
  this.model.aggregate(e),
831
- u
832
- ), i = yield this.populateDynamicVirtualsForDocuments(c.docs, r.populate);
833
- return { success: !0, result: F(S({}, c), { docs: i }) };
823
+ c
824
+ ), o = yield this.populateDynamicVirtualsForDocuments(u.docs.map((i) => i instanceof b ? i.toObject() : i), r.populate);
825
+ return { success: !0, result: j(S({}, u), { docs: o }) };
834
826
  } catch (s) {
835
827
  return d(s);
836
828
  }
@@ -845,7 +837,7 @@ class we {
845
837
  count() {
846
838
  return l(this, arguments, function* (t = {}) {
847
839
  try {
848
- const e = b(t);
840
+ const e = x(t);
849
841
  return { success: !0, result: yield this.model.countDocuments(e) };
850
842
  } catch (e) {
851
843
  return d(e);
@@ -861,7 +853,7 @@ class we {
861
853
  createOne(t) {
862
854
  return l(this, null, function* () {
863
855
  try {
864
- return { success: !0, result: yield this.model.create(t) };
856
+ return { success: !0, result: yield this.model.create(t).then((r) => r instanceof b ? r.toObject() : r) };
865
857
  } catch (e) {
866
858
  return d(e);
867
859
  }
@@ -877,7 +869,7 @@ class we {
877
869
  createMany(t) {
878
870
  return l(this, arguments, function* (e, r = {}) {
879
871
  try {
880
- return { success: !0, result: (yield this.model.insertMany(e, r)).map((c) => c instanceof W ? c.toObject() : null).filter((c) => c !== null) };
872
+ return { success: !0, result: yield this.model.insertMany(e, r).then((c) => c.map((u) => u instanceof b ? u.toObject() : u)) };
881
873
  } catch (s) {
882
874
  return d(s);
883
875
  }
@@ -894,10 +886,10 @@ class we {
894
886
  updateOne() {
895
887
  return l(this, arguments, function* (t = {}, e = {}, r = {}) {
896
888
  try {
897
- const s = b(t), u = yield this.model.findOneAndUpdate(s, e, S({
889
+ const s = x(t), c = yield this.model.findOneAndUpdate(s, e, S({
898
890
  new: !0
899
- }, r)).exec();
900
- return u ? { success: !0, result: u } : {
891
+ }, r)).exec().then((u) => u instanceof b ? u.toObject() : u);
892
+ return c ? { success: !0, result: c } : {
901
893
  success: !1,
902
894
  message: `Failed to update ${this.getModelName()}.`,
903
895
  code: R.NOT_FOUND.CODE
@@ -918,7 +910,7 @@ class we {
918
910
  updateMany() {
919
911
  return l(this, arguments, function* (t = {}, e = {}, r = {}) {
920
912
  try {
921
- const s = b(t);
913
+ const s = x(t);
922
914
  return { success: !0, result: yield this.model.updateMany(s, e, r).exec() };
923
915
  } catch (s) {
924
916
  return d(s);
@@ -935,7 +927,7 @@ class we {
935
927
  deleteOne() {
936
928
  return l(this, arguments, function* (t = {}, e = {}) {
937
929
  try {
938
- const r = b(t), s = yield this.model.findOneAndDelete(r, e).exec();
930
+ const r = x(t), s = yield this.model.findOneAndDelete(r, e).exec().then((c) => c instanceof b ? c.toObject() : c);
939
931
  return s ? { success: !0, result: s } : {
940
932
  success: !1,
941
933
  message: `No ${this.getModelName()} found to delete.`,
@@ -956,7 +948,7 @@ class we {
956
948
  deleteMany() {
957
949
  return l(this, arguments, function* (t = {}, e = {}) {
958
950
  try {
959
- const r = b(t), s = yield this.model.deleteMany(r, e).exec();
951
+ const r = x(t), s = yield this.model.deleteMany(r, e).exec();
960
952
  return s.deletedCount === 0 ? {
961
953
  success: !1,
962
954
  message: "No documents found to delete.",
@@ -978,13 +970,13 @@ class we {
978
970
  createShortId(t, e = 4) {
979
971
  return l(this, null, function* () {
980
972
  try {
981
- const s = Array.from({ length: 10 }, (i, o) => ne(t, o + e)), c = (yield Promise.all(
982
- s.map((i) => this.model.exists({ shortId: i }))
983
- )).findIndex((i) => !i);
984
- if (c !== -1) {
985
- const i = s[c];
986
- if (i)
987
- return { success: !0, result: i };
973
+ const s = Array.from({ length: 10 }, (o, i) => ne(t, i + e)), u = (yield Promise.all(
974
+ s.map((o) => this.model.exists({ shortId: o }))
975
+ )).findIndex((o) => !o);
976
+ if (u !== -1) {
977
+ const o = s[u];
978
+ if (o)
979
+ return { success: !0, result: o };
988
980
  }
989
981
  return {
990
982
  success: !1,
@@ -1004,17 +996,18 @@ class we {
1004
996
  * @param options.slug - The slug string to check for existence.
1005
997
  * @param options.field - The field name for object-based slug checking.
1006
998
  * @param options.isObject - Whether the slug is stored as an object with nested fields.
999
+ * @param options.haveHistory - Whether to check historical slug fields for existence.
1007
1000
  * @param options.filter - Additional filter conditions to apply to the query.
1008
1001
  * @returns A MongoDB query object for checking slug existence.
1009
1002
  */
1010
- createSlugQuery({ slug: t, field: e, isObject: r, haveHistory: s = !1, filter: u }) {
1011
- const c = S({}, u != null ? u : {});
1012
- return r ? F(S({}, c), {
1003
+ createSlugQuery({ slug: t, field: e, isObject: r, haveHistory: s = !1, filter: c }) {
1004
+ const u = S({}, c != null ? c : {});
1005
+ return r ? j(S({}, u), {
1013
1006
  $or: [
1014
1007
  { [`slug.${e}`]: t },
1015
1008
  ...s ? [{ slugHistory: { $elemMatch: { [`slug.${e}`]: t } } }] : []
1016
1009
  ]
1017
- }) : F(S({}, c), {
1010
+ }) : j(S({}, u), {
1018
1011
  $or: [
1019
1012
  { slug: t },
1020
1013
  ...s ? [{ slugHistory: t }] : []
@@ -1029,27 +1022,28 @@ class we {
1029
1022
  * @param options.slug - The base slug string to make unique.
1030
1023
  * @param options.field - The field name for object-based slug checking.
1031
1024
  * @param options.isObject - Whether the slug is stored as an object with nested fields.
1025
+ * @param options.haveHistory - Whether to check historical slug fields for uniqueness.
1032
1026
  * @param options.filter - Additional filter conditions to apply when checking slug existence.
1033
1027
  * @returns A promise that resolves to a unique slug string.
1034
1028
  */
1035
1029
  createUniqueSlug(t) {
1036
- return l(this, arguments, function* ({ slug: e, field: r, isObject: s, haveHistory: u, filter: c }) {
1030
+ return l(this, arguments, function* ({ slug: e, field: r, isObject: s, haveHistory: c, filter: u }) {
1037
1031
  if (!e || typeof e != "string")
1038
1032
  throw new Error("Invalid slug provided: must be a non-empty string");
1039
- const i = I(e);
1033
+ const o = $(e);
1040
1034
  if (!(yield this.model.exists(
1041
- this.createSlugQuery({ slug: i, field: r, isObject: s, haveHistory: u, filter: c })
1035
+ this.createSlugQuery({ slug: o, field: r, isObject: s, haveHistory: c, filter: u })
1042
1036
  )))
1043
- return i;
1044
- for (let O = 1; O <= X; O++) {
1045
- const m = `${i}-${O}`;
1037
+ return o;
1038
+ for (let h = 1; h <= X; h++) {
1039
+ const m = `${o}-${h}`;
1046
1040
  if (!(yield this.model.exists(
1047
- this.createSlugQuery({ slug: m, field: r, isObject: s, haveHistory: u, filter: c })
1041
+ this.createSlugQuery({ slug: m, field: r, isObject: s, haveHistory: c, filter: u })
1048
1042
  )))
1049
1043
  return m;
1050
1044
  }
1051
1045
  const a = Date.now(), f = Math.random().toString(36).substring(2, 8);
1052
- return `${i}-${a}-${f}`;
1046
+ return `${o}-${a}-${f}`;
1053
1047
  });
1054
1048
  }
1055
1049
  /**
@@ -1059,35 +1053,36 @@ class we {
1059
1053
  * @param options - Configuration for slug creation including field, source document, and filter.
1060
1054
  * @param options.field - The field name to create a slug for.
1061
1055
  * @param options.from - The source document containing the field value.
1056
+ * @param options.haveHistory - Whether to check historical slug fields for uniqueness.
1062
1057
  * @param options.filter - Additional filter conditions to apply when checking slug existence.
1063
1058
  * @returns A promise that resolves to a standardized response with the created slug(s).
1064
1059
  */
1065
1060
  createSlug(t) {
1066
- return l(this, arguments, function* ({ field: e, from: r, filter: s, haveHistory: u }) {
1061
+ return l(this, arguments, function* ({ field: e, from: r, filter: s, haveHistory: c }) {
1067
1062
  try {
1068
- const c = r[e];
1069
- return $(c) ? { success: !0, result: Object.fromEntries(
1063
+ const u = r[e];
1064
+ return G(u) ? { success: !0, result: Object.fromEntries(
1070
1065
  yield Promise.all(
1071
- Object.entries(c).map((f) => l(this, [f], function* ([O, m]) {
1072
- const g = yield this.createUniqueSlug({
1066
+ Object.entries(u).map((f) => l(this, [f], function* ([h, m]) {
1067
+ const p = yield this.createUniqueSlug({
1073
1068
  slug: m,
1074
- field: O,
1069
+ field: h,
1075
1070
  isObject: !0,
1076
- haveHistory: u,
1071
+ haveHistory: c,
1077
1072
  filter: s
1078
1073
  });
1079
- return [O, g];
1074
+ return [h, p];
1080
1075
  }))
1081
1076
  )
1082
1077
  ) } : { success: !0, result: yield this.createUniqueSlug({
1083
- slug: c,
1078
+ slug: u,
1084
1079
  field: e,
1085
1080
  isObject: !1,
1086
- haveHistory: u,
1081
+ haveHistory: c,
1087
1082
  filter: s
1088
1083
  }) };
1089
- } catch (c) {
1090
- return d(c);
1084
+ } catch (u) {
1085
+ return d(u);
1091
1086
  }
1092
1087
  });
1093
1088
  }
@@ -1099,36 +1094,37 @@ class we {
1099
1094
  * @param options.slug - The slug string to check for existence.
1100
1095
  * @param options.field - The field name for object-based slug checking.
1101
1096
  * @param options.from - The source document containing the field value.
1097
+ * @param options.haveHistory - Whether to check historical slug fields for existence.
1102
1098
  * @param options.filter - Additional filter conditions to apply to the query.
1103
1099
  * @returns A promise that resolves to a standardized response indicating whether the slug exists.
1104
1100
  */
1105
1101
  checkSlug(t) {
1106
- return l(this, arguments, function* ({ slug: e, field: r, from: s, filter: u, haveHistory: c }) {
1102
+ return l(this, arguments, function* ({ slug: e, field: r, from: s, filter: c, haveHistory: u }) {
1107
1103
  try {
1108
- const i = s[r];
1109
- if ($(i)) {
1110
- const m = Object.values(i).map((v) => I(v));
1104
+ const o = s[r];
1105
+ if (G(o)) {
1106
+ const m = Object.values(o).map((v) => $(v));
1111
1107
  return (yield Promise.all(
1112
1108
  m.map(
1113
1109
  (v) => this.model.exists(this.createSlugQuery({
1114
1110
  slug: v,
1115
1111
  field: r,
1116
1112
  isObject: !0,
1117
- haveHistory: c,
1118
- filter: u
1113
+ haveHistory: u,
1114
+ filter: c
1119
1115
  }))
1120
1116
  )
1121
1117
  )).some((v) => v) ? { success: !0, result: !0 } : { success: !0, result: !1 };
1122
1118
  }
1123
- const a = I(e);
1119
+ const a = $(e);
1124
1120
  return { success: !0, result: (yield this.model.exists(this.createSlugQuery({
1125
1121
  slug: a,
1126
1122
  field: r,
1127
1123
  isObject: !1,
1128
- filter: u
1124
+ filter: c
1129
1125
  }))) !== null };
1130
- } catch (i) {
1131
- return d(i);
1126
+ } catch (o) {
1127
+ return d(o);
1132
1128
  }
1133
1129
  });
1134
1130
  }
@@ -1159,14 +1155,14 @@ class we {
1159
1155
  return l(this, arguments, function* (e, r = {}, s = {}) {
1160
1156
  try {
1161
1157
  return { success: !0, result: yield this.model.distinct(e, r, s) };
1162
- } catch (u) {
1163
- return d(u);
1158
+ } catch (c) {
1159
+ return d(c);
1164
1160
  }
1165
1161
  });
1166
1162
  }
1167
1163
  }
1168
1164
  export {
1169
- Me as MongoController,
1165
+ xe as MongoController,
1170
1166
  we as MongooseController,
1171
- x as mongo
1167
+ w as mongo
1172
1168
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cyberskill/shared",
3
3
  "type": "module",
4
- "version": "2.10.0",
4
+ "version": "2.11.0",
5
5
  "description": "CyberSkill Shared",
6
6
  "author": "Stephen Cheng",
7
7
  "license": "MIT",