couchdb-web-node-plugin 2.0.839 → 2.0.840

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/helper.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { Logger, Mapping, ValueOf } from 'clientnode';
2
- import { AbortControllerStack, ModelRolesMapping, Roles, Configuration, Connection, ConnectorConfiguration, CoreConfiguration, DatabaseConnectorConfiguration, Model, ModelConfiguration, Models, NormalizedRoles, PropertyDefinition, Services, SpecialPropertyNames } from './type';
1
+ import type { Mapping, ValueOf } from 'clientnode';
2
+ import type { AbortControllerStack, ModelRolesMapping, Roles, Configuration, Connection, ConnectorConfiguration, CoreConfiguration, DatabaseConnectorConfiguration, Model, ModelConfiguration, Models, NormalizedRoles, PropertyDefinition, Services, SpecialPropertyNames } from './type';
3
+ import { Logger } from 'clientnode';
3
4
  export declare const TOGGLE_LATEST_REVISION_DETERMINING: unique symbol;
4
5
  export declare const log: Logger;
5
6
  /**
package/helper.js CHANGED
@@ -1 +1,232 @@
1
- (()=>{"use strict";var e=[,e=>{e.exports=require("@babel/runtime/helpers/extends")},e=>{e.exports=require("@babel/runtime/helpers/asyncToGenerator")},e=>{e.exports=require("@babel/runtime/regenerator")},e=>{e.exports=require("clientnode")}],t={};function r(n){var a=t[n];if(void 0!==a)return a.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};r.r(n),r.d(n,{TOGGLE_LATEST_REVISION_DETERMINING:()=>h,applyDefaultPropertyConfigurations:()=>P,applyModelInheritance:()=>D,applyModelsInheritance:()=>_,determineGenericIndexablePropertyNames:()=>T,determineModelRolesMapping:()=>S,ensureValidationDocumentPresence:()=>k,getConnectorOptions:()=>x,getEffectiveURL:()=>j,getPouchDBPlugin:()=>b,initializeConnection:()=>O,isPropertyDefinition:()=>I,log:()=>y,mayStripRepresentation:()=>w,normalizeRoles:()=>E,removeDeprecatedIndexes:()=>g,waitWithTimeout:()=>A});var a=r(1),i=r.n(a),o=r(2),s=r.n(o),c=r(3),u=r.n(c),p=r(4);const l=require("rxjs"),d=require("rxjs/fetch"),f="2.0.839";function m(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return v(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var h=Symbol("toggleLatestRevisionDetermining"),y=new p.Logger({name:"web-node.couchdb"}),b=function(e){var t=e.model.property.name.special,r=t.id,n=t.revision,a=t.attachment,i=t.deleted;return{installCouchDBWebNodePlugin:function(t){var o=this;if(this.bulkDocs){var c=this.bulkDocs.bind(this);this.bulkDocs=s()(u().mark((function a(i){var s,l,d,f,v,b,g,x,w,k,O,j,A,S,I,T,D,P,_,E,R,M,N,C=arguments;return u().wrap((function(a){for(;;)switch(a.prev=a.next){case 0:y.debug("BulkDocs called from:",t),(0,p.isObject)(i)&&1===Object.keys(i).length&&"docs"in i&&Array.isArray(i.docs)&&(i=i.docs);for(s=C.length,l=new Array(s>1?s-1:0),d=1;d<s;d++)l[d-1]=C[d];f=l.length>0&&l[l.length-1]===h,v=f?!e.skipLatestRevisionDetermining:e.skipLatestRevisionDetermining,f&&l.pop(),b=!Array.isArray(i)&&(0,p.isObject)(i)&&r in i?[i]:i,g=e.maximumNumberOfEntitiesInBulkOperation,x=[],w=0;case 1:if(!(w<b.length)){a.next=4;break}return k=b.slice(w,w+g),a.next=2,c.call.apply(c,[o,k].concat(l));case 2:O=a.sent,x=x.concat(O);case 3:w+=g,a.next=1;break;case 4:j=[],A=[],S=0,I=m(x);case 5:if((T=I()).done){a.next=12;break}if(D=T.value,"object"!=typeof b[S]){a.next=10;break}if(!(n in b[S])||"conflict"!==D.name||!["0-latest","0-upsert"].includes(b[S][n])){a.next=6;break}A.push(b[S]),j.push(S),a.next=10;break;case 6:if(!(r in b[S]&&e.ignoreNoChangeError&&"name"in D&&"forbidden"===D.name&&"message"in D&&D.message.startsWith("NoChange:"))){a.next=10;break}if(x[S]={id:b[S][r],ok:!0},v){a.next=10;break}if(!(n in b[S])||["0-latest","0-upsert"].includes(b[S][n])){a.next=7;break}M=b[S][n],a.next=9;break;case 7:return a.next=8,o.get(x[S].id);case 8:N=n,M=a.sent[N];case 9:x[S].rev=M;case 10:S+=1;case 11:a.next=5;break;case 12:if(!A.length){a.next=14;break}return b=A,f&&l.push(h),a.next=13,o.bulkDocs.apply(o,[b].concat(l));case 13:for(P=a.sent,_=m(P);!(E=_()).done;)R=E.value,x[j.shift()]=R;case 14:return a.abrupt("return",x);case 15:case"end":return a.stop()}}),a)})))}this.post=this.put=s()(u().mark((function e(t,r){var n;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,o.bulkDocs([t],r);case 1:if(null==(n=e.sent[0])||!n.name){e.next=2;break}throw n;case 2:return e.abrupt("return",n);case 3:case"end":return e.stop()}}),e)}))),this.remove=s()(u().mark((function e(t,a){var s;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",o.put(((s={})[r]=t,s[n]=a,s[i]=!0,s)));case 1:case"end":return e.stop()}}),e)}))),this.putAttachment&&(this.putAttachment=s()(u().mark((function e(t,i,s,c,p){var l,d,f,m,v,h;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return"string"==typeof s?(v=c,h=s):(v=s,h="0-latest"),e.abrupt("return",o.put(((m={})[r]=t,m[n]=h,m[a]=((f={})[i]={content_type:null!==(l=null!==(d=v.type)&&void 0!==d?d:p)&&void 0!==l?l:"application/octet-stream",data:v},f),m)));case 1:case"end":return e.stop()}}),e)})))),this.removeAttachment&&(this.removeAttachment=s()(u().mark((function e(t,i,s){var c,p;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",o.put(((p={})[r]=t,p[n]=s,p[a]=((c={})[i]={content_type:"application/octet-stream",data:null},c),p)));case 1:case"end":return e.stop()}}),e)}))))}}},g=function(){var e=s()(u().mark((function e(t,r,n){var a,i,o,s,c,p,l,d,f,v,h,y,b;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,t.getIndexes();case 1:a=e.sent.indexes.filter((function(e){return e.name.endsWith("-GenericIndex")})),i=m(a);case 2:if((o=i()).done){e.next=7;break}s=o.value,c=!1,p=0,l=Object.entries(r);case 3:if(!(p<l.length)){e.next=5;break}if(d=l[p],f=d[0],v=d[1],!s.name.startsWith(f+"-")){e.next=4;break}for(h=0,y=T(n,v);h<y.length;h++)b=y[h],[f+"-"+b+"-GenericIndex",f+"-GenericIndex"].includes(s.name)&&(c=!0);return e.abrupt("continue",5);case 4:p++,e.next=3;break;case 5:if(c){e.next=6;break}return e.next=6,t.deleteIndex(s);case 6:e.next=2;break;case 7:case"end":return e.stop()}}),e)})));return function(t,r,n){return e.apply(this,arguments)}}(),x=function(e,t){var r=new Map([[408,"Request Timeout"],[425,"Too Early"],[429,"Too Many Requests"],[502,"Bad Gateway"],[503,"Service Unavailable"],[504,"Gateway Timeout"]]);return i()({},e,{fetch:function(n,a){var i=e.fetchInterceptor,o=i.numberOfRetries,s=i.retryIntervalInSeconds,c=i.exponentialBackoff,u=i.maximumRetryIntervallInSeconds,f=(0,d.fromFetch)(n,function(r){var n;return void 0===r&&(r={}),r=(0,p.extend)(!0,(0,p.copy)(e.fetch),r),Array.isArray(t)&&t.length>0&&(r.signal=null==(n=t.pop())?void 0:n.controller.signal),r}(a)).pipe((0,l.map)((function(e){if(r.has(e.status))throw e;return e})),(0,l.retry)({count:o,delay:function(e,t){if("number"!=typeof e.status)throw e;var r=e;if(r.headers.has("retry-after")){var n=r.headers.get("retry-after");if("string"==typeof n){var a=parseInt(n);if(String(a)===n)return y.info("Retry in "+n+" seconds","according to given retry value."),(0,l.timer)(1e3*a);var i=new Date(n);if(!isNaN(i.getTime())){var o=new Date;if(o<i){if(u<(i.getTime()-o.getTime())/1e3)return y.info("Retry at",i.toUTCString(),"according to given retry","value."),(0,l.timer)(i);y.warn("The recommended retry attempt is",i.toUTCString(),"further in the future than the","configured maximum wait time of",u,"seconds.")}else y.warn("Given retry time recommendation","from server is in the past and","has to be ignored therefore.")}}}var p=c?Math.pow(2,t-1)*s:s;return(0,l.timer)(1e3*Math.min(p,u))}}));return(0,l.lastValueFrom)(f)}})},w=function(e,t,r){var n=(0,p.represent)(e);return n.length<=t?n.length>r?n.substring(0,r-3)+"...":n:"DOCUMENT IS TOO BIG TO REPRESENT"},k=function(){var e=s()(u().mark((function e(t,r,n,a,o,s,c,l){var d,m,v,h,b;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return void 0===o&&(o=!0),void 0===s&&(s="_id"),void 0===c&&(c="_rev"),void 0===l&&(l="_design/"),m=i()(((d={})[s]=""+l+r,d.language="javascript",d.version=f,d),n),e.prev=1,e.next=2,t.get(""+l+r);case 2:return v=e.sent,m[c]=v[c],e.next=3,t.put(m);case 3:o&&y.info(a+" updated."),e.next=8;break;case 4:return e.prev=4,h=e.catch(1),o&&("not_found"===h.error||"not_found"===h.name||"missing"===h.message||"missing"===h.reason?y.info(a+" not available. Create new one."):y.info(a+" couldn't be updated:",'"'+(0,p.represent)(h)+'" create new one.')),e.prev=5,e.next=6,t.put(m);case 6:o&&y.info(a+" installed/updated."),e.next=8;break;case 7:throw e.prev=7,b=e.catch(5),new Error(a+" couldn't be installed/updated: \""+(0,p.represent)(b)+'".',{cause:b});case 8:case"end":return e.stop()}}),e,null,[[1,4],[5,7]])})));return function(t,r,n,a,i,o,s,c){return e.apply(this,arguments)}}(),O=function(){var e=s()(u().mark((function e(t,r,n){var a,i,o,s;return u().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(void 0===n&&(n=!0),a=t.couchdb,i=r.couchdb,o=j(i),t.couchdb.server.expressPouchDBInstance?(a.connection=new a.connector(i.databaseName,a.server.runner.configuration),a.connection.installValidationMethods()):a.connection=new a.connector(o,x(i.connector)),a.connection.installCouchDBWebNodePlugin("backend"),a.connection.setMaxListeners(1/0),!n){e.next=4;break}return e.prev=1,e.next=2,a.connection.allDocs({limit:1});case 2:e.next=4;break;case 3:throw e.prev=3,s=e.catch(1),new Error("Database has not been installed yet: "+(0,p.represent)(s),{cause:s});case 4:return e.abrupt("return",t);case 5:case"end":return e.stop()}}),e,null,[[1,3]])})));return function(t,r,n){return e.apply(this,arguments)}}(),j=function(e,t,r){void 0===t&&(t=!0),void 0===r&&(r=!1);var n=/^https?:\/\//.test(e.url)?e.url:"http://{1}"+e.runner.host+":"+String(e.runner.port);return(0,p.format)(n,r?e.admin.name+":"+e.admin.password+"@":"")+(t?"/"+e.databaseName:"")},A=function(e,t,r){var n=!0;return Promise.race([e.then((function(){n=!1})),(0,p.timeout)(1e3*t).then((function(){n&&y.warn("Timeout of",String(t)+".","seconds reached while waiting for "+r+".")}))])},S=function(e){for(var t=e.property.name.special,r=t.role,n=t.attachment,a={},o=_(e),s=0,c=Object.entries(o);s<c.length;s++){var u=c[s],l=u[0],d=u[1];if(d[r]){a[l]=i()({properties:{}},E(d[r]));for(var f=0,m=Object.entries(d);f<m.length;f++){var v=m[f],h=v[0],y=v[1];if((0,p.isObject)(y))if(h===n){a[l].attachments={};for(var b=0,g=Object.entries(y);b<g.length;b++){var x=g[b],w=x[0],k=x[1];k.roles&&(a[l].attachments[w]=E(k.roles))}}else y.roles&&(a[l].properties[h]=E(y.roles))}}}return a},I=function(e){return(0,p.isObject)(e)},T=function(e,t){var r=e.property.name.special;return Object.keys(t).filter((function(n){var a=t[n];return I(a)&&Object.prototype.hasOwnProperty.call(a,"index")&&a.index||I(a)&&!(Object.prototype.hasOwnProperty.call(a,"index")&&!a.index||e.property.name.reserved.concat(r.additional,r.role,r.attachment,r.conflict,r.constraint.execution,r.constraint.expression,r.deleted,r.deletedConflict,r.extend,r.maximumAggregatedSize,r.minimumAggregatedSize,r.oldType,r.id,r.revision,r.revisions,r.revisionsInformation,r.type,r.updateStrategy).includes(n)||a.type&&("string"==typeof a.type&&a.type.endsWith("[]")||Array.isArray(a.type)&&a.type.length&&Array.isArray(a.type[0])||Object.prototype.hasOwnProperty.call(e.entities,a.type)))})).concat([r.id,r.revision]).sort()},D=function(e,t,r){void 0===r&&(r="in-place");var n=t.entities,a=t.property.name.special.extend;if(Object.prototype.hasOwnProperty.call(n,"_base")&&(Object.prototype.hasOwnProperty.call(e,a)&&e[a]&&![].concat(e[a]).includes("_base")?e[a]=["_base"].concat(e[a]):e[a]="_base"),Object.prototype.hasOwnProperty.call(e,a)){for(var i,o=[].concat(e[a]),s=m(o);!(i=s()).done;){var c=i.value;"_base"!==c&&D(n[c],t,c),(0,p.extend)(!0,e,n[c],(0,p.copy)(e)),e[a]=o}delete e[a]}return P(e,t),e},P=function(e,t){for(var r=t.property.name.special,n=0,a=Object.entries(e);n<a.length;n++){var i=a[n],o=i[0],s=i[1];if(o===r.attachment)for(var c=s,u=0,l=Object.entries(c);u<l.length;u++){var d=l[u],f=d[0],v=d[1];c[f]=(0,p.extend)(!0,(0,p.copy)(t.property.defaultDefinition),v)}else if(![r.role,r.constraint.execution,r.constraint.expression,r.extend,r.maximumAggregatedSize,r.minimumAggregatedSize,r.oldType].includes(o)){var h=(0,p.extend)(!0,(0,p.copy)(t.property.defaultDefinition),s);e[o]=h;for(var y,b=m([].concat(h.type));!(y=b()).done;){var g=y.value;Array.isArray(g)||"object"!=typeof g||(h.type=D(g,t))}}}return e},_=function(e){for(var t=e.entities,r=e.property.name.typePattern,n=0,a=Object.keys(t);n<a.length;n++){var i=a[n];if(!new RegExp(r.public).test(i)&&!new RegExp(r.private).test(i))throw new Error('Model names have to match "'+r.public+'" or "'+r.private+'" for xprivate one (given name: "'+i+'").');"_base"!==i&&D(t[i],e,i)}return t},E=function(e){if(Array.isArray(e))return{read:e,write:e};if("object"==typeof e){for(var t={read:[],write:[]},r=0,n=Object.keys(t);r<n.length;r++){var a=n[r];if(Object.prototype.hasOwnProperty.call(e,a)){var i=e[a];Array.isArray(i)?t[a]=i:"string"==typeof i&&(t[a]=[i])}}return t}return{read:[e],write:[e]}};module.exports=n})();
1
+ if(typeof window==='undefined'||window===null)var window=(typeof globalThis==='undefined'||globalThis===null)?{}:globalThis;import * as __WEBPACK_EXTERNAL_MODULE_clientnode__ from "clientnode";
2
+ import { lastValueFrom as __WEBPACK_EXTERNAL_MODULE_rxjs_lastValueFrom__, map as __WEBPACK_EXTERNAL_MODULE_rxjs_map__, retry as __WEBPACK_EXTERNAL_MODULE_rxjs_retry__, timer as __WEBPACK_EXTERNAL_MODULE_rxjs_timer__ } from "rxjs";
3
+ import { fromFetch as __WEBPACK_EXTERNAL_MODULE_rxjs_fetch_acb1bba5_fromFetch__ } from "rxjs/fetch";
4
+ /******/ var __webpack_modules__ = ({
5
+
6
+ /***/ 0
7
+ (module, __unused_webpack_exports, __webpack_require__) {
8
+
9
+ const x = (y) => {
10
+ const x = {}; __webpack_require__.d(x, y); return x
11
+ }
12
+ const y = (x) => (() => (x))
13
+ module.exports = x({ ["Logger"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.Logger), ["copy"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.copy), ["extend"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.extend), ["format"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.format), ["isObject"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.isObject), ["represent"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.represent), ["timeout"]: () => (__WEBPACK_EXTERNAL_MODULE_clientnode__.timeout) });
14
+
15
+ /***/ },
16
+
17
+ /***/ 5
18
+ (module) {
19
+
20
+ module.exports = {"rE":"2.0.840"};
21
+
22
+ /***/ }
23
+
24
+ /******/ });
25
+ /************************************************************************/
26
+ /******/ // The module cache
27
+ /******/ const __webpack_module_cache__ = {};
28
+ /******/
29
+ /******/ // The require function
30
+ /******/ function __webpack_require__(moduleId) {
31
+ /******/ // Check if module is in cache
32
+ /******/ const cachedModule = __webpack_module_cache__[moduleId];
33
+ /******/ if (cachedModule !== undefined) {
34
+ /******/ return cachedModule.exports;
35
+ /******/ }
36
+ /******/ // Create a new module (and put it into the cache)
37
+ /******/ const module = __webpack_module_cache__[moduleId] = {
38
+ /******/ // no module.id needed
39
+ /******/ // no module.loaded needed
40
+ /******/ exports: {}
41
+ /******/ };
42
+ /******/
43
+ /******/ // Execute the module function
44
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
45
+ /******/
46
+ /******/ // Return the exports of the module
47
+ /******/ return module.exports;
48
+ /******/ }
49
+ /******/
50
+ /************************************************************************/
51
+ /******/ /* webpack/runtime/define property getters */
52
+ /******/ (() => {
53
+ /******/ // define getter/value functions for harmony exports
54
+ /******/ __webpack_require__.d = (exports, definition) => {
55
+ /******/ if(Array.isArray(definition)) {
56
+ /******/ var i = 0;
57
+ /******/ while(i < definition.length) {
58
+ /******/ var key = definition[i++];
59
+ /******/ var binding = definition[i++];
60
+ /******/ if(!__webpack_require__.o(exports, key)) {
61
+ /******/ if(binding === 0) {
62
+ /******/ Object.defineProperty(exports, key, { enumerable: true, value: definition[i++] });
63
+ /******/ } else {
64
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: binding });
65
+ /******/ }
66
+ /******/ } else if(binding === 0) { i++; }
67
+ /******/ }
68
+ /******/ } else {
69
+ /******/ for(var key in definition) {
70
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
71
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
72
+ /******/ }
73
+ /******/ }
74
+ /******/ }
75
+ /******/ };
76
+ /******/ })();
77
+ /******/
78
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
79
+ /******/ (() => {
80
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
81
+ /******/ })();
82
+ /******/
83
+ /************************************************************************/
84
+
85
+ // EXTERNAL MODULE: external "clientnode"
86
+ var external_clientnode_ = __webpack_require__(0);
87
+ ;// external "rxjs"
88
+
89
+ ;// external "rxjs/fetch"
90
+
91
+ // EXTERNAL MODULE: ./package.json
92
+ var package_0 = __webpack_require__(5);
93
+ ;// ./helper.ts
94
+ // -*- coding: utf-8 -*-
95
+ /** @module helper *//* !
96
+ region header
97
+ Copyright Torben Sickert (info["~at~"]torben.website) 16.12.2012
98
+
99
+ License
100
+ -------
101
+
102
+ This library written by Torben Sickert stands under a creative commons
103
+ naming 3.0 unported license.
104
+ See https://creativecommons.org/licenses/by/3.0/deed.de
105
+ endregion
106
+ */// region imports
107
+ function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o)}return t}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function _slicedToArray(r,e){return _arrayWithHoles(r)||_iterableToArrayLimit(r,e)||_unsupportedIterableToArray(r,e)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _iterableToArrayLimit(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}function _arrayWithHoles(r){if(Array.isArray(r))return r}function _defineProperty(e,r,t){return(r=_toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function _toPropertyKey(t){var i=_toPrimitive(t,"string");return"symbol"==_typeof(i)?i:i+""}function _toPrimitive(t,r){if("object"!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||"default");if("object"!=_typeof(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(t)}function _regenerator(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function i(r,n,o,i){var c=n&&n.prototype instanceof Generator?n:Generator,u=Object.create(c.prototype);return _regeneratorDefine2(u,"_invoke",function(r,n,o){var i,c,u,f=0,p=o||[],y=!1,G={p:0,n:0,v:e,a:d,f:d.bind(e,4),d:function d(t,r){return i=t,c=0,u=e,G.n=r,a}};function d(r,n){for(c=r,u=n,t=0;!y&&f&&!o&&t<p.length;t++){var o,i=p[t],d=G.p,l=i[2];r>3?(o=l===n)&&(u=i[(c=i[4])?5:(c=3,3)],i[4]=i[5]=e):i[0]<=d&&((o=r<2&&d<i[1])?(c=0,G.v=n,G.n=i[1]):d<l&&(o=r<3||i[0]>n||n>l)&&(i[4]=r,i[5]=n,G.n=l,c=0))}if(o||r>1)return a;throw y=!0,n}return function(o,p,l){if(f>1)throw TypeError("Generator is already running");for(y&&1===p&&d(p,l),c=p,u=l;(t=c<2?e:u)||!y;){i||(c?c<3?(c>1&&(G.n=-1),d(c,u)):G.n=u:G.v=u);try{if(f=2,i){if(c||(o="next"),t=i[o]){if(!(t=t.call(i,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=i.return)&&t.call(i),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);i=e}else if((t=(y=G.n<0)?u:r.call(n,G))!==a)break}catch(t){i=e,c=1,u=t}finally{f=1}}return{value:t,done:y}}}(r,o,i),!0),u}var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}t=Object.getPrototypeOf;var c=[][n]?t(t([][n]())):(_regeneratorDefine2(t={},n,function(){return this}),t),u=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,_regeneratorDefine2(e,o,"GeneratorFunction")),e.prototype=Object.create(u),e}return GeneratorFunction.prototype=GeneratorFunctionPrototype,_regeneratorDefine2(u,"constructor",GeneratorFunctionPrototype),_regeneratorDefine2(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName="GeneratorFunction",_regeneratorDefine2(GeneratorFunctionPrototype,o,"GeneratorFunction"),_regeneratorDefine2(u),_regeneratorDefine2(u,o,"Generator"),_regeneratorDefine2(u,n,function(){return this}),_regeneratorDefine2(u,"toString",function(){return"[object Generator]"}),(_regenerator=function _regenerator(){return{w:i,m:f}})()}function _regeneratorDefine2(e,r,n,t){var i=Object.defineProperty;try{i({},"",{})}catch(e){i=0}_regeneratorDefine2=function _regeneratorDefine(e,r,n,t){function o(r,n){_regeneratorDefine2(e,r,function(e){return this._invoke(r,n,e)})}r?i?i(e,r,{value:n,enumerable:!t,configurable:!t,writable:!t}):e[r]=n:(o("next",0),o("throw",1),o("return",2))},_regeneratorDefine2(e,r,n,t)}function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]}},e:function e(r){throw r},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,u=!1;return{s:function s(){t=t.call(r)},n:function n(){var r=t.next();return a=r.done,r},e:function e(r){u=!0,o=r},f:function f(){try{a||null==t.return||t.return()}finally{if(u)throw o}}}}function _toConsumableArray(r){return _arrayWithoutHoles(r)||_iterableToArray(r)||_unsupportedIterableToArray(r)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0}}function _iterableToArray(r){if("undefined"!=typeof Symbol&&null!=r[Symbol.iterator]||null!=r["@@iterator"])return Array.from(r)}function _arrayWithoutHoles(r){if(Array.isArray(r))return _arrayLikeToArray(r)}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n}function asyncGeneratorStep(n,t,e,r,o,a,c){try{var i=n[a](c),u=i.value}catch(n){return void e(n)}i.done?t(u):Promise.resolve(u).then(r,o)}function _asyncToGenerator(n){return function(){var t=this,e=arguments;return new Promise(function(r,o){var a=n.apply(t,e);function _next(n){asyncGeneratorStep(a,r,o,_next,_throw,"next",n)}function _throw(n){asyncGeneratorStep(a,r,o,_next,_throw,"throw",n)}_next(void 0)})}};// endregion
108
+ /*
109
+ Token to provide to "bulkDocs" method call to indicate id determination
110
+ skip or not (depends on "skipLatestRevisionDetermining" configuration).
111
+ */var TOGGLE_LATEST_REVISION_DETERMINING=Symbol("toggleLatestRevisionDetermining");var log=new external_clientnode_.Logger({name:"web-node.couchdb"});/**
112
+ * Determines plugin to hook into any write operations.
113
+ * @param configuration - This's plugin configuration object.
114
+ * @returns A pouchdb plugin in object style.
115
+ */var getPouchDBPlugin=function getPouchDBPlugin(configuration){var _configuration$model$=configuration.model.property.name.special,idName=_configuration$model$.id,revisionName=_configuration$model$.revision,attachmentsPropertyName=_configuration$model$.attachment,deletedName=_configuration$model$.deleted;return{installCouchDBWebNodePlugin:function installCouchDBWebNodePlugin(description){var _this=this;if(this.bulkDocs){var nativeBulkDocs=this.bulkDocs.bind(this);this.bulkDocs=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(firstParameter){var _len,parameters,_key,toggleLatestRevisionDetermining,skipLatestRevisionDetermining,data,chunkSize,results,_index,chunk,result,conflictingIndexes,conflicts,index,_iterator,_step,item,retriedResults,_iterator2,_step2,retriedResult,_args=arguments,_t,_t2,_t3;return _regenerator().w(function(_context){while(1)switch(_context.p=_context.n){case 0:log.debug("BulkDocs called from:",description);// Normalize parameter to an array of documents.
116
+ if((0,external_clientnode_.isObject)(firstParameter)&&Object.keys(firstParameter).length===1&&"docs"in firstParameter&&Array.isArray(firstParameter.docs))firstParameter=firstParameter.docs;for(_len=_args.length,parameters=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){parameters[_key-1]=_args[_key]}toggleLatestRevisionDetermining=parameters.length>0&&parameters[parameters.length-1]===TOGGLE_LATEST_REVISION_DETERMINING;skipLatestRevisionDetermining=toggleLatestRevisionDetermining?!configuration.skipLatestRevisionDetermining:configuration.skipLatestRevisionDetermining;if(toggleLatestRevisionDetermining)parameters.pop();data=!Array.isArray(firstParameter)&&(0,external_clientnode_.isObject)(firstParameter)&&idName in firstParameter?[firstParameter]:firstParameter;chunkSize=configuration.maximumNumberOfEntitiesInBulkOperation;results=[];_index=0;case 1:if(!(_index<data.length)){_context.n=4;break}chunk=data.slice(_index,_index+chunkSize);_context.n=2;return nativeBulkDocs.call.apply(nativeBulkDocs,[_this,chunk].concat(_toConsumableArray(parameters)));case 2:result=_context.v;results=results.concat(result);case 3:_index+=chunkSize;_context.n=1;break;case 4:conflictingIndexes=[];conflicts=[];index=0;_iterator=_createForOfIteratorHelper(results);_context.p=5;_iterator.s();case 6:if((_step=_iterator.n()).done){_context.n=13;break}item=_step.value;if(!(_typeof(data[index])==="object")){_context.n=11;break}if(!(revisionName in data[index]&&item.name==="conflict"&&["0-latest","0-upsert"].includes(data[index][revisionName]))){_context.n=7;break}conflicts.push(data[index]);conflictingIndexes.push(index);_context.n=11;break;case 7:if(!(idName in data[index]&&configuration.ignoreNoChangeError&&"name"in item&&item.name==="forbidden"&&"message"in item&&item.message.startsWith("NoChange:"))){_context.n=11;break}results[index]={id:data[index][idName],ok:true};if(skipLatestRevisionDetermining){_context.n=11;break}if(!(revisionName in data[index]&&!["0-latest","0-upsert"].includes(data[index][revisionName]))){_context.n=8;break}_t=data[index][revisionName];_context.n=10;break;case 8:_context.n=9;return _this.get(results[index].id);case 9:_t2=revisionName;_t=_context.v[_t2];case 10:results[index].rev=_t;case 11:index+=1;case 12:_context.n=6;break;case 13:_context.n=15;break;case 14:_context.p=14;_t3=_context.v;_iterator.e(_t3);case 15:_context.p=15;_iterator.f();return _context.f(15);case 16:if(!conflicts.length){_context.n=18;break}data=conflicts;if(toggleLatestRevisionDetermining)parameters.push(TOGGLE_LATEST_REVISION_DETERMINING);_context.n=17;return _this.bulkDocs.apply(_this,[data].concat(_toConsumableArray(parameters)));case 17:retriedResults=_context.v;_iterator2=_createForOfIteratorHelper(retriedResults);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){retriedResult=_step2.value;results[conflictingIndexes.shift()]=retriedResult}}catch(err){_iterator2.e(err)}finally{_iterator2.f()}case 18:return _context.a(2,results)}},_callee,null,[[5,14,15,16]])}))}this.post=this.put=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(document,options){var result;return _regenerator().w(function(_context2){while(1)switch(_context2.n){case 0:_context2.n=1;return _this.bulkDocs([document],options);case 1:result=_context2.v[0];if(!(result!==null&&result!==void 0&&result.name)){_context2.n=2;break}throw result;case 2:return _context2.a(2,result)}},_callee2)}));this.remove=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(id,revision){return _regenerator().w(function(_context3){while(1)switch(_context3.n){case 0:return _context3.a(2,_this.put(_defineProperty(_defineProperty(_defineProperty({},idName,id),revisionName,revision),deletedName,true)))}},_callee3)}));if(this.putAttachment)this.putAttachment=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(id,attachmentName,revisionOrAttachment,attachmentOrType,type){var _ref5,_type;var attachment,revision;return _regenerator().w(function(_context4){while(1)switch(_context4.n){case 0:if(typeof revisionOrAttachment==="string"){attachment=attachmentOrType;revision=revisionOrAttachment}else{attachment=revisionOrAttachment;revision="0-latest"}return _context4.a(2,_this.put(_defineProperty(_defineProperty(_defineProperty({},idName,id),revisionName,revision),attachmentsPropertyName,_defineProperty({},attachmentName,{/*
117
+ NOTE: We only need to set a content type to
118
+ avoid getting a warning.
119
+ */// eslint-disable-next-line camelcase
120
+ content_type:(_ref5=(_type=attachment.type)!==null&&_type!==void 0?_type:type)!==null&&_ref5!==void 0?_ref5:"application/octet-stream",data:attachment}))))}},_callee4)}));if(this.removeAttachment)this.removeAttachment=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(id,attachmentName,revision){return _regenerator().w(function(_context5){while(1)switch(_context5.n){case 0:return _context5.a(2,_this.put(_defineProperty(_defineProperty(_defineProperty({},idName,id),revisionName,revision),attachmentsPropertyName,_defineProperty({},attachmentName,{/*
121
+ NOTE: We only need to set a content type to
122
+ avoid getting a warning.
123
+ */// eslint-disable-next-line camelcase
124
+ content_type:"application/octet-stream",data:null}))))}},_callee5)}))}}};// region utility functions
125
+ var removeDeprecatedIndexes=/*#__PURE__*/function(){var _removeDeprecatedIndexes=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(connection,models,modelConfiguration){var genericIndexes,_iterator3,_step3,index,exists,_i,_Object$entries,_Object$entries$_i,modelName,model,_i2,_determineGenericInde,name,_t4;return _regenerator().w(function(_context6){while(1)switch(_context6.p=_context6.n){case 0:_context6.n=1;return connection.getIndexes();case 1:genericIndexes=_context6.v.indexes.filter(function(index){return index.name.endsWith("-GenericIndex")});_iterator3=_createForOfIteratorHelper(genericIndexes);_context6.p=2;_iterator3.s();case 3:if((_step3=_iterator3.n()).done){_context6.n=8;break}index=_step3.value;exists=false;_i=0,_Object$entries=Object.entries(models);case 4:if(!(_i<_Object$entries.length)){_context6.n=6;break}_Object$entries$_i=_slicedToArray(_Object$entries[_i],2),modelName=_Object$entries$_i[0],model=_Object$entries$_i[1];if(!index.name.startsWith("".concat(modelName,"-"))){_context6.n=5;break}for(_i2=0,_determineGenericInde=determineGenericIndexablePropertyNames(modelConfiguration,model);_i2<_determineGenericInde.length;_i2++){name=_determineGenericInde[_i2];if(["".concat(modelName,"-").concat(name,"-GenericIndex"),"".concat(modelName,"-GenericIndex")].includes(index.name))exists=true}return _context6.a(3,6);case 5:_i++;_context6.n=4;break;case 6:if(exists){_context6.n=7;break}_context6.n=7;return connection.deleteIndex(index);case 7:_context6.n=3;break;case 8:_context6.n=10;break;case 9:_context6.p=9;_t4=_context6.v;_iterator3.e(_t4);case 10:_context6.p=10;_iterator3.f();return _context6.f(10);case 11:return _context6.a(2)}},_callee6,null,[[2,9,10,11]])}));function removeDeprecatedIndexes(_x12,_x13,_x14){return _removeDeprecatedIndexes.apply(this,arguments)}return removeDeprecatedIndexes}();/**
126
+ * Converts internal declarative database connector configuration object
127
+ * into a database compatible one.
128
+ * @param configuration - Connector configuration object.
129
+ * @param abortControllerStack - Stack to put abort signals to. They will be
130
+ * shifted and used for fetch calls.
131
+ * @returns Database compatible configuration object.
132
+ */var getConnectorOptions=function getConnectorOptions(configuration,abortControllerStack){/*
133
+ NOTE: We convert given fetch options into a fetch function wrapper
134
+ which is than accepted by pouchdb's api.
135
+ */var getOptions=function getOptions(options){var _abortControllerStack;if(options===void 0){options={}}options=(0,external_clientnode_.extend)(true,(0,external_clientnode_.copy)(configuration.fetch),options);if(Array.isArray(abortControllerStack)&&abortControllerStack.length>0)options.signal=(_abortControllerStack=abortControllerStack.pop())===null||_abortControllerStack===void 0?void 0:_abortControllerStack.controller.signal;return options};var KNOWN_ERRORS=new Map([[408,"Request Timeout"],[425,"Too Early"],[429,"Too Many Requests"],[502,"Bad Gateway"],[503,"Service Unavailable"],[504,"Gateway Timeout"]]);return _objectSpread(_objectSpread({},configuration),{},{fetch:function fetch(url,options){var _configuration$fetchI=configuration.fetchInterceptor,numberOfRetries=_configuration$fetchI.numberOfRetries,retryIntervalInSeconds=_configuration$fetchI.retryIntervalInSeconds,exponentialBackoff=_configuration$fetchI.exponentialBackoff,maximumRetryIntervallInSeconds=_configuration$fetchI.maximumRetryIntervallInSeconds;// Provides a retry mechanism with configurable delay mechanism.
136
+ var $result=__WEBPACK_EXTERNAL_MODULE_rxjs_fetch_acb1bba5_fromFetch__(url,getOptions(options)).pipe(__WEBPACK_EXTERNAL_MODULE_rxjs_map__(function(response){if(KNOWN_ERRORS.has(response.status))// eslint-disable-next-line no-throw-literal
137
+ throw response;return response}),__WEBPACK_EXTERNAL_MODULE_rxjs_retry__({count:numberOfRetries,delay:function delay(error,retryCount){// Client side error will just be forwarded
138
+ if(typeof error.status!=="number")throw error;var httpError=error;if(httpError.headers.has("retry-after")){var retryValue=httpError.headers.get("retry-after");if(typeof retryValue==="string"){var intervallInSeconds=parseInt(retryValue);if(String(intervallInSeconds)===retryValue){log.info("Retry in ".concat(retryValue," seconds"),"according to given retry value.");// We interpret value as seconds.
139
+ return __WEBPACK_EXTERNAL_MODULE_rxjs_timer__(intervallInSeconds*1000)}var futureRetryMoment=new Date(retryValue);if(!isNaN(futureRetryMoment.getTime())){var now=new Date;if(now<futureRetryMoment){if(maximumRetryIntervallInSeconds<(futureRetryMoment.getTime()-now.getTime())/1000){log.info("Retry at",futureRetryMoment.toUTCString(),"according to given retry","value.");return __WEBPACK_EXTERNAL_MODULE_rxjs_timer__(futureRetryMoment)}log.warn("The recommended retry attempt is",futureRetryMoment.toUTCString(),"further in the future than the","configured maximum wait time of",maximumRetryIntervallInSeconds,"seconds.")}else log.warn("Given retry time recommendation","from server is in the past and","has to be ignored therefore.")}}}var delayInSeconds=exponentialBackoff?Math.pow(2,retryCount-1)*retryIntervalInSeconds:retryIntervalInSeconds;return __WEBPACK_EXTERNAL_MODULE_rxjs_timer__(Math.min(delayInSeconds,maximumRetryIntervallInSeconds)*1000)}}));return __WEBPACK_EXTERNAL_MODULE_rxjs_lastValueFrom__($result)}})};/**
140
+ * Determines a representation for given plain object.
141
+ * @param object - Object to represent.
142
+ * @param maximumRepresentationTryLength - Maximum representation string to
143
+ * process.
144
+ * @param maximumRepresentationLength - Maximum length of returned
145
+ * representation.
146
+ * @returns Representation string.
147
+ */var mayStripRepresentation=function mayStripRepresentation(object,maximumRepresentationTryLength,maximumRepresentationLength){var representation=(0,external_clientnode_.represent)(object);if(representation.length<=maximumRepresentationTryLength){if(representation.length>maximumRepresentationLength)return representation.substring(0,maximumRepresentationLength-"...".length)+"..."}else return"DOCUMENT IS TOO BIG TO REPRESENT";return representation};/**
148
+ * Updates/creates a design document in database with a validation function
149
+ * set to given code.
150
+ * @param databaseConnection - Database connection to use for document
151
+ * updates.
152
+ * @param documentName - Design document name.
153
+ * @param documentData - Design document data.
154
+ * @param description - Used to produce semantic logging messages.
155
+ * @param doLogging - Enables logging.
156
+ * @param idName - Property name for ids.
157
+ * @param revisionName - Property name for revisions.
158
+ * @param designDocumentNamePrefix - Document name prefix indicating deign
159
+ * documents.
160
+ * @returns Promise which will be resolved after given document has updated
161
+ * successfully.
162
+ */var ensureValidationDocumentPresence=/*#__PURE__*/function(){var _ensureValidationDocumentPresence=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(databaseConnection,documentName,documentData,description,doLogging,idName,revisionName,designDocumentNamePrefix){var newDocument,oldDocument,_t5,_t6;return _regenerator().w(function(_context7){while(1)switch(_context7.p=_context7.n){case 0:if(doLogging===void 0){doLogging=true}if(idName===void 0){idName="_id"}if(revisionName===void 0){revisionName="_rev"}if(designDocumentNamePrefix===void 0){designDocumentNamePrefix="_design/"}newDocument=_objectSpread(_defineProperty(_defineProperty(_defineProperty({},idName,"".concat(designDocumentNamePrefix).concat(documentName)),"language","javascript"),"version",package_0/* version */.rE),documentData);_context7.p=1;_context7.n=2;return databaseConnection.get("".concat(designDocumentNamePrefix).concat(documentName));case 2:oldDocument=_context7.v;newDocument[revisionName]=oldDocument[revisionName];_context7.n=3;return databaseConnection.put(newDocument);case 3:if(doLogging)log.info("".concat(description," updated."));_context7.n=8;break;case 4:_context7.p=4;_t5=_context7.v;if(doLogging)if(_t5.error==="not_found"||_t5.name==="not_found"||_t5.message==="missing"||_t5.reason==="missing")log.info("".concat(description," not available. Create new one."));else log.info("".concat(description," couldn't be updated:"),"\"".concat((0,external_clientnode_.represent)(_t5),"\" create new one."));_context7.p=5;_context7.n=6;return databaseConnection.put(newDocument);case 6:if(doLogging)log.info("".concat(description," installed/updated."));_context7.n=8;break;case 7:_context7.p=7;_t6=_context7.v;throw new Error("".concat(description," couldn't be installed/updated: ")+"\"".concat((0,external_clientnode_.represent)(_t6),"\"."),{cause:_t6});case 8:return _context7.a(2)}},_callee7,null,[[5,7],[1,4]])}));function ensureValidationDocumentPresence(_x15,_x16,_x17,_x18,_x19,_x20,_x21,_x22){return _ensureValidationDocumentPresence.apply(this,arguments)}return ensureValidationDocumentPresence}();/**
163
+ * Initializes a database connection instance.
164
+ * @param services - An object with stored service instances.
165
+ * @param configuration - Mutable by plugins extended configuration object.
166
+ * @param checkForDatabaseReachability - Indicates whether to check for
167
+ * reachability of newly created database.
168
+ * @returns Given and extended object of services.
169
+ */var initializeConnection=/*#__PURE__*/function(){var _initializeConnection=_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(services,configuration,checkForDatabaseReachability){var couchdb,config,url,_t7;return _regenerator().w(function(_context8){while(1)switch(_context8.p=_context8.n){case 0:if(checkForDatabaseReachability===void 0){checkForDatabaseReachability=true}couchdb=services.couchdb;config=configuration.couchdb;url=getEffectiveURL(config);/*
170
+ NOTE: We have to connect remotely for a memory based database to avoid
171
+ having multiple ones created per connector instance.
172
+ */if(services.couchdb.server.expressPouchDBInstance){// @ts-expect-error "pouchdb-validation" does not have a typings yet.
173
+ couchdb.connection=new couchdb.connector(config.databaseName,couchdb.server.runner.configuration);couchdb.connection.installValidationMethods()}else// @ts-expect-error "pouchdb-validation" does not have a typings yet.
174
+ couchdb.connection=new couchdb.connector(url,getConnectorOptions(config.connector));couchdb.connection.installCouchDBWebNodePlugin("backend");couchdb.connection.setMaxListeners(Infinity);// region ensure database presence
175
+ if(!checkForDatabaseReachability){_context8.n=4;break}_context8.p=1;_context8.n=2;return couchdb.connection.allDocs({limit:1});case 2:_context8.n=4;break;case 3:_context8.p=3;_t7=_context8.v;throw new Error("Database has not been installed yet: ".concat((0,external_clientnode_.represent)(_t7)),{cause:_t7});case 4:return _context8.a(2,services)}},_callee8,null,[[1,3]])}));function initializeConnection(_x23,_x24,_x25){return _initializeConnection.apply(this,arguments)}return initializeConnection}();/**
176
+ * Determines the effective database URL to connect to based on given
177
+ * configuration.
178
+ * @param configuration - Couchdb configuration object.
179
+ * @param withDatabase - Indicates whether the URL should contain the database
180
+ * name or not.
181
+ * @param withCredentials - Indicates whether the URL should contain the
182
+ * credentials or not.
183
+ * @returns The effective URL.
184
+ */var getEffectiveURL=function getEffectiveURL(configuration,withDatabase,withCredentials){if(withDatabase===void 0){withDatabase=true}if(withCredentials===void 0){withCredentials=false}var urlTemplate=/^https?:\/\//.test(configuration.url)?configuration.url:"http://{1}".concat(configuration.runner.host,":")+String(configuration.runner.port);return (0,external_clientnode_.format)(urlTemplate,withCredentials?"".concat(configuration.admin.name,":")+"".concat(configuration.admin.password,"@"):"")+(withDatabase?"/".concat(configuration.databaseName):"")};/**
185
+ * Waits for given promise to be resolved or given timeout has been exceeded.
186
+ * @param promise - Promise to wait for.
187
+ * @param timeoutInSeconds - Timeout in seconds.
188
+ * @param description - Used to produce semantic logging messages.
189
+ * @returns A promise which will be resolved after given promise is resolved or
190
+ * given timeout has been exceeded.
191
+ */var waitWithTimeout=function waitWithTimeout(promise,timeoutInSeconds,description){var timeoutExceeded=true;return Promise.race([promise.then(function(){timeoutExceeded=false}),(0,external_clientnode_.timeout)(timeoutInSeconds*1000).then(function(){if(timeoutExceeded)log.warn("Timeout of","".concat(String(timeoutInSeconds),"."),"seconds reached while waiting for ".concat(description,"."))})])};// endregion
192
+ // region model
193
+ /**
194
+ * Determines a mapping of all models to roles who are allowed to edit
195
+ * corresponding model instances.
196
+ * @param modelConfiguration - Model specification object.
197
+ * @returns The mapping object.
198
+ */var determineModelRolesMapping=function determineModelRolesMapping(modelConfiguration){var _modelConfiguration$p=modelConfiguration.property.name.special,rolePropertyName=_modelConfiguration$p.role,attachmentsPropertyName=_modelConfiguration$p.attachment;var modelRolesMapping={};var models=applyModelsInheritance(modelConfiguration);for(var _i3=0,_Object$entries2=Object.entries(models);_i3<_Object$entries2.length;_i3++){var _Object$entries2$_i=_slicedToArray(_Object$entries2[_i3],2),modelName=_Object$entries2$_i[0],model=_Object$entries2$_i[1];if(model[rolePropertyName]){modelRolesMapping[modelName]=_objectSpread({properties:{}},normalizeRoles(model[rolePropertyName]));for(var _i4=0,_Object$entries3=Object.entries(model);_i4<_Object$entries3.length;_i4++){var _Object$entries3$_i=_slicedToArray(_Object$entries3[_i4],2),name=_Object$entries3$_i[0],property=_Object$entries3$_i[1];if((0,external_clientnode_.isObject)(property))if(name===attachmentsPropertyName){modelRolesMapping[modelName].attachments={};for(var _i5=0,_Object$entries4=Object.entries(property);_i5<_Object$entries4.length;_i5++){var _Object$entries4$_i=_slicedToArray(_Object$entries4[_i5],2),fileDescription=_Object$entries4$_i[0],fileDefinition=_Object$entries4$_i[1];if(fileDefinition.roles)modelRolesMapping[modelName].attachments[fileDescription]=normalizeRoles(fileDefinition.roles)}}else if(property.roles)modelRolesMapping[modelName].properties[name]=normalizeRoles(property.roles)}}}return modelRolesMapping};/**
199
+ * Determines whether given value of a model is a property specification.
200
+ * @param value - Value to analyze.
201
+ * @returns Boolean indicating the case.
202
+ */var isPropertyDefinition=function isPropertyDefinition(value){return (0,external_clientnode_.isObject)(value)};/**
203
+ * Determines all property names which are indexable in a generic manner.
204
+ * @param modelConfiguration - Model specification object.
205
+ * @param model - Model to determine property names from.
206
+ * @returns The mapping object.
207
+ */var determineGenericIndexablePropertyNames=function determineGenericIndexablePropertyNames(modelConfiguration,model){var specialNames=modelConfiguration.property.name.special;return Object.keys(model).filter(function(name){var specification=model[name];return isPropertyDefinition(specification)&&Object.prototype.hasOwnProperty.call(specification,"index")&&specification.index||isPropertyDefinition(specification)&&!(Object.prototype.hasOwnProperty.call(specification,"index")&&!specification.index||modelConfiguration.property.name.reserved.concat(specialNames.additional,specialNames.role,specialNames.attachment,specialNames.conflict,specialNames.constraint.execution,specialNames.constraint.expression,specialNames.deleted,specialNames.deletedConflict,specialNames.extend,specialNames.maximumAggregatedSize,specialNames.minimumAggregatedSize,specialNames.oldType,specialNames.id,specialNames.revision,specialNames.revisions,specialNames.revisionsInformation,specialNames.type,specialNames.updateStrategy).includes(name)||specification.type&&(typeof specification.type==="string"&&specification.type.endsWith("[]")||Array.isArray(specification.type)&&specification.type.length&&Array.isArray(specification.type[0])||Object.prototype.hasOwnProperty.call(modelConfiguration.entities,specification.type)))}).concat([specialNames.id,specialNames.revision]).sort()};/**
208
+ * Extend given model with all specified one.
209
+ * @param model - Model to extend.
210
+ * @param modelConfiguration - Model specification object.
211
+ * @param _name - Model name to extend. Only needed for debugging purposes.
212
+ * @returns Given model in extended version.
213
+ */var _applyModelInheritance=function applyModelInheritance(model,modelConfiguration,_name){if(_name===void 0){_name="in-place"}var models=modelConfiguration.entities;var extendPropertyName=modelConfiguration.property.name.special.extend;if(Object.prototype.hasOwnProperty.call(models,"_base"))if(Object.prototype.hasOwnProperty.call(model,extendPropertyName)&&model[extendPropertyName]&&![].concat(model[extendPropertyName]).includes("_base"))model[extendPropertyName]=["_base"].concat(model[extendPropertyName]);else model[extendPropertyName]="_base";if(Object.prototype.hasOwnProperty.call(model,extendPropertyName)){var originallyDeclaredExtensions=[].concat(model[extendPropertyName]);var _iterator4=_createForOfIteratorHelper(originallyDeclaredExtensions),_step4;try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var modelNameToExtend=_step4.value;if(modelNameToExtend!=="_base")_applyModelInheritance(models[modelNameToExtend],modelConfiguration,modelNameToExtend);/*
214
+ NOTE: We need to merge into model to change the given object
215
+ in-place. Furthermore, we have to copy the initial model before
216
+ merging it finally to avoid having the inherited overwrites in
217
+ the final model object as well.
218
+ */(0,external_clientnode_.extend)(true,model,models[modelNameToExtend],(0,external_clientnode_.copy)(model));model[extendPropertyName]=originallyDeclaredExtensions}}catch(err){_iterator4.e(err)}finally{_iterator4.f()}delete model[extendPropertyName]}applyDefaultPropertyConfigurations(model,modelConfiguration);return model};/**
219
+ * Apply default property definitions to given model.
220
+ * @param model - Model to extends its properties.
221
+ * @param modelConfiguration - Model configuration to take into account.
222
+ * @returns Extended model.
223
+ */var applyDefaultPropertyConfigurations=function applyDefaultPropertyConfigurations(model,modelConfiguration){var specialNames=modelConfiguration.property.name.special;for(var _i6=0,_Object$entries5=Object.entries(model);_i6<_Object$entries5.length;_i6++){var _Object$entries5$_i=_slicedToArray(_Object$entries5[_i6],2),name=_Object$entries5$_i[0],propertyDefinition=_Object$entries5$_i[1];if(name===specialNames.attachment){var fileDefinition=propertyDefinition;for(var _i7=0,_Object$entries6=Object.entries(fileDefinition);_i7<_Object$entries6.length;_i7++){var _Object$entries6$_i=_slicedToArray(_Object$entries6[_i7],2),type=_Object$entries6$_i[0],value=_Object$entries6$_i[1];fileDefinition[type]=(0,external_clientnode_.extend)(true,(0,external_clientnode_.copy)(modelConfiguration.property.defaultDefinition),value)}}else if(![specialNames.role,specialNames.constraint.execution,specialNames.constraint.expression,specialNames.extend,specialNames.maximumAggregatedSize,specialNames.minimumAggregatedSize,specialNames.oldType].includes(name)){var property=(0,external_clientnode_.extend)(true,(0,external_clientnode_.copy)(modelConfiguration.property.defaultDefinition),propertyDefinition);model[name]=property;var types=[].concat(property.type);var _iterator5=_createForOfIteratorHelper(types),_step5;try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var _type2=_step5.value;if(!Array.isArray(_type2)&&_typeof(_type2)==="object")property.type=_applyModelInheritance(_type2,modelConfiguration)}}catch(err){_iterator5.e(err)}finally{_iterator5.f()}}}return model};/**
224
+ * Extend default specification with specific one.
225
+ * @param modelConfiguration - Model specification object.
226
+ * @returns Models with extended specific specifications.
227
+ */var applyModelsInheritance=function applyModelsInheritance(modelConfiguration){var models=modelConfiguration.entities;var typePattern=modelConfiguration.property.name.typePattern;for(var _i8=0,_Object$keys=Object.keys(models);_i8<_Object$keys.length;_i8++){var modelName=_Object$keys[_i8];if(!(new RegExp(typePattern.public).test(modelName)||new RegExp(typePattern.private).test(modelName)))throw new Error("Model names have to match "+"\"".concat(typePattern.public,"\" or \"").concat(typePattern.private,"\" for ")+"xprivate one (given name: \"".concat(modelName,"\")."));if(modelName!=="_base")_applyModelInheritance(models[modelName],modelConfiguration,modelName)}return models};/**
228
+ * Convert given roles to its normalized representation.
229
+ * @param roles - Unstructured role's description.
230
+ * @returns Normalized roles representation.
231
+ */var normalizeRoles=function normalizeRoles(roles){if(Array.isArray(roles))return{read:roles,write:roles};if(_typeof(roles)==="object"){var result={read:[],write:[]};for(var _i9=0,_Object$keys2=Object.keys(result);_i9<_Object$keys2.length;_i9++){var type=_Object$keys2[_i9];if(Object.prototype.hasOwnProperty.call(roles,type)){var operationRoles=roles[type];if(Array.isArray(operationRoles))result[type]=operationRoles;else if(typeof operationRoles==="string")result[type]=[operationRoles]}}return result}return{read:[roles],write:[roles]}};// endregion
232
+ export { TOGGLE_LATEST_REVISION_DETERMINING, applyDefaultPropertyConfigurations, _applyModelInheritance as applyModelInheritance, applyModelsInheritance, determineGenericIndexablePropertyNames, determineModelRolesMapping, ensureValidationDocumentPresence, getConnectorOptions, getEffectiveURL, getPouchDBPlugin, initializeConnection, isPropertyDefinition, log, mayStripRepresentation, normalizeRoles, removeDeprecatedIndexes, waitWithTimeout };
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { PluginPromises } from 'web-node/type';
2
- import { ServicesState, State } from './type';
1
+ import type { PluginPromises } from 'web-node/type';
2
+ import type { PluginHandler, ServicesState, State } from './type';
3
3
  /**
4
4
  * Launches an application server und triggers all some pluginable hooks on
5
5
  * an event.
@@ -38,5 +38,5 @@ export declare const postLoadService: (state: State) => Promise<void>;
38
38
  * @returns Promise resolving to nothing.
39
39
  */
40
40
  export declare const shouldExit: ({ configuration, services }: State) => Promise<void>;
41
- export declare const database: any;
41
+ export declare const database: PluginHandler;
42
42
  export default database;