UNPKG

@decaf-ts/for-couchdb

Version:
3 lines (2 loc) 40.3 kB
var e,t;e=this,t=function(e,t,r,o,n,i,a){"use strict";const s=/^_.*$/g,c={SEPARATOR:"__",ID:"_id",REV:"_rev",DELETED:"_deleted",TABLE:"??table",SEQUENCE:"??sequence",DDOC:"ddoc",NATIVE:"__native",INDEX:"index",VIEW:"view"},u={EQUAL:"$eq",DIFFERENT:"$ne",BIGGER:"$gt",BIGGER_EQ:"$gte",SMALLER:"$lt",SMALLER_EQ:"$lte",NOT:"$not",IN:"$in",REGEXP:"$regex"},l={AND:"$and",OR:"$or"};async function d(e,t,r){return e.auth(t,r)}function f(e,t,n,i,a=o.DefaultSeparator){const s={};let l;if(s[c.TABLE]={},s[c.TABLE][u.EQUAL]=t,i){const t={};t[e]=i;const r=(n||[]).map(e=>{const t={};return t[e]=i,t}),o={};o[c.TABLE]=i,l=[t,...r,o]}else l=[e,...n||[],c.TABLE];const d=((e,t,n,i,a=o.DefaultSeparator)=>{const s=[r.PersistenceKeys.INDEX,t,e];return n&&s.push(...n),i&&s.push(i),s.join(a)})(e,t,n,i,a);return{index:{fields:l},ddoc:[d,c.DDOC].join(a),name:d}}function p(e){return e instanceof Date?JSON.stringify(e.toISOString()):e instanceof RegExp?`new RegExp(${JSON.stringify(e.source)}, ${JSON.stringify(e.flags)})`:JSON.stringify(e)}function g(e,t){const{attr1:o,operator:n,comparison:i}=e;if(o instanceof r.Condition){const e=g(o,t);if(n===r.Operator.NOT)return`!(${e})`;const a=g(i,t);return n===r.GroupOperator.AND?`(${e} && ${a})`:n===r.GroupOperator.OR?`(${e} || ${a})`:e}const a=`${t}[${JSON.stringify(o)}]`;switch(n){case r.Operator.EQUAL:return`${a} === ${p(i)}`;case r.Operator.DIFFERENT:return`${a} !== ${p(i)}`;case r.Operator.BIGGER:return`${a} > ${p(i)}`;case r.Operator.BIGGER_EQ:return`${a} >= ${p(i)}`;case r.Operator.SMALLER:return`${a} < ${p(i)}`;case r.Operator.SMALLER_EQ:return`${a} <= ${p(i)}`;case r.Operator.IN:return`(${p(i)}).indexOf(${a}) !== -1`;case r.Operator.REGEXP:return`${i instanceof RegExp?p(i):`new RegExp(${JSON.stringify(i)})`}.test(${a})`;case r.Operator.NOT:return`!(${a} === ${p(i)})`;default:return"true"}}function h(e,t,r){return e?Array.isArray(e)?e:[e]:t?[t,...r||[]]:r||[]}function m(e,t,r,n,i=o.DefaultSeparator){return n.name?n.name:[e,t,r,"view"].join(i).replace(/\s+/g,"_")}function y(e,t,r=o.DefaultSeparator){return[e,t,c.DDOC].join(r)}function A(e,o,n){const i={view:r.Operator.VIEW,groupBy:r.Operator.GROUP_BY,count:r.Operator.COUNT,sum:r.Operator.SUM,max:r.Operator.MAX,min:r.Operator.MIN,distinct:r.Operator.DISTINCT}[o];if(!i)return[];const a=t.Metadata.get(e,i)||{};return Object.entries(a).flatMap(([e,t])=>t&&"object"==typeof t?Object.values(t).map(t=>({...t,kind:o,attribute:t.attribute||e})).filter(e=>!n||e.attribute===n):[])}function b(e,r,o){const n=t.Metadata.get(e,r)||{};return Object.entries(n).flatMap(([e,t])=>t&&"object"==typeof t?Object.values(t).map(t=>{const r=t;return{...r,kind:o,attribute:r.attribute||e}}):[])}function E(e){const t={},o=[[c.VIEW,"view"],[r.Operator.GROUP_BY,"groupBy"],[r.Operator.COUNT,"count"],[r.Operator.SUM,"sum"],[r.Operator.MAX,"max"],[r.Operator.MIN,"min"],[r.Operator.DISTINCT,"distinct"]];return e.forEach(e=>{const i=n.Model.tableName(e);o.flatMap(([t,r])=>b(e,t,r)).forEach(e=>{const o=h(e.key,e.attribute,e.compositions);if(!o.length)return;const n=o[0],a=o.slice(1),s=e.directions||[r.OrderDirection.ASC,r.OrderDirection.DSC],c=f(n,i,a);t[c.name||""]=c,s.forEach(e=>{const r=f(n,i,a,e);t[r.name||""]=r})})}),Object.values(t)}function O(e,t,r,n=o.DefaultSeparator){return[...e.map(e=>e===c.TABLE?"table":e),...r||[],...t?[t]:[],c.INDEX].join(n)}function S(e,t,n=[],i,a=o.DefaultSeparator){return[e,t,...n,...i?[i]:[],r.PersistenceKeys.INDEX].join(a)}function w(e,t){Object.defineProperty(e,r.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:t})}function D(e){const t=Object.getOwnPropertyDescriptor(e,r.PersistenceKeys.METADATA);return t?t.value:void 0}function v(e){Object.getOwnPropertyDescriptor(e,r.PersistenceKeys.METADATA)&&delete e[r.PersistenceKeys.METADATA]}class N extends r.Repository{constructor(e,t,r=!1){super(e,t,r)}assignMetadata(e,t){const r=(e,t)=>{const r=D(t??e);return r&&w(e,r),e};return Array.isArray(e)?e.map((e,o)=>{const n=Array.isArray(t)?t[o]:t;return r(e,n)}):r(e,Array.isArray(t)?t?.[0]:t)}async create(e,...t){const r=await super.create(e,...t);return this.assignMetadata(r),this.assignMetadata(e,r),r}async createAll(e,...t){const r=await super.createAll(e,...t);return this.assignMetadata(r),this.assignMetadata(e,r),r}async read(e,...t){const r=await super.read(e,...t);return this.assignMetadata(r)}async readAll(e,...t){const r=await super.readAll(e,...t);return this.assignMetadata(r)}async update(e,...t){const r=await super.update(e,...t);return this.assignMetadata(r),this.assignMetadata(e,r),r}async updateAll(e,...t){const r=await super.updateAll(e,...t);return this.assignMetadata(r),this.assignMetadata(e,r),r}async delete(e,...t){const r=await super.delete(e,...t);return this.assignMetadata(r)}async deleteAll(e,...t){const r=await super.deleteAll(e,...t);return this.assignMetadata(r)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:i,log:a}=(await this.logCtx(t,o.OperationKeys.UPDATE,!0)).for(this.updatePrefix),s=r.get("ignoreHandlers"),c=r.get("ignoreValidation");a.silly(`handlerSetting: ${s}, validationSetting: ${c}`);const u=e[this.pk];if(!u)throw new o.InternalError("No value for the Id is defined under the property "+this.pk);let l,d;if(r.get("applyUpdateValidation")&&(l=await this.read(u),d=l?D(l):void 0,r.get("mergeForUpdate")&&(e=n.Model.merge(l,e,this.class))),s||await o.enforceDBDecorators(this,r,e,o.OperationKeys.UPDATE,o.OperationKeys.ON,l),!c){const t=r.get("ignoredValidationProperties")||[];a.silly("ignored validation properties: "+t);const n=await Promise.resolve(e.hasErrors(l,...t));if(n)throw new o.ValidationError(n.toString())}return d&&w(e,d),[e,...i,l]}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:i,log:a}=(await this.logCtx(t,o.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),s=r.get("ignoreHandlers"),c=r.get("ignoreValidation");a.silly(`handlerSetting: ${s}, ignoredValidation: ${c}`);const u=e.map(e=>{const t=e[this.pk];if(!t)throw new o.InternalError("missing id on update operation");return t});let l;if(r.get("applyUpdateValidation")&&(l=await this.readAll(u,r),e=e.map((e,t)=>{r.get("mergeForUpdate")&&(e=n.Model.merge(l[t],e,this.class));const o=D(l[t]);return o&&w(e,o),e})),s||await Promise.all(e.map((e,t)=>o.enforceDBDecorators(this,r,e,o.OperationKeys.UPDATE,o.OperationKeys.ON,l?l[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let n;a.silly("ignored validation properties: "+t),n=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(l[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=o.reduceErrorsToPrint(n);if(i)throw new o.ValidationError(i)}return[e,...i,l]}}class x extends o.BaseError{constructor(e){super(x.name,e,404)}}class T extends x{constructor(e,t,r){super(e),this.name="IndexPlanningError",this.suggestion=t,this.query=r}}class M extends r.Paginator{constructor(e,t,r,o){super(e,t,r,o),this._bookmarks=new Map}isValidBookmark(e){return"string"==typeof e&&e.length>0}prepare(e){const t=Object.assign({},e);return t.limit&&(this.limit=t.limit),t.limit=this.size,delete t.skip,t}async page(e=1,i,...a){const{log:s,ctxArgs:c,ctx:u}=this.adapter.logCtx([i,...a],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...c);e=this.validatePage(e??1);const l=Object.assign({},this.statement);if(l.limit=this.size,1===e)this.isValidBookmark(i)?l.bookmark=i:delete l.bookmark;else{const t=i||this._bookmarks.get(e);if(!this.isValidBookmark(t))throw new r.PagingError("Random page access requires a cached CouchDB bookmark. Start at page 1 and page forward, or pass an explicit bookmark.");delete l.skip,l.bookmark=t}delete l.skip;const d=await this.adapter.raw(l,!1,...c),{docs:f,bookmark:p,warning:g}=d;if(g&&s.warn(g),d.execution_stats&&s.debug("Mango execution stats: "+JSON.stringify(d.execution_stats)),!this.clazz)throw new r.PagingError("No statement target defined");const h=n.Model.pk(this.clazz),m=t.Metadata.get(this.clazz,t.Metadata.key(o.DBKeys.ID,h))?.type,y=l.fields&&l.fields.length?f:f.map(e=>this.adapter.revert(e,this.clazz,r.Sequence.parseValue(m,e[h]),void 0,u));return this._bookmark=this.isValidBookmark(p)?p:void 0,this._currentPage=e,this.isValidBookmark(p)&&this._bookmarks.set(e+1,p),this.isValidBookmark(p)&&f.length>=this.size||(this._knownLastPage=e,this._totalPages=e,this._recordCount=(e-1)*this.size+f.length),y}}function C(e){for(const t of[u,l]){const r=Object.keys(t).find(t=>t===e);if(r)return t[r]}throw new r.QueryError("Could not find adapter translation for operator "+e)}const _=new Set(["$or","$in","$regex","$nin","$not","$ne","$nor"]);function B(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function I(e,t){return!(!e||"object"!=typeof e)&&(Array.isArray(e)?e.some(e=>I(e,t)):Object.entries(e).some(([e,r])=>e===t||I(r,t)))}function j(e){if("string"==typeof e)return{field:e};if(Array.isArray(e))return e.length?{field:e[0]+""}:void 0;const[t,o]=Object.entries(e||{})[0]||[];return t?{field:t,direction:((o||r.OrderDirection.ASC)+"").toLowerCase()}:void 0}function $(e){return(e.sort||[]).map(j).filter(Boolean).map(e=>e.field)}function P(e){return(e.sort||[]).map(j).find(Boolean)?.direction}function L(e={}){const t=new Set,r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else if(Array.isArray(e[l.AND]))e[l.AND].forEach(r);else for(const[o,n]of Object.entries(e))o!==l.OR&&o!==l.AND?B(n)?Object.prototype.hasOwnProperty.call(n,u.EQUAL)&&t.add(o):t.add(o):r(n)};return r(e),t}function k(e={}){const t=new Set,r=e=>{if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach(r);else if(Array.isArray(e[l.AND]))e[l.AND].forEach(r);else for(const[o,n]of Object.entries(e))o!==l.OR&&o!==l.AND?B(n)&&(Object.prototype.hasOwnProperty.call(n,u.BIGGER)||Object.prototype.hasOwnProperty.call(n,u.BIGGER_EQ)||Object.prototype.hasOwnProperty.call(n,u.SMALLER)||Object.prototype.hasOwnProperty.call(n,u.SMALLER_EQ))&&t.add(o):r(n)};return r(e),t}function R(e){const t=n.Model.tableName(e),o=[],i=O([c.TABLE]);o.push({name:i,ddoc:i,fields:[c.TABLE],source:"table"});let a=[];try{a=n.Model.defaultQueryAttributes(e)}catch{a=[]}for(const e of a){const n=O([t,e,"defaultQuery"]);o.push({name:n,ddoc:n,fields:[c.TABLE,e],source:"defaultQuery"});for(const n of[r.OrderDirection.ASC,r.OrderDirection.DSC]){const r=O([t,e,"defaultQuery"],n);o.push({name:r,ddoc:r,fields:[c.TABLE,e],direction:n,source:"defaultQuery"})}}const s=n.Model.indexes(e);return Object.entries(s||{}).forEach(([e,n])=>{Object.values(n||{}).forEach(n=>{if(!n||!B(n))return;const i=n,a=i.compositions||[],s=i.directions||[r.OrderDirection.ASC],u=[c.TABLE,e,...a],l=S(t,e,a);o.push({name:l,ddoc:l,fields:u,source:"index"});const d=Array.from(new Set(s.map(e=>(e+"").toLowerCase()))).filter(e=>e===r.OrderDirection.ASC||e===r.OrderDirection.DSC);for(const r of d){const n=S(t,e,a,r);o.push({name:n,ddoc:n,fields:u,direction:r,source:"index"})}})}),o}function V(e,t,r={}){if(t.use_index)return;if(I(t.selector,l.OR)||I(t.selector,"$nor"))return;const o=!1!==r.preserveDefaultQuery,n=R(e),i=L(t.selector),a=k(t.selector),s=$(t),u=P(t);i.add(c.TABLE);const d=n.map(e=>{if(e.direction&&u&&e.direction!==u)return;if(!e.fields.includes(c.TABLE))return;if(e.fields[0]!==c.TABLE)return;const t=e.fields.filter(e=>e!==c.TABLE),n=0===s.length||s.every(e=>t.includes(e)),l=s.some(e=>t.includes(e)),d=0===a.size||Array.from(a).every(e=>t.includes(e)),f=Array.from(a).some(e=>t.includes(e));if(r.requireSortCoverage&&s.length&&!n)return;const p=t.filter(e=>i.has(e)).length,g=t.filter(e=>a.has(e)).length,h=t.filter(e=>s.includes(e)).length;if(!p&&!g&&!h)return;let m=0;return"defaultQuery"===e.source&&o&&(m+=100),"index"===e.source&&(m+=50),m+=30*p,m+=25*g,m+=20*h,n&&s.length&&(m+=20),d&&a.size&&(m+=20),l&&(m+=5),f&&(m+=5),e.direction&&u&&(m+=10),{candidate:e,score:m}}).filter(Boolean);if(!d.length)return;d.sort((e,t)=>t.score!==e.score?t.score-e.score:e.candidate.fields.length-t.candidate.fields.length);const f=d[0].candidate;return{candidate:f,use_index:[f.ddoc,f.name]}}function Q(e,t){const r=n.Model.tableName(e),o=e.name,i=Array.from(L(t.selector)),a=Array.from(k(t.selector)),s=$(t),u=P(t),l=[c.TABLE];for(const e of i)e===c.TABLE||l.includes(e)||l.push(e);for(const e of a)e===c.TABLE||l.includes(e)||l.push(e);for(const e of s)e===c.TABLE||l.includes(e)||l.push(e);return{tableName:r,modelName:o,equalityFields:i,rangeFields:a,sortFields:s,sortDirection:u,requiredFields:l}}function U(e,t){const o=Q(e,t),n=o.requiredFields.filter(e=>e!==c.TABLE);if(!n.length)throw new T("Cannot infer @index declaration for query with no model fields.",{modelName:o.modelName,tableName:o.tableName,attribute:"",compositions:[],directions:[],expectedName:"",expectedDdoc:"",expectedFields:[c.TABLE],decorator:""},t);const i=n[0],a=n.slice(1),s=o.sortDirection||r.OrderDirection.ASC,u=S(o.tableName,i,a,s),l=[{[c.TABLE]:s},{[i]:s},...a.map(e=>({[e]:s}))],d=["@index({",a.length?` compositions: ${JSON.stringify(a)},`:void 0," directions: "+JSON.stringify([s]),"})",i+"!: <type>;"].filter(Boolean).join("\n");return{attribute:i,compositions:a,directions:[s],name:u,ddoc:u,fields:l,decorator:d}}function q(e,t,r,o={}){if(!e||t.use_index)return;if(!1===o.forceNamedIndexes&&!o.requireIndex)return;const n=V(e,t,{preserveDefaultQuery:o.preserveDefaultQuery??!0,requireSortCoverage:o.requireSortCoverage??!1});if(n)return t.use_index=n.use_index,void r?.debug?.(`Attached Mango use_index=${JSON.stringify(n.use_index)} from ${n.candidate.source} metadata`);if(!o.requireIndex)return;const i=U(e,t);throw new T(["No generated CouchDB index can satisfy this Mango query.\n","Model: "+e.name,"Table: "+G(e),"\nTo allow this query, declare the following index on the model attribute:\n",i.decorator,"\nThen regenerate/deploy indexes.\n\nExpected generated index:"," ddoc: "+i.ddoc," name: "+i.name," fields: "+JSON.stringify(i.fields)].join("\n"),{modelName:e.name,tableName:G(e),attribute:i.attribute,compositions:i.compositions,directions:i.directions,expectedName:i.name,expectedDdoc:i.ddoc,expectedFields:i.fields,decorator:i.decorator},t)}function G(e){return n.Model.tableName(e)}function F(e,t,r="selector"){if(e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e,o)=>F(e,t,`${r}[${o}]`));else for(const[o,n]of Object.entries(e))_.has(o)&&t?.warn?.(`Mango query contains scan-prone operator ${o} at ${r}. This may bypass or weaken index usage and can produce slow queries.`),F(n,t,`${r}.${o}`)}function K(e){if(!e)return"\0";const t=Array.from(e);for(let e=t.length-1;e>=0;e-=1){const r=t[e].codePointAt(0);if(void 0!==r&&1114111>r)return t[e]=String.fromCodePoint(r+1),t.slice(0,e+1).join("")}return e+"\0"}class J extends r.Statement{constructor(e,t){super(e,t),this.attributeTypeCache=new Map}toColumnName(e){return e===c.TABLE||e===c.SEQUENCE?e:n.Model.columnName(this.fromSelector,e)}build(){const e=this.log.for(this.build);this.manualAggregation=void 0;const t=this.buildAggregateInfo();if(t){if(!this.shouldUseManualAggregation())return this.createAggregateQuery(t);this.manualAggregation=t}const o={};o[c.TABLE]={},o[c.TABLE]=n.Model.tableName(this.fromSelector);const i={selector:o};if(this.selectSelector&&(i.fields=this.selectSelector.map(e=>this.toColumnName(e))),this.whereCondition){const t=this.parseCondition(r.Condition.and(this.whereCondition,r.Condition.attribute(c.TABLE).eq(i.selector[c.TABLE]))).selector,o=Object.keys(t);if(1===o.length&&-1!==Object.values(l).indexOf(o[0]))switch(o[0]){case l.AND:t[l.AND]=[...Object.values(t[l.AND]).reduce((e,t)=>{const r=Object.keys(t);if(1!==r.length)throw Error("Too many keys in query selector. should be one");const o=r[0];return o===l.AND?e.push(...t[o]):e.push(t),e},[])],i.selector=t;break;case l.OR:{const e={};e[l.AND]=[t,...Object.entries(i.selector).map(([e,t])=>{const r={};return r[e]=t,r})],i.selector=e;break}default:throw Error("This should be impossible")}else Object.entries(t).forEach(([t,r])=>{i.selector[t]&&e.warn(`A ${t} query param is about to be overridden: ${i.selector[t]} by ${r}`),i.selector[t]=r})}if(this.orderBySelectors?.length){i.sort=i.sort||[],i.selector=i.selector||{};for(const[e,t]of this.orderBySelectors){const r=this.toColumnName(e),o={};o[r]=t,i.sort.push(o),i.selector[r]||(i.selector[r]={},i.selector[r][u.BIGGER]=null)}}const a=!!this.manualAggregation;return this.limitSelector?i.limit=this.limitSelector:a||(e.warn("No limit selector defined. Using default couchdb limit of 250"),i.limit=250),this.offsetSelector&&(i.skip=this.offsetSelector),this.attachDefaultQueryIndex(i),(this.overrides?.forceNamedIndexes??!0)&&q(this.fromSelector,i,e,{preserveDefaultQuery:!0,requireSortCoverage:!1,forceNamedIndexes:!0}),F(i.selector,e),i}attachDefaultQueryIndex(e){if(!this.fromSelector||e.use_index)return;const t=n.Model.tableName(this.fromSelector);let r=[];try{r=n.Model.defaultQueryAttributes(this.fromSelector)}catch{r=[]}if(!r.length)return;const o=this.collectStartsWithRangeAttrs(e.selector||{}),i=r.filter(e=>o.has(e));if(!i.length)return;const a=(Array.isArray(e.sort)?e.sort:[]).map(e=>Object.entries(e||{})[0]).find(e=>e&&i.includes(e[0])),s=O([t,a?.[0]||i[0],"defaultQuery"],a?.[1]||void 0);e.use_index=s}collectStartsWithRangeAttrs(e){const t=new Set,r=e=>{e&&"object"==typeof e&&(Array.isArray(e)?e.forEach(e=>r(e)):Object.entries(e).forEach(([e,o])=>{if(e!==l.AND&&e!==l.OR&&o&&"object"==typeof o&&!Array.isArray(o)){const r=Object.prototype.hasOwnProperty.call(o,u.BIGGER_EQ),n=Object.prototype.hasOwnProperty.call(o,u.SMALLER);r&&n&&t.add(e)}r(o)}))};return r(e),t}processRecord(e,i){const a=n.Model.pk(this.fromSelector),s=t.Metadata.get(this.fromSelector,t.Metadata.key(o.DBKeys.ID,a))?.type;if(e[c.ID]){const[,...t]=e[c.ID].split(c.SEPARATOR),o=t.join("_");e[a]=r.Sequence.parseValue(s,o)}return this.adapter.revert(e,this.fromSelector,e[a],void 0,i)}async raw(e,...t){const{ctx:r}=this.logCtx(t,this.raw),o=e?.aggregateInfo;if(e?.aggregate&&o)return this.executeAggregate(o,r);const n=this.scopeToTable(e),i=await this.adapter.raw(n,!0,r);if(this.manualAggregation){const e=i.map(e=>this.processRecord(e,r)),t=this.executeManualAggregation(e,this.manualAggregation,r);return this.manualAggregation=void 0,t}if(!this.selectSelector&&this.groupBySelectors?.length){const e=i.map(e=>this.processRecord(e,r));return this.groupSelectResults(e)}if(!this.selectSelector)return i;const a=e=>this.processRecord(e,r);if(Array.isArray(i)){const e=i.map(a);return await this.applyAfterHandlersToResult(e,r)}const s=a(i);return await this.applyAfterHandlersToResult(s,r)}scopeToTable(e){if(!this.fromSelector)return e;const t=n.Model.tableName(this.fromSelector),r=e&&"object"==typeof e?e:{},o=Object.assign({},r.selector||{});return o[c.TABLE]=t,Object.assign({},r,{selector:o})}buildAggregateInfo(){if(this.fromSelector){if(this.avgSelector){const e=this.avgSelector+"",t=this.createAggregateDescriptor("sum",e);if(!t)throw this.missingDecorator("sum",e);const r=this.createAggregateDescriptor("count",e);if(!r)throw this.missingDecorator("count",e);return{kind:"avg",attribute:e,sumDescriptor:t.descriptor,countDescriptor:r.descriptor}}if(void 0!==this.countDistinctSelector){const e=this.resolveSelectorAttribute(this.countDistinctSelector),t=this.createAggregateDescriptor("distinct",e);if(!t)throw this.missingDecorator("distinct",e);return t.countDistinct=!0,t}if(void 0!==this.countSelector){const e=this.resolveSelectorAttribute(this.countSelector),t=this.createAggregateDescriptor("count",e);if(!t)throw this.missingDecorator("count",e);return t}if(this.maxSelector){const e=this.resolveSelectorAttribute(this.maxSelector),t=this.createAggregateDescriptor("max",e);if(!t)throw this.missingDecorator("max",e);return t}if(this.minSelector){const e=this.resolveSelectorAttribute(this.minSelector),t=this.createAggregateDescriptor("min",e);if(!t)throw this.missingDecorator("min",e);return t}if(this.sumSelector){const e=this.resolveSelectorAttribute(this.sumSelector),t=this.createAggregateDescriptor("sum",e);if(!t)throw this.missingDecorator("sum",e);return t}if(this.distinctSelector){const e=this.resolveSelectorAttribute(this.distinctSelector),t=this.createAggregateDescriptor("distinct",e);if(!t)throw this.missingDecorator("distinct",e);return t}}}createAggregateDescriptor(e,t){if(!this.fromSelector)return;const r=A(this.fromSelector,e,t);if(!r.length)return;const o=r[0],i=n.Model.tableName(this.fromSelector),a=m(i,o.attribute,e,o),s=o.ddoc||y(i,a),c={reduce:void 0!==o.reduce||!o.returnDocs};return"distinct"!==e&&"groupBy"!==e||(c.group=!0),{kind:e,meta:o,descriptor:{ddoc:s,view:a,options:c}}}createAggregateQuery(e){return{selector:{},aggregate:!0,aggregateInfo:e}}shouldUseManualAggregation(){return!!this.whereCondition}async executeAggregate(e,t){if(!this.isViewAggregate(e))return this.handleAverage(e,t);const r=this.getCouchAdapter(),o=e,n=await r.view(o.descriptor.ddoc,o.descriptor.view,o.descriptor.options,t);return this.processViewResponse(e,n)}async handleAverage(e,t){if("avg"!==e.kind)throw new r.QueryError("Average descriptor is not valid");const[o,n]=[e.sumDescriptor,e.countDescriptor],i=this.getCouchAdapter(),[a,s]=await Promise.all([i.view(o.ddoc,o.view,o.options,t),i.view(n.ddoc,n.view,n.options,t)]),c=a.rows?.[0]?.value??0,u=s.rows?.[0]?.value??0;return u?c/u:0}executeManualAggregation(e,t,o){if(!this.fromSelector)throw new r.QueryError("Manual aggregation requires a target model");if("avg"===t.kind)return this.computeAverage(e,t.attribute);if("groupBy"===t.kind)return this.computeGroupBy(e,t.meta.attribute);const n=t.meta.attribute;switch(t.kind){case"count":return t.countDistinct?this.computeDistinctCount(e,n):this.computeCount(e,n);case"distinct":return t.countDistinct?this.computeDistinctCount(e,n):this.computeDistinctValues(e,n);case"sum":return this.computeSum(e,n);case"min":return this.computeMinMax(e,n,"min");case"max":return this.computeMinMax(e,n,"max");default:throw new r.QueryError("Unsupported manual aggregation "+t.kind)}}computeCount(e,t){return t?this.collectValues(e,t).filter(e=>null!=e).length:e.length}computeDistinctCount(e,t){const r=t?this.collectValues(e,t).filter(e=>null!=e):e,o=new Set;return r.forEach(e=>o.add(JSON.stringify(e))),o.size}computeDistinctValues(e,t){if(!t)return[];const r=this.collectValues(e,t),o=new Set,n=[];return r.forEach(e=>{const t=JSON.stringify(e);o.has(t)||(o.add(t),n.push(e))}),n}computeSum(e,t){return t?this.collectValues(e,t).filter(e=>null!=e).reduce((e,r)=>e+this.toNumericValue(r,t,"SUM operation"),0):e.length}computeAverage(e,t){if(!t)return 0;const r=this.collectValues(e,t).filter(e=>null!=e);return r.length?r.reduce((e,r)=>e+this.toNumericValue(r,t,"AVG operation"),0)/r.length:0}computeMinMax(e,t,r){if(!t)return null;const o=this.collectValues(e,t).filter(e=>null!=e);let n=null,i=null;for(const e of o){const t=this.normalizeComparable(e);null!==t&&(null!==i?("min"===r&&i>t||"max"===r&&t>i)&&(i=t,n=e):(i=t,n=e))}return n}computeGroupBy(e,t){const r={},o=this.collectValues(e,t);return e.forEach((e,t)=>{const n=this.groupKey(o[t]);r[n]||(r[n]=[]),r[n].push(e)}),r}groupSelectResults(e){if(!this.groupBySelectors?.length)return{};const t=this.resolveSelectorAttribute(this.groupBySelectors[0]);if(!t)return{};const r={};return e.forEach(e=>{const o=this.groupKey(this.convertValueByAttribute(t,e[t]));r[o]||(r[o]=[]),r[o].push(e)}),r}collectValues(e,t){return e.map(e=>{if(e&&"object"==typeof e)return this.convertValueByAttribute(t,e[t])})}convertValueByAttribute(e,t){if(!this.fromSelector)return t;if("date"===this.getAttributeType(e)){if(t instanceof Date)return t;const e=new Date(t);if(!Number.isNaN(e.getTime()))return e}if("string"==typeof t&&e.toLowerCase().includes("date")){const e=new Date(t);if(!Number.isNaN(e.getTime()))return e}return t}getAttributeType(e){if(!e||!this.fromSelector)return;if(this.attributeTypeCache.has(e))return this.attributeTypeCache.get(e);const r=t.Metadata.type(this.fromSelector,e)??t.Metadata.getPropDesignTypes?.(this.fromSelector,e)?.designType,o=this.normalizeMetaType(r);return this.attributeTypeCache.set(e,o),o}normalizeMetaType(e){if(e)return"string"==typeof e?e.toLowerCase():"function"==typeof e&&e.name?e.name.toLowerCase():void 0}normalizeComparable(e){return"number"==typeof e?e:"bigint"==typeof e?Number(e):e instanceof Date?e.getTime():"string"!=typeof e||isNaN(Number(e))?null:Number(e)}groupKey(e){if(void 0===e)return"undefined";if(null===e)return"null";if("symbol"==typeof e)return e.toString();if("object"==typeof e)try{return JSON.stringify(e)}catch{return e+""}return e+""}toNumericValue(e,t,o){if("number"==typeof e)return e;if("bigint"==typeof e)return Number(e);if(e instanceof Date)return e.getTime();if("string"==typeof e&&!isNaN(Number(e)))return Number(e);throw new r.QueryError(`${o} on "${t}" requires numeric values, but got ${typeof e}`)}convertAggregateValue(e,t){return e?this.convertValueByAttribute(e,t):t}resolveSelectorAttribute(e){if(null!=e)return e+""}missingDecorator(e,t){const o=this.decoratorForKind(e),i=this.fromSelector?n.Model.tableName(this.fromSelector):"<unknown table>",a=t?` on "${t}"`:"";return new r.UnsupportedError(`${o} decorator is required for CouchDB ${e} aggregation${a} on table "${i}".`)}decoratorForKind(e){return{count:"@count",sum:"@sum",min:"@min",max:"@max",distinct:"@distinct",groupBy:"@groupBy",view:"@view",avg:"@avg"}[e]||"@"+e}processViewResponse(e,t){if("avg"===e.kind)throw new r.QueryError("Average results should be handled before processing rows");const o=t.rows||[],n=e,i=n.meta;return n.countDistinct?o.length||0:"distinct"===n.kind||"groupBy"===n.kind?o.map(e=>this.convertAggregateValue(n.meta.attribute,e.key??e.value)):i.returnDocs?o.map(e=>e.value??e.doc??e):o.length?this.convertAggregateValue(n.meta.attribute,o[0].value??o[0].key??null):"count"===n.kind?0:null}isViewAggregate(e){return"avg"!==e.kind}getCouchAdapter(){return this.adapter}parseCondition(e){const{attr1:t,operator:o,comparison:n}=e;if(o===r.Operator.STARTS_WITH){if("string"!=typeof t)throw new r.QueryError("STARTS_WITH requires an attribute name");if("string"!=typeof n)throw new r.QueryError("STARTS_WITH requires a string comparison");const e={start:i=n,end:K(i)};return{selector:{[this.toColumnName(t)]:{[u.BIGGER_EQ]:e.start,[u.SMALLER]:e.end}}}}var i,a;if(o===r.Operator.ENDS_WITH){if("string"!=typeof t)throw new r.QueryError("ENDS_WITH requires an attribute name");if("string"!=typeof n)throw new r.QueryError("ENDS_WITH requires a string comparison");return{selector:{[this.toColumnName(t)]:{[u.REGEXP]:(a=n,a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"$")}}}}if(o===r.Operator.BETWEEN){const e=this.toColumnName(t);if(!Array.isArray(n)||2!==n.length)throw new r.QueryError("BETWEEN operator requires [min, max] comparison");const[o,i]=n,a={};return a[e]={},a[e][C(r.Operator.BIGGER_EQ)]=o,a[e][C(r.Operator.SMALLER_EQ)]=i,{selector:a}}let s={};if(-1===[r.GroupOperator.AND,r.GroupOperator.OR,r.Operator.NOT].indexOf(o)){const e=this.toColumnName(t);s[e]={},s[e][C(o)]=n}else if(o===r.Operator.NOT)s=this.parseCondition(t).selector,s[C(r.Operator.NOT)]={},s[C(r.Operator.NOT)][this.toColumnName(t.attr1)]=n;else{const e=this.parseCondition(t).selector,r=this.parseCondition(n).selector;s=((e,t,r)=>{const o={selector:{}};return o.selector[e]=[t,r],o})(C(o),e,r).selector}return{selector:s}}}class z extends r.Adapter{constructor(e,t,r){super(e,t,r),[this.create,this.createAll,this.update,this.updateAll].forEach(e=>{const t=e.name;o.prefixMethod(this,e,this[t+"Prefix"])})}Statement(e){return new J(this,e)}Paginator(e,t,r){return new M(this,e,t,r)}async initialize(){const e=r.Adapter.models(this.flavour);return this.index(...e)}repository(){return N}assignMetadata(e,t){return t?(w(e,t),e):e}assignMultipleMetadata(e,t){return e.forEach((e,r)=>(w(e,t[r]),e)),e}prepare(e,...t){const{log:i}=this.logCtx(t,this.prepare),a=e.segregate(),s=Object.entries(a.model).reduce((t,[r,i])=>{if(void 0===i)return t;const a=n.Model.columnName(e.constructor,r);if(this.isReserved(a))throw new o.InternalError(`Property name ${a} is reserved`);return i=i instanceof Date?new Date(i):i,t[a]=i,t},{});return e[r.PersistenceKeys.METADATA]&&(i.silly("Passing along persistence metadata for "+e[r.PersistenceKeys.METADATA]),Object.defineProperty(s,r.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:e[r.PersistenceKeys.METADATA]})),{record:s,id:e[n.Model.pk(e.constructor)],transient:a.transient}}createPrefix(e,t,r,...o){const{ctxArgs:i}=this.logCtx(o,this.createPrefix),a=n.Model.tableName(e),s={};return Object.assign(s,r),s[c.TABLE]=a,s[c.ID]=this.generateId(a,t),[e,t,s,...i]}createAllPrefix(e,t,r,...i){const a=n.Model.tableName(e);if(t.length!==r.length)throw new o.InternalError("Ids and models must have the same length");const{ctxArgs:s}=this.logCtx(i,this.createAllPrefix),u=t.map((e,t)=>{const o={};return Object.assign(o,r[t]),o[c.TABLE]=a,o[c.ID]=this.generateId(a,e),o});return[e,t,u,...s]}updatePrefix(e,t,i,...a){const s=n.Model.tableName(e),{ctxArgs:u}=this.logCtx(a,this.updatePrefix),l={},d=i[r.PersistenceKeys.METADATA];if(!d)throw new o.InternalError("No revision number found for record with id "+t);return Object.assign(l,i),l[c.TABLE]=s,l[c.ID]=this.generateId(s,t),l[c.REV]=d,[e,t,l,...u]}updateAllPrefix(e,t,i,...a){const s=n.Model.tableName(e);if(t.length!==i.length)throw new o.InternalError("Ids and models must have the same length");const{ctxArgs:u}=this.logCtx(a,this.updateAllPrefix),l=t.map((e,t)=>{const n={},a=i[t][r.PersistenceKeys.METADATA];if(!a)throw new o.InternalError("No revision number found for record with id "+e);return Object.assign(n,i[t]),n[c.TABLE]=s,n[c.ID]=this.generateId(s,e),n[c.REV]=a,n});return[e,t,l,...u]}generateId(e,t){const r=c.SEPARATOR;return"string"==typeof t&&t.startsWith(`${e}${r}`)&&t.split(r).length>=2?t:`${e}${r}${t+""}`}parseError(e,t){return z.parseError(e,t)}isReserved(e){return!!e.match(s)||e===c.TABLE||e===c.SEQUENCE}static parseError(e,t){if(e instanceof o.BaseError)return e;let n="";if("string"==typeof e){if(n=e,n.match(/already exist|update conflict/g))return new o.ConflictError(n);if(n.match(/missing|deleted/g))return new o.NotFoundError(n)}else e.code?(n=e.code,t=t||e.message):e.statusCode?(n=e.statusCode,t=t||e.message):n=e.message;switch(n.toString()){case"401":case"412":case"409":return new o.ConflictError(t);case"404":return new o.NotFoundError(t);case"400":return n.toString().match(/No\sindex\sexists/g)?new x(e):new o.InternalError(e);default:return n.toString().match(/ECONNREFUSED/g)?new r.ConnectionError(e):new o.InternalError(e)}}static setMetadata(e,t){w(e,t)}static getMetadata(e){return D(e)}static removeMetadata(e){v(e)}}i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Object]),i.__metadata("design:returntype",J)],z.prototype,"Statement",null),i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Object,String]),i.__metadata("design:returntype",Object)],z.prototype,"assignMetadata",null),i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Array,Array]),i.__metadata("design:returntype",Array)],z.prototype,"assignMultipleMetadata",null),i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Object,Object,Object,Object]),i.__metadata("design:returntype",Array)],z.prototype,"createPrefix",null),i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Object,Array,Array,Object]),i.__metadata("design:returntype",void 0)],z.prototype,"createAllPrefix",null),i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Object,Object,Object,Object]),i.__metadata("design:returntype",void 0)],z.prototype,"updatePrefix",null),i.__decorate([a.final(),i.__metadata("design:type",Function),i.__metadata("design:paramtypes",[Object,Array,Array,Object]),i.__metadata("design:returntype",void 0)],z.prototype,"updateAllPrefix",null);const W="##VERSION##",X="##PACKAGE##";t.Metadata.registerLibrary(X,W),e.COMMIT="80b9ad6",e.CouchDBAdapter=z,e.CouchDBConst={NULL:"null"},e.CouchDBGroupOperator=l,e.CouchDBKeys=c,e.CouchDBOperator=u,e.CouchDBPaginator=M,e.CouchDBQueryLimit=250,e.CouchDBRepository=N,e.CouchDBStatement=J,e.FULL_VERSION="0.14.4-80b9ad6",e.IndexError=x,e.IndexPlanningError=T,e.PACKAGE_NAME=X,e.VERSION=W,e.attachGeneratedUseIndex=q,e.buildGeneratedIndexCandidates=e=>R(e),e.collectViewMetadata=b,e.count=(e,o)=>{let n={};return e instanceof r.Condition?n.condition=e:"object"==typeof e&&e?n=e:void 0!==e&&(n.value=e),o&&(n=Object.assign({},n,o)),t.Decoration.for(r.Operator.COUNT).define({decorator:e=>r.applyViewDecorator(r.Operator.COUNT,"count",e),args:[n]}).apply()},e.distinct=(e,o)=>{let n={};return e instanceof r.Condition?n.condition=e:e&&(n=e),o&&(n=Object.assign({},n,o)),t.Decoration.for(r.Operator.DISTINCT).define({decorator:e=>r.applyViewDecorator(r.Operator.DISTINCT,"distinct",e),args:[n]}).apply()},e.enableMangoExecutionStats=e=>{e.execution_stats=!0},e.ensureDeterministicSort=(e,t,o)=>{if(!e.sort?.length)return;if($(e).includes(t))return;const n=o||P(e)||r.OrderDirection.ASC;e.sort=[...e.sort,{[t]:n}]},e.findGeneratedIndexCandidateByName=(e,t)=>R(e).find(e=>e.name===t||e.ddoc===t),e.findViewMetadata=A,e.generateDesignDocName=y,e.generateIndexDoc=f,e.generateIndexName=O,e.generateIndexes=e=>{const t=O([c.TABLE]),o={};return o[t]={index:{fields:[c.TABLE]},name:t,ddoc:t,type:"json"},e.forEach(e=>{const t=n.Model.tableName(e);let i=[];try{i=n.Model.defaultQueryAttributes(e)}catch(e){i=[]}i.forEach(e=>{const n=O([t,e,"defaultQuery"]),i={[c.TABLE]:{[u.EQUAL]:t}};o[n]={index:{fields:[c.TABLE,e]},name:n,ddoc:n,type:"json"},o[n].index.partial_filter_selector=i,[r.OrderDirection.ASC,r.OrderDirection.DSC].forEach(r=>{const n=O([t,e,"defaultQuery"],r);o[n]={index:{fields:[{[c.TABLE]:r},{[e]:r}]},name:n,ddoc:n,type:"json"}})});const a=n.Model.indexes(e);Object.entries(a).forEach(([e,n])=>{const i=[];Object.entries(n||{}).forEach(([,t])=>{if(!t)return;const r=t;void 0===r.directions&&void 0===r.compositions?"object"!=typeof t||Array.isArray(t)||Object.entries(t).forEach(([e,t])=>{t&&i.push([e,t])}):i.push([e,r])}),i.forEach(([e,n])=>{if(!n)return;let{directions:i,compositions:a}=n;a=a||[];const s=[e,...a],l={[c.TABLE]:{[u.EQUAL]:t}};function d(r,n){const i=S(t,e,a,n),u=[c.TABLE,...s],d=r?[{[c.TABLE]:r},...s.map(e=>({[e]:r}))]:u;o[i]={index:{fields:d},name:i,ddoc:i,type:"json"},r||(o[i].index.partial_filter_selector=l)}d(),Array.from(new Set((i||[r.OrderDirection.ASC]).map(e=>(e+"").toLowerCase()))).filter(e=>e===r.OrderDirection.ASC||e===r.OrderDirection.DSC).forEach(e=>{d(e,e)})})})}),E(e).forEach(e=>{e.name&&(o[e.name]=e)}),Object.values(o)},e.generateModelIndexName=S,e.generateViewIndexes=E,e.generateViewName=m,e.generateViews=e=>{const t={},o=[[c.VIEW,"view"],[r.Operator.GROUP_BY,"groupBy"],[r.Operator.COUNT,"count"],[r.Operator.SUM,"sum"],[r.Operator.MAX,"max"],[r.Operator.MIN,"min"],[r.Operator.DISTINCT,"distinct"]];return e.forEach(e=>{const i=n.Model.tableName(e);o.flatMap(([t,r])=>b(e,t,r)).forEach(e=>{const o=e.attribute,n=m(i,o,e.kind,e),a="_design/"+(e.ddoc||y(i,n)),s=((e,t,o,n)=>{const i=((e,t,o)=>{if(o.map)return"function"==typeof o.map?o.map.toString():o.map;const n=[];if(n.push(`doc[${JSON.stringify(c.TABLE)}] === ${JSON.stringify(e)}`),o.condition)if(o.condition instanceof r.Condition)n.push(g(o.condition,"doc"));else if("string"==typeof o.condition)n.push(o.condition);else{const e=r.Condition.from(o.condition);n.push(g(e,"doc"))}"count"===o.kind&&void 0!==o.value&&n.push(`doc[${JSON.stringify(t)}] === ${p(o.value)}`);const i=((e,t="doc")=>{if(!e)return;if("string"==typeof e)return e;const r=e.field||"roles",o=e.roles||[];if(!o.length)return e.expression;const n=`${t}[${JSON.stringify(r)}] || []`;return"all"===(e.mode||"any")?o.map(e=>`${n}.indexOf(${JSON.stringify(e)}) !== -1`).join(" && "):o.map(e=>`${n}.indexOf(${JSON.stringify(e)}) !== -1`).join(" || ")})(o.auth,"doc");i&&n.push(i);const a=n.length?n.join(" && "):"true",s=((e,t,r)=>{const o=h(e,t,r);return 1===o.length?`doc[${JSON.stringify(o[0])}]`:`[${o.map(e=>`doc[${JSON.stringify(e)}]`).join(", ")}]`})(o.key,t,o.compositions),u=((e,t)=>"doc"===e?"doc":e?Array.isArray(e)?`[${e.map(e=>`doc[${JSON.stringify(e)}]`).join(", ")}]`:"string"==typeof e?`doc[${JSON.stringify(e)}]`:p(e):`doc[${JSON.stringify(t)}]`)(o.value??(o.returnDocs&&"sum"!==o.kind?"doc":void 0),t);return`function (doc) {\n if (!(${a})) return;\n emit(${s}, ${u});\n}`})(n,t,o),a=o.reduce?"function"==typeof o.reduce?o.reduce.toString():o.reduce:(e=>{switch(e){case"count":case"groupBy":case"distinct":return"_count";case"sum":return"_sum";case"max":return"function (keys, values, rereduce) {\n var maxVal = null;\n for (var i = 0; i < values.length; i++) {\n var val = values[i];\n if (rereduce && val && typeof val === 'object' && 'value' in val) val = val.value;\n if (maxVal === null || val > maxVal) maxVal = val;\n }\n return maxVal;\n}";case"min":return"function (keys, values, rereduce) {\n var minVal = null;\n for (var i = 0; i < values.length; i++) {\n var val = values[i];\n if (rereduce && val && typeof val === 'object' && 'value' in val) val = val.value;\n if (minVal === null || val < minVal) minVal = val;\n }\n return minVal;\n}";default:return}})(e);return{map:i,reduce:a}})(e.kind,o,e,i);t[a]||(t[a]={_id:a,language:"javascript",views:{}}),t[a].views[n]=s})}),Object.values(t)},e.getEqualitySelectorFields=L,e.getMetadata=D,e.getRangeSelectorFields=k,e.getRequiredMangoIndexShape=Q,e.getSortDirection=P,e.getSortFields=$,e.groupBy=(e,o)=>{let n={};return Array.isArray(e)?n.compositions=e:"string"==typeof e?n.name=e:e&&(n=e),"string"==typeof o?n.name=o:o&&(n=Object.assign({},n,o)),void 0===n.returnDocs&&(n.returnDocs=!0),t.Decoration.for(r.Operator.GROUP_BY).define({decorator:e=>r.applyViewDecorator(r.Operator.GROUP_BY,"groupBy",e),args:[n]}).apply()},e.max=(e,o)=>{let n={};return e instanceof r.Condition?n.condition=e:e&&(n=e),o&&(n=Object.assign({},n,o)),t.Decoration.for(r.Operator.MAX).define({decorator:e=>r.applyViewDecorator(r.Operator.MAX,"max",e),args:[n]}).apply()},e.min=(e,o)=>{let n={};return e instanceof r.Condition?n.condition=e:e&&(n=e),o&&(n=Object.assign({},n,o)),t.Decoration.for(r.Operator.MIN).define({decorator:e=>r.applyViewDecorator(r.Operator.MIN,"min",e),args:[n]}).apply()},e.normalizeSortField=j,e.reAuth=d,e.removeMetadata=v,e.requireGeneratedUseIndex=(e,t,r,o={})=>{q(e,t,r,{preserveDefaultQuery:!0,requireSortCoverage:o.requireSortCoverage??!0,requireIndex:!0,forceNamedIndexes:!0})},e.reservedAttributes=s,e.resolveGeneratedIndexForQuery=V,e.reverseRequiredShapeToIndexDeclaration=U,e.setMetadata=w,e.sum=(e,o)=>{let n={};return e instanceof r.Condition?n.condition=e:e&&(n=e),o&&(n=Object.assign({},n,o)),t.Decoration.for(r.Operator.SUM).define({decorator:e=>r.applyViewDecorator(r.Operator.SUM,"sum",e),args:[n]}).apply()},e.testReservedAttributes=e=>e.match(/^_.*$/g),e.translateOperators=C,e.viewIndexDefinition=e=>{const t=h(e.key,e.attribute);return{attribute:t[0],compositions:t.slice(1).concat(e.compositions||[]),directions:e.directions}},e.warnScanProneMangoOperators=F,e.wrapDocumentScope=(e,t,r,o)=>{const n=e.use?e.use(t):e;return["insert","bulk","fetch","createIndex","get","put","destroy","find","view"].forEach(t=>{const i=n[t];"function"==typeof i&&Object.defineProperty(n,t,{enumerable:!1,configurable:!0,value:async(...t)=>(await d(e,r,o),i.call(n,...t))})}),Object.defineProperty(n,c.NATIVE,{enumerable:!1,configurable:!1,writable:!1,value:e}),n}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/core"),require("@decaf-ts/db-decorators"),require("@decaf-ts/decorator-validation"),require("tslib"),require("@decaf-ts/logging")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/core","@decaf-ts/db-decorators","@decaf-ts/decorator-validation","tslib","@decaf-ts/logging"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-couchdb"]={},e.decafTsDecoration,e.decafTsCore,e.decafTsDbDecorators,e.decafTsDecoratorValidation,e.tslib,e.decafTsLogging); //# sourceMappingURL=for-couchdb.cjs.map