UNPKG

couchdb-web-node-plugin

Version:

A couchdb server, model instance conflict handler, rest api, authentication, session management, schema validator and model relation guarantee for webNode.

1 lines 235 kB
(()=>{var __webpack_modules__=[(e,t,r)=>{"use strict";r.d(t,{bulkDocsFactory:()=>h,determineAllowedModelRolesMapping:()=>g,determineGenericIndexablePropertyNames:()=>D,ensureValidationDocumentPresence:()=>v,extendModels:()=>M,getConnectorOptions:()=>b,initializeConnection:()=>y,mayStripRepresentation:()=>O,removeDeprecatedIndexes:()=>E});var n=r(1),o=r.n(n),a=r(2),i=r.n(a),_=r(3),c=r.n(_),u=r(4);const s=require("rxjs"),l=require("rxjs/fetch"),p="1.0.761";function d(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 f(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)?f(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 f(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 m=Symbol("toggleLatestRevisionDetermining"),E=function(){var e=i()(c().mark((function e(t,r,n){var o,a,i,_,u,s,l,p,f,m,E,b,O;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getIndexes();case 2:o=e.sent.indexes.filter((function(e){return e.name.endsWith("-GenericIndex")})),a=d(o);case 4:if((i=a()).done){e.next=21;break}_=i.value,u=!1,s=0,l=Object.entries(r);case 8:if(!(s<l.length)){e.next=16;break}if(p=l[s],f=p[0],m=p[1],!_.name.startsWith(f+"-")){e.next=13;break}for(E=0,b=D(n,m);E<b.length;E++)O=b[E],[f+"-"+O+"-GenericIndex",f+"-GenericIndex"].includes(_.name)&&(u=!0);return e.abrupt("break",16);case 13:s++,e.next=8;break;case 16:if(u){e.next=19;break}return e.next=19,t.deleteIndex(_);case 19:e.next=4;break;case 21:case"end":return e.stop()}}),e)})));return function(t,r,n){return e.apply(this,arguments)}}(),b=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{fetch:function(n,o){var a=e.fetchInterceptor,i=a.numberOfRetries,_=a.retryIntervalInSeconds,c=a.exponentialBackoff,p=a.maximumRetryIntervallInSeconds,d=(0,l.fromFetch)(n,function(r){return void 0===r&&(r={}),e.fetch&&(r=(0,u.extend)(!0,(0,u.copy)(e.fetch),r)),Array.isArray(t)&&t.length>0&&(r.signal=t.pop()),r}(o)).pipe((0,s.map)((function(e){if(r.has(e.status))throw e;return e})),(0,s.retry)({count:i,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 o=parseInt(n);if(String(o)===n)return console.info("Retry in "+n+" seconds","according to given retry value."),(0,s.timer)(1e3*o);var a=new Date(n);if(!isNaN(a.getTime())){var i=new Date;if(i<a){if(p<(a.getTime()-i.getTime())/1e3)return console.info("Retry at",a.toUTCString(),"according to given retry","value."),(0,s.timer)(a);console.warn("The recommended retry attempt is",a.toUTCString(),"further in the future than the","configured maximum wait time of",p,"seconds.")}else console.warn("Given retry time recommendation","from server is in the past and","has to be ignored therefore.")}}}var u=c?Math.pow(2,t-1)*_:_;return(0,s.timer)(1e3*Math.min(u,p))}}));return(0,s.lastValueFrom)(d)}}},O=function(e,t,r){var n=(0,u.represent)(e);return n.length<=t?n.length>r?n.substring(0,r-3)+"...":n:"DOCUMENT IS TOO BIG TO REPRESENT"},v=function(){var e=i()(c().mark((function e(t,r,n,a,i,_,s,l){var d,f,m;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return void 0===i&&(i=!0),void 0===_&&(_="_id"),void 0===s&&(s="_rev"),void 0===l&&(l="_design/"),f=o()(((d={})[_]=""+l+r,d.language="javascript",d.version=p,d),n),e.prev=5,e.next=8,t.get(""+l+r);case 8:return m=e.sent,f[s]=m[s],e.next=12,t.put(f);case 12:i&&console.info(a+" updated."),e.next=27;break;case 15:return e.prev=15,e.t0=e.catch(5),i&&("not_found"===e.t0.error?console.info(a+" not available: create new one."):console.info(a+" couldn't be updated: \""+(0,u.represent)(e.t0)+'" create new one.')),e.prev=18,e.next=21,t.put(f);case 21:i&&console.info(a+" installed/updated."),e.next=27;break;case 24:throw e.prev=24,e.t1=e.catch(18),new Error(a+" couldn't be installed/updated: \""+(0,u.represent)(e.t1)+'".');case 27:case"end":return e.stop()}}),e,null,[[5,15],[18,24]])})));return function(t,r,n,o,a,i,_,c){return e.apply(this,arguments)}}(),h=function(e,t){var r=t.model.property.name.special.id,n=t.model.property.name.special.revision;return i()(c().mark((function o(a){var i,_,s,l,p,f,E,b,O,v,h,y,g,P,D,x,M,A,w,T,I,C=arguments;return c().wrap((function(o){for(;;)switch(o.prev=o.next){case 0:for(i=C.length,_=new Array(i>1?i-1:0),s=1;s<i;s++)_[s-1]=C[s];l=_.length>0&&_[_.length-1]===m,p=l?!t.skipLatestRevisionDetermining:t.skipLatestRevisionDetermining,l&&_.pop(),f=!Array.isArray(a)&&(0,u.isObject)(a)&&r in a?[a]:a,E=t.maximumNumberOfEntitiesInBulkOperation,b=[],O=0;case 8:if(!(O<f.length)){o.next=17;break}return v=f.slice(O,O+E),o.next=12,e.call.apply(e,[this,v].concat(_));case 12:h=o.sent,b=b.concat(h);case 14:O+=E,o.next=8;break;case 17:y=[],g=[],P=0,D=d(b);case 21:if((x=D()).done){o.next=44;break}if(M=x.value,"object"!=typeof f[P]){o.next=41;break}if(!(n in f[P])||"conflict"!==M.name||!["0-latest","0-upsert"].includes(f[P][n])){o.next=29;break}g.push(f[P]),y.push(P),o.next=41;break;case 29:if(!(r in f[P]&&t.ignoreNoChangeError&&"name"in M&&"forbidden"===M.name&&"message"in M&&M.message.startsWith("NoChange:"))){o.next=41;break}if(b[P]={id:f[P][r],ok:!0},p){o.next=41;break}if(!(n in f[P])||["0-latest","0-upsert"].includes(f[P][n])){o.next=36;break}o.t0=f[P][n],o.next=40;break;case 36:return o.next=38,this.get(b[P].id);case 38:o.t1=n,o.t0=o.sent[o.t1];case 40:b[P].rev=o.t0;case 41:P+=1;case 42:o.next=21;break;case 44:if(!g.length){o.next=51;break}return f=g,l&&_.push(m),o.next=49,this.bulkDocs.apply(this,[f].concat(_));case 49:for(A=o.sent,w=d(A);!(T=w()).done;)I=T.value,b[y.shift()]=I;case 51:return o.abrupt("return",b);case 52:case"end":return o.stop()}}),o,this)})))},y=function(){var e=i()(c().mark((function e(t,r){var n,o,a,_;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.couchdb,o=r.couchdb,a=(0,u.format)(o.url,o.admin.name+":"+o.admin.password+"@")+"/"+o.databaseName,Object.prototype.hasOwnProperty.call(n.server,"runner")&&n.server.runner.binaryFilePath?n.connection=new n.connector(a,b(r.couchdb.connector)):n.connection=new n.connector(o.databaseName,b(r.couchdb.connector)),n.connection.installValidationMethods(),(_=n.connection).setMaxListeners(1/0),_.bulkDocs=h(_.bulkDocs,r.couchdb),_.post=_.put=i()(c().mark((function e(t,r){var n;return c().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,_.bulkDocs.call(this,[t],r);case 2:if(null==(n=e.sent[0])||!n.name){e.next=5;break}throw n;case 5:return e.abrupt("return",n);case 6:case"end":return e.stop()}}),e,this)}))),!Object.prototype.hasOwnProperty.call(n.server,"runner")){e.next=22;break}return e.prev=10,e.next=13,(0,u.checkReachability)(a);case 13:e.next=22;break;case 15:if(e.prev=15,e.t0=e.catch(10),console.info("Database could not be retrieved yet: Creating it."),u.globalContext.fetch){e.next=20;break}throw new Error("Missing fetch implementation.");case 20:return e.next=22,u.globalContext.fetch(a,{method:"PUT"});case 22:return e.abrupt("return",t);case 23:case"end":return e.stop()}}),e,null,[[10,15]])})));return function(t,r){return e.apply(this,arguments)}}(),g=function(e){for(var t=e.property.name.special.allowedRole,r={},n=M(e),a=0,i=Object.entries(n);a<i.length;a++){var _=i[a],c=_[0],s=_[1];if(s[t]){r[c]=o()({properties:{}},A(s[t]));for(var l=0,p=Object.entries(s);l<p.length;l++){var d=p[l],f=d[0],m=d[1];(0,u.isObject)(m)&&m.allowedRoles&&(r[c].properties[f]=A(m.allowedRoles))}}else r[c]={properties:{},read:[],write:[]}}return r},P=function(e){return(0,u.isObject)(e)},D=function(e,t){var r=e.property.name.special;return Object.keys(t).filter((function(n){var o=t[n];return P(o)&&Object.prototype.hasOwnProperty.call(o,"index")&&o.index||P(o)&&!(Object.prototype.hasOwnProperty.call(o,"index")&&!o.index||e.property.name.reserved.concat(r.additional,r.allowedRole,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).includes(n)||o.type&&("string"==typeof o.type&&o.type.endsWith("[]")||Array.isArray(o.type)&&o.type.length&&Array.isArray(o.type[0])||Object.prototype.hasOwnProperty.call(e.entities,o.type)))})).concat([r.id,r.revision]).sort()},x=function(e,t,r){if(void 0===r&&(r="_extends"),"_base"===e)return t[e];if(Object.prototype.hasOwnProperty.call(t,"_base")&&(Object.prototype.hasOwnProperty.call(t[e],r)&&t[e][r]?t[e][r]=["_base"].concat(t[e][r]):t[e][r]="_base"),Object.prototype.hasOwnProperty.call(t[e],r)){for(var n,o=d([].concat(t[e][r]));!(n=o()).done;){var a=n.value;t[e]=(0,u.extend)(!0,(0,u.copy)(x(a,t,r)),t[e])}delete t[e][r]}return t[e]},M=function(e){for(var t=e.property.name.special,r={},n=e.property.name.typePattern,o=0,a=Object.keys(e.entities);o<a.length;o++){var i=a[o];if(!new RegExp(n.public).test(i)&&!new RegExp(n.private).test(i))throw new Error('Model names have to match "'+n.public+'" or "'+n.private+'" for private one (given name: "'+i+'").');r[i]=x(i,e.entities,t.extend)}for(var _=0,c=Object.values(r);_<c.length;_++)for(var s=c[_],l=0,p=Object.entries(s);l<p.length;l++){var d=p[l],f=d[0],m=d[1];if(f===t.attachment)for(var E=m,b=0,O=Object.entries(E);b<O.length;b++){var v=O[b],h=v[0],y=v[1];E[h]=(0,u.extend)(!0,(0,u.copy)(e.property.defaultSpecification),y)}else[t.allowedRole,t.constraint.execution,t.constraint.expression,t.extend,t.maximumAggregatedSize,t.minimumAggregatedSize,t.oldType].includes(f)||(s[f]=(0,u.extend)(!0,(0,u.copy)(e.property.defaultSpecification),m))}return r},A=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 o=n[r];Object.prototype.hasOwnProperty.call(e,o)&&(Array.isArray(e[o])?t[o]=e[o]:t[o]=[e[o]])}return t}return{read:[e],write:[e]}}},e=>{"use strict";e.exports=require("@babel/runtime/helpers/extends")},e=>{"use strict";e.exports=require("@babel/runtime/helpers/asyncToGenerator")},e=>{"use strict";e.exports=require("@babel/runtime/regenerator")},e=>{"use strict";e.exports=require("clientnode")},(module,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{database:()=>database,default:()=>__WEBPACK_DEFAULT_EXPORT__,loadService:()=>loadService,postLoadService:()=>postLoadService,preLoadService:()=>preLoadService,shouldExit:()=>shouldExit});var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(1),_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default=__webpack_require__.n(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__),_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(2),_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default=__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__),_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(3),_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default=__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2__),clientnode__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(4),clientnode__WEBPACK_IMPORTED_MODULE_3___default=__webpack_require__.n(clientnode__WEBPACK_IMPORTED_MODULE_3__),fs__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(6),fs__WEBPACK_IMPORTED_MODULE_4___default=__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_4__),path__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(7),path__WEBPACK_IMPORTED_MODULE_5___default=__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_5__),pouchdb_node__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(9),pouchdb_node__WEBPACK_IMPORTED_MODULE_6___default=__webpack_require__.n(pouchdb_node__WEBPACK_IMPORTED_MODULE_6__),pouchdb_authentication__WEBPACK_IMPORTED_MODULE_7__=__webpack_require__(10),pouchdb_authentication__WEBPACK_IMPORTED_MODULE_7___default=__webpack_require__.n(pouchdb_authentication__WEBPACK_IMPORTED_MODULE_7__),pouchdb_find__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__(11),pouchdb_find__WEBPACK_IMPORTED_MODULE_8___default=__webpack_require__.n(pouchdb_find__WEBPACK_IMPORTED_MODULE_8__),pouchdb_validation__WEBPACK_IMPORTED_MODULE_9__=__webpack_require__(12),pouchdb_validation__WEBPACK_IMPORTED_MODULE_9___default=__webpack_require__.n(pouchdb_validation__WEBPACK_IMPORTED_MODULE_9__),_databaseHelper__WEBPACK_IMPORTED_MODULE_11__=__webpack_require__(8),_databaseHelper__WEBPACK_IMPORTED_MODULE_11___default=__webpack_require__.n(_databaseHelper__WEBPACK_IMPORTED_MODULE_11__),_helper__WEBPACK_IMPORTED_MODULE_10__=__webpack_require__(0),_server__WEBPACK_IMPORTED_MODULE_12__=__webpack_require__(36);function _createForOfIteratorHelperLoose(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=_unsupportedIterableToArray(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 _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(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)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(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}module=__webpack_require__.hmd(module);var preLoadService=function(){var _ref2=_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().mark((function _callee(_ref){var configuration,services,couchdb,triedPaths,runnerFound,_iterator,_step,runner,inPlaceRunner,_iterator2,_step2,name,binaryRunner,_iterator3,_step3,directoryPath,_iterator4,_step4,_name,binaryFilePath,modelConfiguration,models;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().wrap((function _callee$(_context){for(;;)switch(_context.prev=_context.next){case 0:if(configuration=_ref.configuration.couchdb,services=_ref.services,Object.prototype.hasOwnProperty.call(services,"couchdb")||(services.couchdb={}),couchdb=services.couchdb,Object.prototype.hasOwnProperty.call(couchdb,"connector")||(couchdb.connector=pouchdb_node__WEBPACK_IMPORTED_MODULE_6___default().plugin({bulkDocs:(0,_helper__WEBPACK_IMPORTED_MODULE_10__.bulkDocsFactory)(pouchdb_node__WEBPACK_IMPORTED_MODULE_6___default().prototype.bulkDocs,configuration)}).plugin(pouchdb_authentication__WEBPACK_IMPORTED_MODULE_7___default()).plugin(pouchdb_find__WEBPACK_IMPORTED_MODULE_8___default()).plugin(pouchdb_validation__WEBPACK_IMPORTED_MODULE_9___default()).defaults(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({prefix:(0,path__WEBPACK_IMPORTED_MODULE_5__.resolve)(configuration.backend.configuration["couchdb/database_dir"])+"/"},(0,_helper__WEBPACK_IMPORTED_MODULE_10__.getConnectorOptions)(configuration.connector))),configuration.debug&&couchdb.connector.debug.enable("*")),Object.prototype.hasOwnProperty.call(couchdb,"server")){_context.next=59;break}couchdb.server={},triedPaths=[],runnerFound=!1,_iterator=_createForOfIteratorHelperLoose([].concat(configuration.runner.variants));case 9:if((_step=_iterator()).done){_context.next=58;break}if(runner=_step.value,!runner.packages){_context.next=32;break}inPlaceRunner=runner,runnerFound=!0,_iterator2=_createForOfIteratorHelperLoose(inPlaceRunner.packages);case 15:if((_step2=_iterator2()).done){_context.next=28;break}return name=_step2.value,_context.prev=17,_context.next=20,eval("import('"+name+"')");case 20:_context.next=26;break;case 22:return _context.prev=22,_context.t0=_context.catch(17),runnerFound=!1,_context.abrupt("break",28);case 26:_context.next=15;break;case 28:if(!runnerFound){_context.next=31;break}return couchdb.server.runner=inPlaceRunner,_context.abrupt("break",58);case 31:return _context.abrupt("continue",56);case 32:binaryRunner=runner,_iterator3=_createForOfIteratorHelperLoose([].concat(binaryRunner.locations));case 34:if((_step3=_iterator3()).done){_context.next=54;break}directoryPath=_step3.value,_iterator4=_createForOfIteratorHelperLoose([].concat(binaryRunner.names));case 37:if((_step4=_iterator4()).done){_context.next=50;break}return _name=_step4.value,binaryFilePath=(0,path__WEBPACK_IMPORTED_MODULE_5__.resolve)(directoryPath,_name),triedPaths.push(binaryFilePath),_context.next=43,(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.isFile)(binaryFilePath);case 43:if(!_context.sent){_context.next=48;break}return binaryRunner.binaryFilePath=binaryFilePath,couchdb.server.runner=binaryRunner,runnerFound=!0,_context.abrupt("break",50);case 48:_context.next=37;break;case 50:if(!runnerFound){_context.next=52;break}return _context.abrupt("break",54);case 52:_context.next=34;break;case 54:if(!runnerFound){_context.next=56;break}return _context.abrupt("break",58);case 56:_context.next=9;break;case 58:runnerFound||console.info("No couchdb runner found via files in one of the following",'locations: "'+triedPaths.join('", "')+'". Running pouchdb',"locally.");case 59:modelConfiguration=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.copy)(configuration.model),delete modelConfiguration.property.defaultSpecification,delete modelConfiguration.entities,models=(0,_helper__WEBPACK_IMPORTED_MODULE_10__.extendModels)(configuration.model),couchdb.validateDocument=function(e,t){var r,n=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.copy)(null!==(r=t.oldDocument)&&void 0!==r?r:e),o=Boolean(t.checkPublicModelType);(e=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.copy)(e))[configuration.model.property.name.special.strategy]="migrate",t.type&&(e[modelConfiguration.property.name.special.type]=n[modelConfiguration.property.name.special.type]=t.type);try{return(0,_databaseHelper__WEBPACK_IMPORTED_MODULE_11__.validateDocumentUpdate)(e,n,{db:configuration.databaseName,name:configuration.admin.name,roles:["_admin"]},(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.copy)(configuration.security[configuration.databaseName]),modelConfiguration,models,o),!0}catch(e){return!(!Object.prototype.hasOwnProperty.call(e,"forbidden")||!e.forbidden.startsWith("NoChange:"))||e}};case 64:case"end":return _context.stop()}}),_callee,null,[[17,22]])})));return function(e){return _ref2.apply(this,arguments)}}(),loadService=function(){var _ref3=_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().mark((function _callee2(state){var configuration,services,promise,couchdb,urlPrefix,authorizationHeader,headers,unauthenticatedUserDatabaseConnection,authenticatedUserDatabaseConnection,userDatabaseConnection,_i,_Object$entries,_Object$entries$_i,name,userConfiguration,_userDatabaseConnecti,_iterator5,_step5,prefix,subPath,fullPath,url,value,response,changeNeeded,securityConfigurations,_i2,_Object$entries2,_Object$entries2$_i,databaseName,securityObject,fullSecurityObject,_fullSecurityObject$a,_fullSecurityObject$a2,_fullSecurityObject$m,_fullSecurityObject$m2,_response,modelConfiguration,specialNames,idName,revisionName,typeName,models,databaseHelperCode,_iterator6,_step6,_type,code,_i3,_Object$entries3,_Object$entries3$_i,modelName,model,_i4,_Object$entries4,_Object$entries4$_i,_name2,specification,_iterator7,_step7,constraint,_iterator8,_step8,type,_constraint,migrators,_iterator9,_step9,file,extension,_name3,documents,_iterator10,_step10,document,_forbidden,_iterator11,_step11,retrievedDocument,_document,newDocument,_iterator12,_step12,_name4,_result,result,genericIndexes,_i5,_Object$entries5,_Object$entries5$_i,_modelName,_model,_iterator13,_step13,propertyName,_name5,found,_iterator14,_step14,index,_i6,_Object$entries6,_viewDocument,_Object$entries6$_i,id,viewConfiguration,viewDocument,_i7,_Object$entries7,_Object$entries7$_i,_name6,viewDataConfiguration,rawData,_result2;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().wrap((function _callee2$(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:if(configuration=state.configuration,services=state.services,clientnode__WEBPACK_IMPORTED_MODULE_3__.globalContext.fetch){_context2.next=3;break}throw new Error("Missing fetch implementation.");case 3:if(promise=null,couchdb=services.couchdb,!Object.prototype.hasOwnProperty.call(couchdb.server,"runner")){_context2.next=12;break}return _context2.next=8,(0,_server__WEBPACK_IMPORTED_MODULE_12__.ni)(state);case 8:couchdb.server.restart=_server__WEBPACK_IMPORTED_MODULE_12__.S8,couchdb.server.start=_server__WEBPACK_IMPORTED_MODULE_12__.ni,couchdb.server.stop=_server__WEBPACK_IMPORTED_MODULE_12__.ds,promise=new Promise((function(e,t){couchdb.server.resolve=e,couchdb.server.reject=t}));case 12:if(!Object.prototype.hasOwnProperty.call(couchdb,"connection")){_context2.next=14;break}return _context2.abrupt("return",{couchdb:promise});case 14:if(urlPrefix=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.format)(configuration.couchdb.url,""),authorizationHeader={Authorization:"Basic "+Buffer.from(configuration.couchdb.admin.name+":"+configuration.couchdb.admin.password,"binary").toString("base64")},headers={Accept:"application/json","Content-Type":"application/json"},!configuration.couchdb.ensureAdminPresence){_context2.next=48;break}return unauthenticatedUserDatabaseConnection=new couchdb.connector(urlPrefix+"/_users",(0,_helper__WEBPACK_IMPORTED_MODULE_10__.getConnectorOptions)(configuration.couchdb.connector)),_context2.prev=19,_context2.next=22,unauthenticatedUserDatabaseConnection.allDocs();case 22:return console.info('No admin user available. Automatically creating admin user "'+configuration.couchdb.admin.name+'".'),_context2.next=25,clientnode__WEBPACK_IMPORTED_MODULE_3__.globalContext.fetch(urlPrefix+"/"+couchdb.server.runner.adminUserConfigurationPath+"/"+configuration.couchdb.admin.name,{body:'"'+configuration.couchdb.admin.password+'"',method:"PUT"});case 25:_context2.next=45;break;case 27:if(_context2.prev=27,_context2.t0=_context2.catch(19),"unauthorized"!==_context2.t0.name){_context2.next=44;break}return authenticatedUserDatabaseConnection=new couchdb.connector(urlPrefix+"/_users",_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({},(0,_helper__WEBPACK_IMPORTED_MODULE_10__.getConnectorOptions)(configuration.couchdb.connector),{auth:{username:configuration.couchdb.admin.name,password:configuration.couchdb.admin.password}})),_context2.prev=31,_context2.next=34,authenticatedUserDatabaseConnection.allDocs();case 34:_context2.next=39;break;case 36:_context2.prev=36,_context2.t1=_context2.catch(31),console.error("Can't login as existing admin user \""+configuration.couchdb.admin.name+'": '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t1));case 39:return _context2.prev=39,authenticatedUserDatabaseConnection.close(),_context2.finish(39);case 42:_context2.next=45;break;case 44:console.error("Can't create new admin user \""+configuration.couchdb.admin.name+'": '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t0));case 45:return _context2.prev=45,unauthenticatedUserDatabaseConnection.close(),_context2.finish(45);case 48:if(!configuration.couchdb.ensureUserPresence){_context2.next=79;break}userDatabaseConnection=new couchdb.connector(urlPrefix+"/_users",_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({},(0,_helper__WEBPACK_IMPORTED_MODULE_10__.getConnectorOptions)(configuration.couchdb.connector),{auth:{username:configuration.couchdb.admin.name,password:configuration.couchdb.admin.password}})),_i=0,_Object$entries=Object.entries(configuration.couchdb.users);case 51:if(!(_i<_Object$entries.length)){_context2.next=79;break}return _Object$entries$_i=_Object$entries[_i],name=_Object$entries$_i[0],userConfiguration=_Object$entries$_i[1],_context2.prev=53,_context2.next=56,userDatabaseConnection.get("org.couchdb.user:"+name);case 56:_context2.next=73;break;case 58:if(_context2.prev=58,_context2.t2=_context2.catch(53),"not_found"!==_context2.t2.error){_context2.next=72;break}return console.info('Create missing database user "'+name+'".'),_context2.prev=62,_context2.next=65,userDatabaseConnection.put((_userDatabaseConnecti={},_userDatabaseConnecti[configuration.couchdb.model.property.name.special.id]="org.couchdb.user:"+name,_userDatabaseConnecti.name=name,_userDatabaseConnecti.password=userConfiguration.password,_userDatabaseConnecti.roles=userConfiguration.roles,_userDatabaseConnecti.type="user",_userDatabaseConnecti));case 65:_context2.next=70;break;case 67:throw _context2.prev=67,_context2.t3=_context2.catch(62),new Error("Couldn't create missing user \""+name+'": '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t3));case 70:_context2.next=73;break;case 72:throw new Error("Couldn't check for presence of user \""+name+'": '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t2));case 73:return _context2.prev=73,userDatabaseConnection.close(),_context2.finish(73);case 76:_i++,_context2.next=51;break;case 79:if(!configuration.couchdb.model.updateConfiguration){_context2.next=134;break}_iterator5=_createForOfIteratorHelperLoose(configuration.couchdb.backend.prefixes);case 81:if((_step5=_iterator5()).done){_context2.next=134;break}prefix=_step5.value,_context2.t4=_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().keys(configuration.couchdb.backend.configuration);case 84:if((_context2.t5=_context2.t4()).done){_context2.next=132;break}if(subPath=_context2.t5.value,!Object.prototype.hasOwnProperty.call(configuration.couchdb.backend.configuration,subPath)){_context2.next=130;break}return fullPath="/"+prefix+(prefix.trim()?"/":"")+subPath,url=""+urlPrefix+fullPath,value=configuration.couchdb.backend.configuration[subPath],response=void 0,_context2.prev=91,_context2.next=94,clientnode__WEBPACK_IMPORTED_MODULE_3__.globalContext.fetch(url,{headers:authorizationHeader});case 94:response=_context2.sent,_context2.next=100;break;case 97:_context2.prev=97,_context2.t6=_context2.catch(91),console.warn('Configuration "'+fullPath+'" (with desired value ['+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(value)+"]) couldn't be determined: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t6));case 100:if(!response){_context2.next=130;break}if(!response.ok){_context2.next=129;break}if(changeNeeded=!0,"function"!=typeof response.text){_context2.next=115;break}return _context2.prev=104,_context2.t7=value,_context2.next=108,response["string"==typeof value?"text":"json"]();case 108:_context2.t8=_context2.sent,changeNeeded=_context2.t7===_context2.t8,_context2.next=115;break;case 112:_context2.prev=112,_context2.t9=_context2.catch(104),console.warn('Error checking curent value of "'+fullPath+'" to be ['+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(value)+"]: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t9));case 115:if(!changeNeeded){_context2.next=126;break}return _context2.prev=116,_context2.next=119,clientnode__WEBPACK_IMPORTED_MODULE_3__.globalContext.fetch(url,{body:'"'+configuration.couchdb.backend.configuration[subPath]+'"',method:"PUT"});case 119:_context2.next=124;break;case 121:_context2.prev=121,_context2.t10=_context2.catch(116),console.error('Configuration "'+fullPath+"\" couldn't be applied to ["+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(value)+"]: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t10));case 124:_context2.next=127;break;case 126:console.info('Configuration "'+fullPath+'" is already set to desired value ['+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(value)+"].");case 127:_context2.next=130;break;case 129:console.info('Configuration "'+fullPath+'" does not exist (desired value ['+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(value)+"]). Response code is "+String(response.status)+".");case 130:_context2.next=84;break;case 132:_context2.next=81;break;case 134:return _context2.next=136,(0,_helper__WEBPACK_IMPORTED_MODULE_10__.initializeConnection)(services,configuration);case 136:if(!configuration.couchdb.ensureSecuritySettingsPresence){_context2.next=160;break}securityConfigurations=configuration.couchdb.security,_i2=0,_Object$entries2=Object.entries(securityConfigurations);case 139:if(!(_i2<_Object$entries2.length)){_context2.next=160;break}if(_Object$entries2$_i=_Object$entries2[_i2],databaseName=_Object$entries2$_i[0],securityObject=_Object$entries2$_i[1],"_default"!==databaseName){_context2.next=143;break}return _context2.abrupt("continue",157);case 143:return fullSecurityObject=securityObject,"_users"!==databaseName&&(fullSecurityObject.admins||(fullSecurityObject.admins={names:[],roles:[]}),securityConfigurations._default.admins&&(securityConfigurations._default.admins.names&&(fullSecurityObject.admins.names=securityConfigurations._default.admins.names.concat(null!==(_fullSecurityObject$a=fullSecurityObject.admins.names)&&void 0!==_fullSecurityObject$a?_fullSecurityObject$a:[])),securityConfigurations._default.admins.roles&&(fullSecurityObject.admins.roles=securityConfigurations._default.admins.roles.concat(null!==(_fullSecurityObject$a2=fullSecurityObject.admins.roles)&&void 0!==_fullSecurityObject$a2?_fullSecurityObject$a2:[]))),fullSecurityObject.members||(fullSecurityObject.members={names:[],roles:[]}),securityConfigurations._default.members&&(securityConfigurations._default.members.names&&(fullSecurityObject.members.names=securityConfigurations._default.members.names.concat(null!==(_fullSecurityObject$m=fullSecurityObject.members.names)&&void 0!==_fullSecurityObject$m?_fullSecurityObject$m:[])),securityConfigurations._default.members.roles&&(fullSecurityObject.members.roles=securityConfigurations._default.members.roles.concat(null!==(_fullSecurityObject$m2=fullSecurityObject.members.roles)&&void 0!==_fullSecurityObject$m2?_fullSecurityObject$m2:[])))),console.info('Apply security settings for database "'+databaseName+'":',(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(fullSecurityObject)),_context2.prev=146,_context2.next=149,clientnode__WEBPACK_IMPORTED_MODULE_3__.globalContext.fetch(urlPrefix+"/"+databaseName+"/_security",{body:JSON.stringify(fullSecurityObject),headers:_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({},headers,authorizationHeader),method:"PUT"});case 149:if(_response=_context2.sent,_response.ok){_context2.next=152;break}throw new Error(_response.statusText);case 152:_context2.next=157;break;case 154:_context2.prev=154,_context2.t11=_context2.catch(146),console.error('Security object for database "'+databaseName+"\" couldn't","be applied:",(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t11));case 157:_i2++,_context2.next=139;break;case 160:if(modelConfiguration=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.copy)(configuration.couchdb.model),delete modelConfiguration.property.defaultSpecification,delete modelConfiguration.entities,specialNames=modelConfiguration.property.name.special,idName=specialNames.id,revisionName=specialNames.revision,typeName=specialNames.type,models=(0,_helper__WEBPACK_IMPORTED_MODULE_10__.extendModels)(configuration.couchdb.model),!configuration.couchdb.model.updateValidation){_context2.next=229;break}return _context2.next=169,fs__WEBPACK_IMPORTED_MODULE_4__.promises.readFile(eval("require.resolve('./databaseHelper')"),{encoding:configuration.core.encoding,flag:"r"});case 169:databaseHelperCode=_context2.sent,_iterator6=_createForOfIteratorHelperLoose([{description:"Model specification",methodName:"validateDocumentUpdate",name:"validation",serializedParameter:JSON.stringify(modelConfiguration)+", "+JSON.stringify(models)},{description:"Authorization",methodName:"authorize",name:"authorization",serializedParameter:JSON.stringify((0,_helper__WEBPACK_IMPORTED_MODULE_10__.determineAllowedModelRolesMapping)(configuration.couchdb.model))+", '"+idName+"', '"+typeName+"', '"+specialNames.designDocumentNamePrefix+"'"}]);case 171:if((_step6=_iterator6()).done){_context2.next=186;break}_type=_step6.value,code="function(...parameters) {\n return require('helper')."+_type.methodName+"(...parameters.concat(["+_type.serializedParameter+"]))\n}",_context2.prev=174,new Function("return "+code),_context2.next=181;break;case 178:throw _context2.prev=178,_context2.t12=_context2.catch(174),new Error("Generated "+_type.name+' code "'+code+"\" doesn't compile: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t12));case 181:return configuration.core.debug&&console.debug(_type.name+' code: \n\n"'+code+'" integrated.'),_context2.next=184,(0,_helper__WEBPACK_IMPORTED_MODULE_10__.ensureValidationDocumentPresence)(couchdb.connection,_type.name,{helper:databaseHelperCode,validate_doc_update:code},_type.description,!0,idName,revisionName,specialNames.designDocumentNamePrefix);case 184:_context2.next=171;break;case 186:_i3=0,_Object$entries3=Object.entries(models);case 187:if(!(_i3<_Object$entries3.length)){_context2.next=229;break}_Object$entries3$_i=_Object$entries3[_i3],modelName=_Object$entries3$_i[0],model=_Object$entries3$_i[1],_i4=0,_Object$entries4=Object.entries(model);case 190:if(!(_i4<_Object$entries4.length)){_context2.next=226;break}if(_Object$entries4$_i=_Object$entries4[_i4],_name2=_Object$entries4$_i[0],specification=_Object$entries4$_i[1],![specialNames.constraint.execution,specialNames.constraint.expression].includes(_name2)){_context2.next=208;break}_iterator7=_createForOfIteratorHelperLoose([].concat(specification));case 194:if((_step7=_iterator7()).done){_context2.next=206;break}if(constraint=_step7.value,!constraint.description){_context2.next=204;break}_context2.prev=197,new Function("return "+constraint.description),_context2.next=204;break;case 201:throw _context2.prev=201,_context2.t13=_context2.catch(197),new Error('Specified constraint description "'+constraint.description+'" for model "'+modelName+"\" doesn't compile: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t13));case 204:_context2.next=194;break;case 206:_context2.next=223;break;case 208:_iterator8=_createForOfIteratorHelperLoose(["conflictingConstraintExpression","conflictingConstraintExecution","constraintExpression","constraintExecution"]);case 209:if((_step8=_iterator8()).done){_context2.next=223;break}if(type=_step8.value,!(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.isObject)(specification)){_context2.next=221;break}if(_constraint=specification[type],null==_constraint||!_constraint.description){_context2.next=221;break}_context2.prev=214,new Function(_constraint.description),_context2.next=221;break;case 218:throw _context2.prev=218,_context2.t14=_context2.catch(214),new Error('Specified constraint description "'+_constraint.description+'" for model "'+modelName+'" in property "'+_name2+'" as "'+type+"\" doesn't compile: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t14));case 221:_context2.next=209;break;case 223:_i4++,_context2.next=190;break;case 226:_i3++,_context2.next=187;break;case 229:if(!configuration.couchdb.model.autoMigrationPath){_context2.next=329;break}return migrators={},_context2.next=233,(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.isDirectory)((0,path__WEBPACK_IMPORTED_MODULE_5__.resolve)(configuration.couchdb.model.autoMigrationPath));case 233:if(!_context2.sent){_context2.next=286;break}return _context2.t15=_createForOfIteratorHelperLoose,_context2.next=237,(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.walkDirectoryRecursively)((0,path__WEBPACK_IMPORTED_MODULE_5__.resolve)(configuration.couchdb.model.autoMigrationPath),configuration.couchdb.debug?clientnode__WEBPACK_IMPORTED_MODULE_3__.NOOP:function(e){return!["debug","deprecated"].includes(e.name)});case 237:_context2.t16=_context2.sent,_iterator9=(0,_context2.t15)(_context2.t16);case 239:if((_step9=_iterator9()).done){_context2.next=286;break}if(file=_step9.value,extension=(0,path__WEBPACK_IMPORTED_MODULE_5__.extname)(file.name),_name3=(0,path__WEBPACK_IMPORTED_MODULE_5__.basename)(file.name,extension),".json"!==extension){_context2.next=276;break}return documents=void 0,_context2.prev=245,_context2.t17=[],_context2.t18=JSON,_context2.next=250,fs__WEBPACK_IMPORTED_MODULE_4__.promises.readFile(file.path,{encoding:configuration.core.encoding,flag:"r"});case 250:_context2.t19=_context2.sent,_context2.t20=_context2.t18.parse.call(_context2.t18,_context2.t19),documents=_context2.t17.concat.call(_context2.t17,_context2.t20),_context2.next=258;break;case 255:throw _context2.prev=255,_context2.t21=_context2.catch(245),new Error('Parsing document "'+file.path+'" to include by automigration of has failed: '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t21));case 258:1===documents.length&&(documents[0][idName]||(documents[0][idName]=_name3),documents[0][revisionName]||(documents[0][revisionName]="0-upsert")),_iterator10=_createForOfIteratorHelperLoose(documents);case 260:if((_step10=_iterator10()).done){_context2.next=274;break}return document=_step10.value,_context2.prev=262,_context2.next=265,couchdb.connection.put(document);case 265:_context2.next=271;break;case 267:throw _context2.prev=267,_context2.t22=_context2.catch(262),null!=(_forbidden=_context2.t22.forbidden)&&_forbidden.startsWith("NoChange:")&&console.info('Including document "'+document[idName]+'"',"of type",'"'+document[typeName]+"\" hasn't","changed existing document."),new Error('Migrating document "'+document[idName]+'" of type "'+document[typeName]+'" has failed: '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t22));case 271:console.info('Including document "'+document[idName]+'" of','type "'+document[typeName]+'" was',"successful.");case 272:_context2.next=260;break;case 274:_context2.next=284;break;case 276:if(![".js"].includes((0,path__WEBPACK_IMPORTED_MODULE_5__.extname)(file.name))){_context2.next=280;break}migrators[file.path]=eval("require('"+file.path+"')").default,_context2.next=284;break;case 280:if(![".mjs"].includes((0,path__WEBPACK_IMPORTED_MODULE_5__.extname)(file.name))){_context2.next=284;break}return _context2.next=283,eval("import('"+file.path+"')");case 283:migrators[file.path]=_context2.sent.default;case 284:_context2.next=239;break;case 286:return _context2.t23=_createForOfIteratorHelperLoose,_context2.next=289,couchdb.connection.allDocs({include_docs:!0});case 289:_context2.t24=_context2.sent.rows,_iterator11=(0,_context2.t23)(_context2.t24);case 291:if((_step11=_iterator11()).done){_context2.next=329;break}if(retrievedDocument=_step11.value,"string"==typeof retrievedDocument.id&&retrievedDocument.id.startsWith(configuration.couchdb.model.property.name.special.designDocumentNamePrefix)){_context2.next=327;break}_document=retrievedDocument.doc,newDocument=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.copy)(_document),newDocument[configuration.couchdb.model.property.name.special.strategy]="migrate",_iterator12=_createForOfIteratorHelperLoose(Object.keys(migrators).sort());case 298:if((_step12=_iterator12()).done){_context2.next=311;break}_name4=_step12.value,_result=null,_context2.prev=301,_result=migrators[_name4](newDocument,_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({},clientnode__WEBPACK_IMPORTED_MODULE_3__.UTILITY_SCOPE,{configuration,databaseHelper:_databaseHelper__WEBPACK_IMPORTED_MODULE_11___default(),idName,typeName,migrators,models,modelConfiguration,selfFilePath:_name4,services})),_context2.next=308;break;case 305:throw _context2.prev=305,_context2.t25=_context2.catch(301),new Error('Running migrater "'+_name4+'" in document '+(0,_helper__WEBPACK_IMPORTED_MODULE_10__.mayStripRepresentation)(_document,configuration.couchdb.maximumRepresentationTryLength,configuration.couchdb.maximumRepresentationLength)+'" failed: '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t25));case 308:_result&&(newDocument=_result,console.info('Running migrater "'+_name4+'" for document','"'+newDocument[idName]+'" (of type','"'+newDocument[typeName]+'") was successful.'));case 309:_context2.next=298;break;case 311:if(result=couchdb.validateDocument(newDocument,{checkPublicModelType:!0,oldDocument:_document}),!0===result){_context2.next=318;break}if(!Object.prototype.hasOwnProperty.call(result,"forbidden")){_context2.next=317;break}console.warn('Document "'+(0,_helper__WEBPACK_IMPORTED_MODULE_10__.mayStripRepresentation)(_document,configuration.couchdb.maximumRepresentationTryLength,configuration.couchdb.maximumRepresentationLength)+"\" doesn't satisfy its schema (and can not be","migrated automatically): "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(result)),_context2.next=318;break;case 317:throw result;case 318:return _context2.prev=318,_context2.next=321,couchdb.connection.put(newDocument);case 321:_context2.next=326;break;case 323:throw _context2.prev=323,_context2.t26=_context2.catch(318),new Error('Replacing auto migrated document "'+newDocument[idName]+'" has failed: '+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t26));case 326:console.info('Auto migrating document "'+newDocument[idName]+'" was',"successful.");case 327:_context2.next=291;break;case 329:return _context2.next=331,(0,_helper__WEBPACK_IMPORTED_MODULE_10__.removeDeprecatedIndexes)(couchdb.connection,models,configuration.couchdb.model);case 331:return _context2.next=333,couchdb.connection.getIndexes();case 333:if(genericIndexes=_context2.sent.indexes.filter((function(e){return e.name.endsWith("-GenericIndex")})),!configuration.couchdb.createGenericFlatIndex||!configuration.couchdb.model.autoMigrationPath&&0!==genericIndexes.length){_context2.next=362;break}_i5=0,_Object$entries5=Object.entries(models);case 336:if(!(_i5<_Object$entries5.length)){_context2.next=362;break}if(_Object$entries5$_i=_Object$entries5[_i5],_modelName=_Object$entries5$_i[0],_model=_Object$entries5$_i[1],!new RegExp(configuration.couchdb.model.property.name.typePattern.public).test(_modelName)){_context2.next=359;break}return _context2.next=341,couchdb.connection.createIndex({index:{ddoc:_modelName+"-GenericIndex",fields:[typeName],name:_modelName+"-GenericIndex"}});case 341:_iterator13=_createForOfIteratorHelperLoose((0,_helper__WEBPACK_IMPORTED_MODULE_10__.determineGenericIndexablePropertyNames)(configuration.couchdb.model,_model));case 342:if((_step13=_iterator13()).done){_context2.next=359;break}propertyName=_step13.value,_name5=_modelName+"-"+propertyName+"-GenericIndex",found=!1,_iterator14=_createForOfIteratorHelperLoose(genericIndexes);case 347:if((_step14=_iterator14()).done){_context2.next=354;break}if(index=_step14.value,index.name!==_name5){_context2.next=352;break}return found=!0,_context2.abrupt("break",354);case 352:_context2.next=347;break;case 354:if(!found){_context2.next=357;break}return _context2.next=357,couchdb.connection.createIndex({index:{ddoc:_name5,fields:[typeName,propertyName],name:_name5}});case 357:_context2.next=342;break;case 359:_i5++,_context2.next=336;break;case 362:_i6=0,_Object$entries6=Object.entries(configuration.couchdb.materializedViews);case 363:if(!(_i6<_Object$entries6.length)){_context2.next=382;break}_Object$entries6$_i=_Object$entries6[_i6],id=_Object$entries6$_i[0],viewConfiguration=_Object$entries6$_i[1],_viewDocument={},_viewDocument[specialNames.type]=id,_viewDocument[specialNames.id]=id,viewDocument=_viewDocument,_i7=0,_Object$entries7=Object.entries(viewConfiguration);case 367:if(!(_i7<_Object$entries7.length)){_context2.next=376;break}return _Object$entries7$_i=_Object$entries7[_i7],_name6=_Object$entries7$_i[0],viewDataConfiguration=_Object$entries7$_i[1],_context2.next=371,couchdb.connection.find(viewDataConfiguration.query);case 371:rawData=_context2.sent,viewDataConfiguration.initialMapperExpression?(_result2=(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.evaluate)(viewDataConfiguration.initialMapperExpression,{data:rawData.docs}),_result2.error?console.warn("Could not execute initial expression",'"'+viewDataConfiguration.initialMapperExpression+'"','for property "'+_name6+'" in view document "'+id+'":',_result2.error):viewDocument[_name6]=_result2.result):viewDocument[_name6]=rawData.docs;case 373:_i7++,_context2.next=367;break;case 376:return console.info("Initialize view "+id+":",viewDocument),_context2.next=379,couchdb.connection.put(viewDocument);case 379:_i6++,_context2.next=363;break;case 382:if(!configuration.couchdb.model.triggerInitialCompaction){_context2.next=391;break}return _context2.prev=383,_context2.next=386,couchdb.connection.compact();case 386:_context2.next=391;break;case 388:_context2.prev=388,_context2.t27=_context2.catch(383),console.warn("Initial database compaction has failed: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(_context2.t27));case 391:return _context2.abrupt("return",{couchdb:promise});case 392:case"end":return _context2.stop()}}),_callee2,null,[[19,27,45,48],[31,36,39,42],[53,58,73,76],[62,67],[91,97],[104,112],[116,121],[146,154],[174,178],[197,201],[214,218],[245,255],[262,267],[301,305],[318,323],[383,388]])})));return function(e){return _ref3.apply(this,arguments)}}(),postLoadService=function(e){var t=e.configuration.couchdb,r=e.pluginAPI,n=e.services.couchdb,o=t.model.property.name.special,a=0,i=new clientnode__WEBPACK_IMPORTED_MODULE_3__.Semaphore(t.numberOfParallelChangesRunner),_=function(){var c=_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().mark((function c(){var u,s,l,p,d,f,m,E,b,O,v,h,y,g,P,D;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().wrap((function(c){for(;;)switch(c.prev=c.next){case 0:if(n.changesStream&&n.changesStream.cancel(),s=t.changesStream,void 0!==n.lastChangesSequenceIdentifier&&(s.since=n.lastChangesSequenceIdentifier),console.info("Initialize changes stream since",'"'+String(s.since)+'".'),Object.keys(t.materializedViews).length){for(l=t.updateMaterializedViewsChangesStream,void 0!==n.lastUpdateMaterializedViewsChangesSequenceIdentifier&&(l.since=n.lastUpdateMaterializedViewsChangesSequenceIdentifier),p={$and:[]},d=0,f=Object.entries(t.materializedViews);d<f.length;d++)for(E=f[d],b=E[0],O=E[1],v=[],p.$and.push(((m={})[o.id]={$ne:b},m),{$or:v}),h=0,y=Object.values(O);h<y.length;h++)g=y[h],v.push(g.query.selector);l.selector=p,console.info('Initialize changes stream for views since "'+String(l.since)+'".'),n.updateMaterializedViewsChangesStream=n.connection.changes(l)}return n.changesStream=n.connection.changes(s),P=function(){var r=_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().mark((function r(o){var i;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!((a+=1)>t.changesStreamReinitializer.retries)){r.next=9;break}return console.warn("Observing changes feed throws an error for",String(a)+" times through:",(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(o)+" Restarting database server and","reinitialize changes stream..."),a=0,n.changesStream.cancel(),r.next=7,n.server.restart(e);case 7:r.next=13;break;case 9:return i=Math.min(Math.pow(t.changesStreamReinitializer.retryWaitingFactorInSeconds,a),t.changesStreamReinitializer.maximumRetryWaitingTimeInSeconds),console.warn("Observing changes feed throws an error for",String(a)+" of",String(t.changesStreamReinitializer.retries),"allowed times through: "+(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.represent)(o),"Reinitializing changes stream in",String(i)+" seconds..."),r.next=13,(0,clientnode__WEBPACK_IMPORTED_MODULE_3__.timeout)(1e3*i);case 13:_();case 14:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}(),n.changesStream.on("error",P),n.updateMaterializedViewsChangesStream&&n.updateMaterializedViewsChangesStream.on("error",P),c.next=11,r.callStack(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({},e,{data:{changesStream:n.changesStream,updateMaterializedViewsChangesStream:n.updateMaterializedViewsChangesStream},hook:"couchdbInitializeChangesStream"}));case 11:console.info("Changes stream initialized."),n.changesStream.on("change",_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().mark((function t(o){return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return a=0,t.prev=1,t.next=4,i.acquire();case 4:return t.next=6,r.callStack(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({},e,{data:o,hook:"couchdbChange"}));case 6:n.lastChangesSequenceIdentifier=o.seq,t.next=12;break;case 9:t.prev=9,t.t0=t.catch(1),console.error("An error occurred during on change database hook:",t.t0);case 12:return t.prev=12,i.release(),t.finish(12);case 15:case"end":return t.stop()}}),t,null,[[1,9,12,15]])})))),D=new clientnode__WEBPACK_IMPORTED_MODULE