forked from projects/fipamo
1 line
813 KiB
Text
1 line
813 KiB
Text
{"version":3,"sources":["../../../../brain/tools/events/EventEmitter.js","../../../../brain/tools/events/DataEvent.js","../../../../brain/tools/utilities/DataUtils.js","../../../../brain/tools/effects/Animate.js","../../../../brain/tools/utilities/StringUtils.js","actions/PostActions.js","../../../../brain/tools/events/EditorEvent.js","../../../../node_modules/tiny-date-picker/dist/tiny-date-picker.js","../../../../brain/tools/utilities/DateUtils.js","../../src/mirror.js","../../src/utils.js","../../src/input.js","../../src/editable.js","../../src/main.js","../../../../brain/tools/ui/TextEditor.js","controllers/PostEditor.js","controllers/DisplayManager.js","../../../../node_modules/argsarray/index.js","../../../../node_modules/immediate/lib/browser.js","../../../../../../.nvm/versions/node/v8.12.0/lib/node_modules/parcel-bundler/node_modules/events/events.js","../../../../node_modules/inherits/inherits_browser.js","../../../../node_modules/spark-md5/spark-md5.js","../../../../node_modules/pouchdb/node_modules/uuid/lib/rng-browser.js","../../../../node_modules/pouchdb/node_modules/uuid/lib/bytesToUuid.js","../../../../node_modules/pouchdb/node_modules/uuid/v1.js","../../../../node_modules/pouchdb/node_modules/uuid/v4.js","../../../../node_modules/pouchdb/node_modules/uuid/index.js","../../../../node_modules/vuvuzela/index.js","../../../../../../.nvm/versions/node/v8.12.0/lib/node_modules/parcel-bundler/node_modules/process/browser.js","../../../../node_modules/pouchdb/lib/index-browser.es.js","Base.js","Start.js"],"names":["EventEmitter","listeners","Map","label","callback","has","set","get","push","isFunction","obj","index","length","reduce","i","listener","splice","args","forEach","REQUEST_GOOD","REQUEST_LAME","IMG_REQUEST_GOOD","IMG_REQUEST_LAME","SETTINGS_LOADED","HTML_LOADED","ARCHIVES_JSON_LOADED","ARCHIVES_PAGE_LOADED","ARCHIVES_ENTRY_LOADED","PROJECT_UPDATED","PROJECT_ADDED","PROJECTS_SORTED","POST_IMAGE_ADDED","POST_ERROR","POST_ADDED","POST_UPDATED","POST_DELETED","DataEvent","REQUEST_TYPE_POST","REQUEST_TYPE_GET","REQUEST_TYPE_PUT","REQUEST_TYPE_DELETE","CONTENT_TYPE_JSON","CONTENT_TYPE_FORM","DataUtils","self","requestURL","eventType","requestType","contentType","requestData","Promise","resolve","reject","request","XMLHttpRequest","upload","onprogress","handleLoadProgress","open","onload","e","status","setRequestHeader","send","JSON","stringify","url","responseType","response","Error","statusText","onerror","src","body","document","querySelector","myImage","Image","crossOrigin","imgLoad","then","imageURL","window","URL","createObjectURL","percentComplete","Math","ceil","loaded","total","Animate","properties","animation","anime","StringUtils","string","clean","replace","toLowerCase","quote_style","optTemp","noquotes","toString","OPTS","concat","ENT_HTML_QUOTE_SINGLE","PostActions","folio","dataUtils","edit","uploadFiles","postData","FormData","files","file","type","match","append","name","txt","createElement","innerHTML","getElementById","value","cleanString","getAttribute","postURL","postEventType","postID","catch","err","EDITOR_DELETE","EDITOR_UPLOAD_POST_IMAGE","EDITOR_SAVE","EDITOR_UPDATE","EditorEvent","DateUtils","time","Date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","getTime","seconds","date","rawdate","day","String","getUTCDate","month","getUTCMonth","year","getUTCFullYear","hour","getUTCHours","minute","getUTCMinutes","getUTCSeconds","millisecond","getUTCMilliseconds","offset","getTimezoneOffset","attributes","createMirror","element","html","mirror","mirrorCss","css","tagName","attr","getComputedStyle","initialize","styles","keys","style","key","parentNode","insertBefore","nextSibling","rect","marker","ownerDocument","boundingRect","offsetLeft","offsetTop","offsetHeight","removeChild","isContentEditable","contentEditable","getContext","settings","customPos","iframe","noShadowCaret","contentWindow","contentDocument","getOffset","ctx","win","doc","getBoundingClientRect","docEl","documentElement","scrollLeft","pageXOffset","scrollTop","pageYOffset","top","left","isObject","createInputCaret","getPos","selectionStart","setPos","pos","setSelectionRange","elementOffset","position","getPosition","height","format","val","undefined","startRange","slice","endRange","createEditableCaret","sel","getSelection","found","find","parent","childNodes","node","nodeType","range","createRange","setStart","removeAllRanges","addRange","getRange","hasCustomPos","endOffset","endContainer","clonedRange","cloneRange","fixedPosition","setEnd","width","detach","shadowCaret","createTextNode","insertNode","selectNode","clientTop","clientLeft","inputOffset","rangeCount","getRangeAt","selectNodeContents","createCaret","options","caret","TextEditor","textEditor","scrollLimit","hljs","initHighlightingOnLoad","dateUtils","fixLimit","caretPos","setInputs","addEventListener","f","refresh","editorButtons","querySelectorAll","handleEditorOption","inputType","spiffed","highlight","innerText","temp","data","classList","add","remove","setTimeout","pulled","deleteContents","preventDefault","target","id","emitEvent","PostEditor","anim","editor","addListener","handleEditorOptions","handlePostImageAdd","mode","start","object","targets","duration","opacity","easing","complete","display","visibility","handleDragOver","handleDrop","handleClicked","click","optionButtons","handlePostOptions","currentOption","active","setAttribute","submitPost","note","parse","notify","message","location","console","log","confirm","deletePost","stopPropagation","dataTransfer","dropEffect","reader","FileReader","theFile","image","result","title","escape","span","join","appendChild","readAsDataURL","DisplayManager","currentDisplay","urlPieces","split","chooseDisplay","section","page","_events","_maxListeners","module","exports","prototype","defaultMaxListeners","setMaxListeners","n","isNumber","isNaN","TypeError","emit","er","handler","len","error","arguments","context","isUndefined","call","Array","apply","m","newListener","warned","trace","on","once","fired","g","removeListener","list","removeAllListeners","ret","listenerCount","evlistener","emitter","arg","process","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","clearTimeout","runTimeout","fun","runClearTimeout","queue","draining","currentQueue","queueIndex","cleanUpNextTick","drainQueue","timeout","run","nextTick","Item","array","browser","env","argv","version","versions","noop","off","prependListener","prependOnceListener","binding","cwd","chdir","dir","umask","isBinaryObject","ArrayBuffer","Blob","cloneArrayBuffer","buff","byteLength","targetArray","Uint8Array","sourceArray","cloneBinaryObject","size","webkitSlice","funcToString","Function","objectCtorString","Object","isPlainObject","proto","getPrototypeOf","Ctor","constructor","clone","newObject","isArray","toISOString","hasOwnProperty","called","toPromise","func","usedCB","pop","promise","fulfill","resp","mesg","logApiCall","logArgs","origCallback","res","responseArgs","adapterFun","_closed","_destroyed","taskqueue","isReady","addTask","failed","mangle","unmangle","substring","Map$1","_store","mangled","delete","cb","defineProperty","Set$1","supportsMapAndSet","Symbol","Set","prop","getOwnPropertyDescriptor","species","ExportedSet","ExportedMap","pick","arr","MAX_NUM_CONCURRENT_REQUESTS","identityFunction","x","formatResultForOpenRevsGet","ok","bulkGet","db","opts","requests","docs","requestsById","numDocs","numDone","perDocResults","collapseResultsAndFinish","results","info","checkDone","gotResult","docIndex","allRequests","nextBatch","upTo","min","batch","processBatch","docId","j","docIdx","docRequests","docOpts","open_revs","map","rev","filter","formatResult","param","hasLocal","localStorage","setItem","getItem","hasLocalStorage","Changes","attachBrowserEvents","_listeners","dbName","inprogress","eventFunction","changesOpts","onError","changes","c","seq","since","cancelled","onChange","notifyLocalWindows","guardedConsole","method","randomNumber","max","maxTimeout","parseInt","ratio","random","defaultBackOff","explainError","str","assign","to","nextSource","nextKey","$inject_Object_assign","PouchError","reason","UNAUTHORIZED","MISSING_BULK_DOCS","MISSING_DOC","REV_CONFLICT","INVALID_ID","MISSING_ID","RESERVED_ID","NOT_OPEN","UNKNOWN_ERROR","BAD_ARG","INVALID_REQUEST","QUERY_PARSE_ERROR","DOC_VALIDATION","BAD_REQUEST","NOT_AN_OBJECT","DB_MISSING","IDB_ERROR","WSQ_ERROR","LDB_ERROR","FORBIDDEN","INVALID_REV","FILE_EXISTS","MISSING_STUB","INVALID_URL","createError","CustomPouchError","p","generateErrorFromResponse","tryFilter","req","msg","filterChange","hasFilter","query","query_params","change","filterReturn","include_docs","attachments","att","_attachments","stub","flatten","arrs","invalidIdError","test","isRemote","_remote","ee","parseDesignDocFunctionName","s","parts","normalizeDesignDocFunctionName","normalized","qName","qParser","parser","parseUri","exec","uri","encoded","indexOf","decodeURIComponent","$0","$1","$2","scopeEval","source","scope","values","upsert","diffFun","docRev","_rev","newDoc","updated","_id","tryAndPut","put","thisAtob","atob","thisBtoa","btoa","createBlob","Builder","BlobBuilder","MSBlobBuilder","MozBlobBuilder","WebKitBlobBuilder","builder","getBlob","binaryStringToArrayBuffer","bin","buf","charCodeAt","binStringToBluffer","binString","b64ToBluffer","b64","arrayBufferToBinaryString","buffer","binary","bytes","fromCharCode","readAsBinaryString","blob","hasBinaryString","onloadend","readAsArrayBuffer","blobToBinaryString","blobOrBuffer","blobToBase64","base64","setImmediateShim","global","setImmediate","MD5_CHUNK_SIZE","rawToBase64","raw","sliceBlob","end","appendBlob","arrayBuffer","appendString","appendBinary","binaryMd5","inputIsString","chunkSize","chunks","currentChunk","Md5","next","loadNextChunk","done","destroy","stringMd5","hash","rev$$1","deterministic_revs","clonedDoc","uuidV4","v4","_rev_tree","uuid","winningRev","metadata","winningId","winningPos","winningDeleted","toVisit","rev_tree","tree","ids","branches","deleted","traverseRevTree","revs","newCtx","sortByPos","a","b","collectLeaves","leaves","isLeaf","acc","sort","reverse","collectConflicts","conflicts","leaf","compactTree","revHash","rootToLeaf","paths","history","sortByPos$1","binarySearch","item","comparator","low","high","mid","insertSorted","idx","pathToTree","path","numStemmed","root","currentLeaf","compareTree","mergeTree","in_tree1","in_tree2","tree1","tree2","merged","doMerge","dontExpand","restree","branch","t1","t2","diff","candidateParents","trees","parentIdx","elements","elementsLen","el","stem","depth","stemmedRevs","stemmed","merge","newTree","revExists","splitRev","targetPos","targetId","getTrees","isDeleted","isLocalId","latest","historyNode","historyRev","l","Changes$1","tryCatchInChangeListener","pending","lastSeq","onDestroy","cancel","isCancelled","bind","validateChanges","processChange","changeList","_conflicts","PouchDB","_changesFilterPlugin","validate","doChanges","continuous","live","update_seq","normalize","shouldFilter","descending","limit","newPromise","_changes","compare","right","yankError","cleanDocs","_deleted","atts","compareByIdThenRev","idCompare","aStart","_revisions","bStart","computeHeight","edges","prnt","from","edge","allDocsKeysParse","skip","doNextCompaction","task","_compactionQueue","last_seq","_compact","shift","attachmentNameError","charAt","AbstractPouchDB","post","bulkDocs","_putLocal","_removeLocal","force","transformForceOptionToNewEditsOption","putDoc","oldRevId","oldRevNum","newRevNum","newRevId","new_edits","_put","putAttachment","attachmentId","api","createAttachment","prevrevpos","content_type","revpos","removeAttachment","docOrId","optsOrRev","was_delete","revsDiff","count","missing","addToMissing","revId","processDoc","missingForId","_getRevisionTree","missingObj","compactDocument","maxHeight","revTree","candidates","_doCompaction","compact","return_docs","promises","row","onComplete","all","deltaFunc","_getLocal","finishOpenRevs","existing","_get","revs_info","splittedRev","revNo","currentPath","hashIndex","hashFoundAtRevPos","indexOfRev","howMany","_revs_info","_getAttachment","getAttachment","allDocs","start_key","startkey","end_key","endkey","incompatibleOpt","_allDocs","close","_close","_info","db_name","auto_compaction","adapter","_type","attachmentError","_bulkDocs","registerDependentDatabase","dependentDb","depDB","__opts","dependentDbs","usePrefix","use_prefix","destroyDb","_destroy","localDoc","deletedMap","trueName","RegExp","prefix","TaskQueue","execute","fail","ready","parseAdapter","adapters","preferredAdapters","adapterName","prepareForDestruction","onDestroyed","from_constructor","onClosed","prefixedName","backend","_adapter","valid","AbortController","abort","f$1","fetch","h","Headers","eventEmitter","setUpEventEmitter","Pouch","destructListeners","_destructionListeners","onConstructorRef","onConstructorUnref","dbList","onConstructorDestroyed","addToPreferredAdapters","plugin","__defaults","defaults","defaultOpts","PouchAlt","getFieldFromDoc","parsedField","compare$1","parseField","fieldName","fields","current","ch","combinationFields","isCombinationalField","field","getKey","getValue","mergeAndedSelectors","selectors","selector","matcher","$eq","fieldMatchers","operator","mergeGtGte","mergeLtLte","mergeNe","mergeEq","$gte","$gt","$lte","$lt","$ne","massageSelector","input","wasAnded","orOrNor","subSelector","pad","padWith","upToLength","padding","targetLength","padLeft","MIN_MAGNITUDE","MAGNITUDE_DIGITS","SEP","collate","normalizeKey","ai","collationIndex","bi","stringCollate","arrayCollate","objectCollate","Infinity","origKey","toJSON","k","indexify","numToIndexableString","toIndexableString","objKey","zero","parseNumber","originalIdx","num","neg","numAsString","magAsString","magnitude","parseFloat","stack","metaStack","lastMetaElement","lastElementIndex","parseIndexableString","parsedNum","parsedStr","arrayElement","objElement","ak","bk","expFormat","toExponential","magForComparison","magString","factor","abs","factorStr","toFixed","createFieldSorter","getFieldValuesAsArray","sorting","docFieldValue","aRow","bRow","aFieldValues","bFieldValues","collation","filterInMemoryFields","rows","requestDef","inMemoryFields","rowFilter","fieldSorter","every","matchCominationalSelector","matchSelector","userOperator","userValue","some","orMatchers","matchers","fieldExists","fieldIsNotUndefined","modField","divisor","mod","arrayContainsValue","arrayContainsAllValues","arraySize","regexMatch","re","typeMatch","neValue","matchesSelector","rowsMatched","evalFilter","evalView","code","filterName","view","changesHandler","doc_ids","viewName","ddoc","mapFun","views","filterFun","filters","applyChangesFilterPlugin","toObject","reservedWords","dataWords","parseRevisionInfo","makeRevTreeFromRevisions","revisions","revisionIds","parseDoc","newEdits","dbOpts","nRevNum","revInfo","specialKey","parseBase64","preprocessString","blobType","asBinary","digest","preprocessBlob","md5","preprocessAttachment","preprocessAttachments","docInfos","docv","overallErr","docInfo","recv","processedAttachment","updateDoc","revLimit","prev","writeDoc","previousWinningRev","previouslyDeleted","isRoot","inConflict","newRev","rev_map","winningRev$$1","winningRevIsDeleted","delta","newRevIsDeleted","rootIsMissing","processDocs","fetchedDocs","tx","overallCallback","insertDoc","resultsIdx","idsToDocs","docsDone","docsToDo","checkAllDocsDone","currentDoc","docWritten","nextDoc","ADAPTER_VERSION","DOC_STORE","BY_SEQ_STORE","ATTACH_STORE","ATTACH_AND_SEQ_STORE","META_STORE","LOCAL_STORE","DETECT_BLOB_SUPPORT_STORE","safeJsonParse","vuvuzela","safeJsonStringify","json","idbError","evt","encodeMetadata","deletedOrLocal","decodeMetadata","storedObject","decodeDoc","_doc_id_rev","lastIndexOf","readBlobData","asBlob","fetchAttachmentsIfNecessary","txn","fetchAttachment","attObj","objectStore","onsuccess","postProcessAttachments","attNames","compactRevs","possiblyOrphanedDigests","seqStore","attStore","attAndSeqStore","deleteOrphanedAttachments","countReq","IDBKeyRange","bound","cursor","openCursor","only","event","digestSeq","primaryKey","continue","openTransactionSafely","idb","stores","transaction","idbBulkDocs","docStore","bySeqStore","attachStore","attachAndSeqStore","metaStore","docInfoError","metaDoc","allDocsProcessed","docCountDelta","preconditionErrored","_meta","blobSupport","startTransaction","txnResult","onabort","ontimeout","oncomplete","updateDocCountIfReady","verifyAttachments","fetchExistingDocs","onAllDocsProcessed","idbProcessDocs","revs_limit","docCount","numFetched","readMetadata","verifyAttachment","finish","digests","filename","attErr","isUpdate","hasAttachments","writeAttachments","finishDoc","afterPutDoc","revsToDelete","metadataToStore","metaDataReq","afterPutMetadata","afterPutDocError","getKeyReq","putReq","insertAttachmentMappings","collectResults","attachmentSaved","saveAttachment","attsAdded","attsToAdd","newAtt","runBatchedCursor","keyRange","batchSize","onBatch","useGetAll","getAll","getAllKeys","keysBatch","valuesBatch","pseudoCursor","onGetAll","onGetAllKeys","continuePseudoCursor","lastKey","newKeyRange","upper","upperOpen","lowerBound","onCursor","onSuccess","allDocsKeys","createKeyRange","inclusiveEnd","upperBound","idbAllDocs","inclusive_end","keyRangeError","onTxnComplete","docIdRevIndex","updateSeq","getMaxUpdateSeq","maxKey","fetchDocAsynchronously","onGetDoc","allDocsInner","batchValues","batchValue","batchKeys","onResultsReady","returnVal","total_rows","checkBlobSupport","blob$$1","matchedChrome","navigator","userAgent","matchedEdge","countDocs","running","tryCode","applyNext","enqueueTask","action","runAction","runCallback","runNext","docIds","numResults","docIdsToMetadata","winningDocs","metadatas","processMetadataAndWinningDoc","winningDoc","filtered","onBatchDone","fetchWinningDocAndMetadata","onGetMetadata","docIdRev","objectStores","cachedDBs","blobSupportPromise","openReqList","IdbPouch","thisCallback","init","createSchema","createObjectStore","keyPath","autoIncrement","createIndex","unique","addDeletedOrLocalIndex","createLocalStoreSchema","migrateLocalStore","localStore","local","seqCursor","addAttachAndSeqStore","migrateAttsAndSeqs","digestMap","migrateMetadata","decodeMetadataCompat","fetchMetadataSeq","metadataSeq","onGetMetadataSeq","instanceId","idb_bulkDocs","reqOpts","idb_get","attachId","attachment","blobData","idb_info","doc_count","idb_attachment_format","idb_allDocs","idbChanges","oldRev","oStore","oldDoc","openReq","indexedDB","deleteDatabase","cached","onupgradeneeded","oldVersion","currentTarget","migrations","migration","onversionchange","storedMetaDoc","completeSetup","storeMetaDocIfReady","instanceKey","IDBPouch","pool","promiseFactories","doNext","runNextBatch","thisErr","CHANGES_BATCH_SIZE","MAX_SIMULTANEOUS_REVS","CHANGES_TIMEOUT_BUFFER","DEFAULT_HEARTBEAT","supportsBulkGetMap","readAttachmentsAsBlobOrBuffer","encodeDocId","encodeURIComponent","preprocessAttachments$1","hasUrlPrefix","protocol","getHost","substr","user","password","auth","username","genDBUrl","genUrl","pathDel","host","port","paramsToStr","params","shouldCacheBust","ua","isIE","isTrident","isEdge","isGET","HttpPouch","dbUrl","ourFetch","headers","nAuth","token","unescape","now","fetchFun","adapterFun$$1","setup","fetchJSON","v","setupPromise","skip_setup","uuid$$1","ping","compact_running","interval","doBulkGet","doBulkGetShim","numBatches","onResult","batchNum","subOpts","supportsBulkGet","fetchAttachments","filenames","fetchData","encodeAttachmentId","fetchAllAttachments","docOrDocs","paramStr","batch_size","heartbeat","requestTimeout","leftToFetch","feed","seq_interval","param_name","controller","lastFetchedSeq","aborted","fetchOpts","signal","fetched","raw_results_length","finished","HttpPouch$1","QueryParseError","captureStackTrace","NotFoundError","BuiltInError","promisedCallback","callbackify","fin","finalPromiseFactory","sequentialize","promiseFactory","that","uniq","theSet","mapToKeysArray","createBuiltInError","sum","jLen","jNum","evalFunctionWithEval","TaskQueue$1","createViewSignature","reduceFun","createView","sourceDB","temporary","localDocName","viewSignature","cachedViews","_cachedViews","promiseForView","depDbName","diffFunction","fullViewName","depDbs","lastSeqDoc","persistentQueues","tempViewQueue","CHANGES_BATCH_SIZE$1","parseViewName","isGenOne","emitError","createAbstractMapReduce","mapper","reducer","ddocValidator","tryMap","tryReduce","rereduce","output","sortByKeyThenValue","y","keyCompare","sliceResults","rowToDocId","postprocessAttachments","addHttpParam","paramName","asJson","coerceInteger","integerCandidate","asNumber","Number","coerceOptions","group_level","checkPositiveInteger","number","checkQueryParseError","startkeyName","endkeyName","group","optionName","httpQuery","MAX_URL_LENGTH","keysAsString","customQuery","_query","customViewCleanup","_viewCleanup","defaultsTo","getDocsToPersist","docIdsToChangesAndEmits","metaDocId","defaultMetaDoc","docData","indexableKeysToKeyValues","getMetaDoc","getKeyValueDocs","processKeyValueDocs","kvDocsRes","kvDocs","oldKeys","keyValue","newKeys","kvDoc","saveKeyValues","seqDocId","listOfDocsToPersist","docsToPersist","getQueue","updateView","updateViewInQueue","mapResults","currentSeq","processNextBatch","createDocIdsToChangesAndEmits","createIndexableKeysToKeyValues","emittedKeyValue","complexKey","reduceView","shouldGroup","groups","lvl","POSITIVE_INFINITY","last","groupKey","reduceTry","queryView","queryViewInQueue","totalRows","shouldReduce","fetchFromView","viewOpts","expectedKeys","parsedKeyAndDocId","onMapResultsReady","finalResults","allDocsRes","docIdsToDocs","fetchPromises","keyStart","keyEnd","httpViewCleanup","localViewCleanup","docsToViews","designDocName","viewsToStatus","ddocName","viewDBNames","statusIsGood","viewDBName","dbsToDelete","destroyPromises","queryPromised","createViewPromise","stale","abstractQuery","abstractViewCleanup","viewCleanup","builtInReduce","_sum","_count","_stats","sumsqr","_sumsqr","getBuiltIn","reduceFunString","origMap","builtIn","abstract","mapreduce","isGenOne$1","fileHasChanged","remoteDoc","getDocAttachments","getDocAttachmentsFromTargetOrSource","doCheckForLocalAttachments","createBulkGetOpts","diffs","missingRevs","missingRev","getDocs","state","resultDocs","getAllDocs","bulkGetOpts","bulkGetResponse","bulkGetInfo","Boolean","hasConflicts","fetchRevisionOneDocs","getRevisionOneDocs","returnResult","CHECKPOINT_VERSION","REPLICATOR","CHECKPOINT_HISTORY_SIZE","LOWEST_SEQ","updateCheckpoint","checkpoint","session","returnValue","session_id","replicator","unshift","Checkpointer","writeCheckpoint","updateTarget","updateSource","writeTargetCheckpoint","writeSourceCheckpoint","isForbiddenError","comparisons","targetDoc","sourceDoc","compareReplicationLogs","getCheckpoint","srcDoc","tgtDoc","compareReplicationHistory","sourceHistory","targetHistory","S","sourceRest","T","targetRest","sourceId","hasSessionId","sessionId","props","rest","floor","STARTING_BACK_OFF","backOff","retry","back_off_function","backOffSet","backoffTimeSet","current_back_off","removeBackOffSetter","removeBackOffTimeSet","sortObjectPropertiesByKey","queryParams","generateReplicationId","filterViewName","queryData","md5sum","replicate","batches","currentBatch","pendingBatch","writingCheckpoint","changesCompleted","replicationCompleted","batches_limit","changesPending","repId","checkpointer","changedDocs","start_time","docs_read","docs_written","doc_write_failures","errors","initCheckpointer","checkpointOpts","writeDocs","bulkOpts","completeReplication","errorsById","create","errorsNo","errorName","finishBatch","outResult","getChanges","onCheckpointError","getDiffs","getBatchDocs","got","startNextBatch","processPendingBatch","abortReplication","immediate","fatalError","end_time","onChangesComplete","onChangesError","abortChanges","_abortChanges","startChanges","_addedListeners","Replication","_readyCalled","cleanup","toPouch","PouchConstructor","replicateWrapper","replicateRet","srcPouch","targetPouch","Sync","sync","canceled","optsPush","optsPull","pull","pushPaused","pullPaused","pullChange","direction","pushChange","pushDenied","pullDenied","pushActive","pullActive","removed","removeAll","isChange","isDenied","isPaused","isActive","addOneListener","out","success","replication","replicateMethods","other","Base","admin","displayManager","loadSettings","remote","base"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAMA;;;AAGF;AACA;AACA;AACA,0BACA;AAAA;;AACI,SAAKC,SAAL,GAAiB,IAAIC,GAAJ,EAAjB;AACH,IACD;AACA;AACA;;;;;gCACYC,OAAOC,UAAU;AACzB,WAAKH,SAAL,CAAeI,GAAf,CAAmBF,KAAnB,KAA6B,KAAKF,SAAL,CAAeK,GAAf,CAAmBH,KAAnB,EAA0B,EAA1B,CAA7B;AACA,WAAKF,SAAL,CAAeM,GAAf,CAAmBJ,KAAnB,EAA0BK,IAA1B,CA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AAwB,aAAxB,EAAuCG,YAAvC,CAAoD,SAApD,CAAb;AACA,aAAO,IAAI3E,OAAJ,CAAY,UAAUC,OAAV,EAAmBC,MAAnB,EAA2B;AAC1CR,QAAAA,IAAI,CAACgE,SAAL,CAAevD,OAAf,CAAuB,sBAAsB2E,MAA7C,EAAqD5F,SAAS,CAACD,YAA/D,EAA6EE,4BAA7E,EAAgGK,4BAAhG,EACKsC,IADL,CACU,UAACZ,QAAD,EAAc;AAChBjB,UAAAA,OAAO,CAAC;AACJiB,YAAAA,QAAQ,EAARA;AADI,WAAD,CAAP;AAGH,SALL,EAKO6D,KALP,CAKa,UAACC,GAAD,EAAS;AACd9E,UAAAA,MAAM,CAAC;AACH8E,YAAAA,GAAG,EAAHA;AADG,WAAD,CAAN;AAGH,SATL;AAUH,OAXM,CAAP,CAHS,CAeT;AACH,MACD;AACA;AACA;;;;;;;;;;;;;;;;;;AClGG,IAAMC,aAAa,GAAG,cAAtB;;AACA,IAAMC,wBAAwB,GAAG,mBAAjC;;AACA,IAAMC,WAAW,GAAG,YAApB;;AACA,IAAMC,aAAa,GAAG,cAAtB;;;IAEDC;;;;eAaS,IAAIA,WAAJ;;;;;;AClBf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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AACA,cAAI/N,gBAAJ,GAAcwN,MAAd,CAAqB;AACjBC,YAAAA,OAAO,EAAEzO,QAAQ,CAACgD,cAAT,CAAwB,QAAxB,CADQ;AAEjB0L,YAAAA,QAAQ,EAAE,EAFO;AAGjBC,YAAAA,OAAO,EAAE,CAHQ;AAIjBC,YAAAA,MAAM,EAAE,eAJS;AAKjBC,YAAAA,QAAQ,EAAE,oBAAY;AAClB7O,cAAAA,QAAQ,CAACgD,cAAT,CAAwB,QAAxB,EAAkCwD,KAAlC,CAAwCsI,OAAxC,GAAkD,MAAlD;AACA9O,cAAAA,QAAQ,CAACgD,cAAT,CAAwB,QAAxB,EAAkCwD,KAAlC,CAAwCuI,UAAxC,GAAqD,QAArD;AACH;AARgB,WAArB;AAUH;AAlBgB,OAArB;AAoBH;;;kCAEauC,SAASC,MAAM;AACzB,WAAKL,cAAL,GAAsB,EAAtB;;AACA,cAAQI,OAAR;AACI,aAAK,OAAL;AACI,eAAKJ,cAAL,GAAsB,IAAIlD,mBAAJ,EAAtB;AACA;;AAEJ;AACI;AACA;AAPR;;AASA,WAAKO,KAAL;AAEH,MACD;AACA;AACA;;;;;;;;;ACnEJ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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O,OAAOA,GAAP,KAAe,QAAtB;AACD;;AAED,SAASlL,QAAT,CAAkBkL,GAAlB,EAAuB;AACrB,SAAO,OAAOA,GAAP,KAAe,QAAf,IAA2BA,GAAG,KAAK,IAA1C;AACD;;AAED,SAASnB,WAAT,CAAqBmB,GAArB,EAA0B;AACxB,SAAOA,GAAG,KAAK,KAAK,CAApB;AACD;;AC7SD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/uBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC7KA;AACA,IAAIC,OAAO,GAAGpC,MAAM,CAACC,OAAP,GAAiB,EAA/B,EAEA;AACA;AACA;AACA;;AAEA,IAAIoC,gBAAJ;AACA,IAAIC,kBAAJ;;AAEA,SAASC,gBAAT,GAA4B;AACxB,QAAM,IAAItU,KAAJ,CAAU,iCAAV,CAAN;AACH;;AACD,SAASuU,mBAAT,GAAgC;AAC5B,QAAM,IAAIvU,KAAJ,CAAU,mCAAV,CAAN;AACH;;AACA,aAAY;AACT,MAAI;AACA,QAAI,OAAO8N,UA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MAAZ;AACH,SAFD,EAEGnN,KAFH,CAES,UAAAC,GAAG,EAAE;AACVuM,UAAAA,OAAO,CAACC,GAAR,CAAYxM,GAAZ;AACH,SAJD,EAfJ,CAqBI;;AACA,QAAA,KAAI,CAAC+K,KAAL,GAtBJ,CAuBI;;AACH,OAzBD,EAyBGhL,KAzBH,CAyBS,UAACC,GAAD,EACT,CACI;AACH,OA5BD;AA6BH,MACD;AACA;AACA;;;;;;;;;;;ACxEJ;;;;AAEAxD,QAAQ,CAAC0M,gBAAT,CAA0B,kBAA1B,EAA8C,YAAW;AAErD,MAAIm/C,IAAI,GAAG,IAAIL,aAAJ,EAAX;AACH,CAHD,EAGG,KAHH","file":"dash.min.map","sourceRoot":"../../src/com","sourcesContent":["class EventEmitter\n{\n\n //--------------------------\n // constructor\n //--------------------------\n constructor()\n {\n this.listeners = new Map();\n }\n //--------------------------\n // methods\n //--------------------------\n addListener(label, callback) {\n this.listeners.has(label) || this.listeners.set(label, []);\n this.listeners.get(label).push(callback);\n }\n\n removeListener(label, callback) {\n var isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n\n var listeners = this.listeners.get(label),\n index;\n\n if (listeners && listeners.length) {\n index = listeners.reduce((i, listener, index) => {\n return (isFunction(listener) && listener === callback)\n ? i = index\n : i;\n }, -1);\n\n if (index > -1) {\n listeners.splice(index, 1);\n this.listeners.set(label, listeners);\n return true;\n }\n }\n return false;\n }\n\n emitEvent(label, ...args) {\n var listeners = this.listeners.get(label);\n if (listeners && listeners.length) {\n listeners.forEach((listener) => {\n listener(...args);\n });\n return true;\n }\n return false;\n }\n //--------------------------\n // event handlers\n //--------------------------\n}\nexport default EventEmitter\n","export const REQUEST_GOOD = 'requestGood';\nexport const REQUEST_LAME = 'requestLame';\nexport const IMG_REQUEST_GOOD = 'imgRequestGood';\nexport const IMG_REQUEST_LAME = 'imgRequestLame';\nexport const SETTINGS_LOADED = 'dataLoaded';\nexport const HTML_LOADED = 'htmlLoaded';\nexport const ARCHIVES_JSON_LOADED = 'archivesJSONLoaded';\nexport const ARCHIVES_PAGE_LOADED = 'archivesPAGELoaded';\nexport const ARCHIVES_ENTRY_LOADED = 'archivesEntryLoaded';\nexport const PROJECT_UPDATED = 'projectUpdated';\nexport const PROJECT_ADDED = 'projectAdded';\nexport const PROJECTS_SORTED = 'projectsSorted';\nexport const POST_IMAGE_ADDED = 'postImageAdded';\nexport const POST_ERROR = 'postError';\nexport const POST_ADDED = 'postAdded';\nexport const POST_UPDATED = 'postUpdated';\nexport const POST_DELETED = 'postImageAdded';\n\nclass DataEvent\n{\n\n //--------------------------\n // methods\n //--------------------------\n\n\n\n //--------------------------\n // event handlers\n //--------------------------\n}\nexport default new DataEvent\n","export const REQUEST_TYPE_POST = \"POST\";\nexport const REQUEST_TYPE_GET = \"GET\";\nexport const REQUEST_TYPE_PUT = \"PUT\";\nexport const REQUEST_TYPE_DELETE = \"DELETE\";\nexport const CONTENT_TYPE_JSON = 'json';\nexport const CONTENT_TYPE_FORM = 'x-www-form-urlencoded';\nimport EventEmitter from '../events/EventEmitter';\nimport * as DataEvent from '../events/DataEvent';\nclass DataUtils extends EventEmitter {\n //--------------------------\n // constructor\n //--------------------------\n constructor() {\n super();\n var self = this;\n }\n //--------------------------\n // methods\n //--------------------------\n request(requestURL, eventType, requestType = REQUEST_TYPE_GET, contentType = CONTENT_TYPE_JSON, requestData = null) {\n var self = this;\n return new Promise(function(resolve, reject) {\n var request = new XMLHttpRequest();\n request.upload.onprogress = self.handleLoadProgress;\n request.open(requestType, requestURL, true);\n request.onload = function(e) {\n if (request.status == 200) {\n resolve({\n request,\n eventType\n });\n } else {\n reject({\n request,\n eventType\n });\n }\n ;\n };\n if (requestType == REQUEST_TYPE_PUT || requestType == REQUEST_TYPE_POST) {\n switch (contentType) {\n case CONTENT_TYPE_JSON:\n request.setRequestHeader(\"Content-type\", \"application/\" + contentType);\n request.send(JSON.stringify(requestData));\n break;\n case CONTENT_TYPE_FORM:\n request.send(requestData);\n break;\n }\n } else {\n request.send();\n }\n })\n }\n imgLoad(url) {\n 'use strict';\n // Create new promise with the Promise() constructor;\n // This has as its argument a function with two parameters, resolve and reject\n return new Promise(function(resolve, reject) {\n // Standard XHR to load an image\n var request = new XMLHttpRequest();\n request.open('GET', url);\n request.responseType = 'blob';\n // When the request loads, check whether it was successful\n request.onload = function() {\n if (request.status === 200) {\n // If successful, resolve the promise by passing back the request response\n resolve(request.response);\n } else {\n // If it fails, reject the promise with a error message\n reject(new Error('Image didn\\'t load successfully; error code:' + request.statusText));\n }\n };\n request.onerror = function() {\n // Also deal with the case when the entire request fails to begin with\n // This is probably a network error, so reject the promise with an appropriate message\n reject(new Error('There was a network error.'));\n };\n // Send the request\n request.send();\n });\n }\n loadImage(src) {\n 'use strict';\n let self = this;\n return new Promise(function(resolve, reject) {\n // Get a reference to the body element, and create a new image object\n var body = document.querySelector('body'),\n myImage = new Image();\n myImage.crossOrigin = \"\"; // or \"anonymous\"\n // Call the function with the URL we want to load, but then chain the\n // promise then() method on to the end of it. This contains two callbacks\n self.imgLoad(src).then(function(response) {\n // The first runs when the promise resolves, with the request.reponse specified within the resolve() method.\n var imageURL = window.URL.createObjectURL(response);\n resolve(imageURL);\n //$('background-content').setStyle('background-image', 'url('+imageURL+')') //myImage.src = imageURL;\n //console.log(imageURL);\n //body.appendChild(myImage);\n // The second runs when the promise is rejected, and logs the Error specified with the reject() method.\n }, function(Error) {\n reject(Error)\n });\n });\n }\n //--------------------------\n // event handlers\n //--------------------------\n handleLoadProgress(e) {\n var percentComplete = Math.ceil((e.loaded / e.total) * 100);\n //console.log(percentComplete);\n }\n}\nexport default DataUtils;\n","import EventEmitter from '../events/EventEmitter';\n\nclass Animate extends EventEmitter {\n //--------------------------\n // constructor\n //--------------------------\n constructor() {\n super();\n }\n //--------------------------\n // methods\n //--------------------------\n object(properties) {\n var animation = anime(\n properties\n );\n //animation.start(properties);\n }\n //--------------------------\n // event handlers\n //--------------------------\n}\nexport default Animate\n","class StringUtils\n{\n\n //--------------------------\n // constructor\n //--------------------------\n constructor()\n {}\n //--------------------------\n // methods\n //--------------------------\n cleanString(string)\n {\n var clean = string.replace(/(^\\-+|[^a-zA-Z0-9\\/_| -]+|\\-+$)/g, '').toLowerCase().replace(/[\\/_| -]+/g, '-');\n return clean;\n }\n\n decodeHTML(string, quote_style) {\n var optTemp = 0,\n i = 0,\n noquotes = false;\n if (typeof quote_style === 'undefined') {\n quote_style = 2;\n }\n string = string.toString().replace(/</g, '<').replace(/>/g, '>');\n var OPTS = {\n 'ENT_NOQUOTES': 0,\n 'ENT_HTML_QUOTE_SINGLE': 1,\n 'ENT_HTML_QUOTE_DOUBLE': 2,\n 'ENT_COMPAT': 2,\n 'ENT_QUOTES': 3,\n 'ENT_IGNORE': 4\n };\n if (quote_style === 0) {\n noquotes = true;\n }\n if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags\n quote_style = [].concat(quote_style);\n for (i = 0; i < quote_style.length; i++) {\n // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4\n if (OPTS[quote_style[i]] === 0) {\n noquotes = true;\n } else if (OPTS[quote_style[i]]) {\n optTemp = optTemp | OPTS[quote_style[i]];\n }\n }\n quote_style = optTemp;\n }\n if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {\n string = string.replace(/�*39;/g, \"'\"); // PHP doesn't currently escape if more than one 0, but it should\n // string = string.replace(/'|�*27;/g, \"'\"); // This would also be useful here, but not a part of PHP\n }\n if (!noquotes) {\n string = string.replace(/"/g, '\"');\n }\n // Put this in last place to avoid escape being double-decoded\n string = string.replace(/&/g, '&');\n return string;\n }\n\n //--------------------------\n // event handlers\n //--------------------------\n}\nexport default StringUtils\n","import DataUtils, {\n REQUEST_TYPE_GET,\n REQUEST_TYPE_PUT,\n REQUEST_TYPE_POST,\n REQUEST_TYPE_DELETE,\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_FORM\n} from '../../../../../brain//tools/utilities/DataUtils';\nimport * as DataEvent from '../../../../../brain//tools/events/DataEvent';\nimport StringUtils from '../../../../../brain//tools/utilities/StringUtils';\n\nclass PostActions {\n //--------------------------\n // constructor\n //--------------------------\n constructor() {\n var folio = [];\n this.dataUtils = new DataUtils();\n }\n //--------------------------\n // methods\n //--------------------------\n start() {}\n\n submitPost(edit, uploadFiles) {\n let self = this;\n return new Promise(function (resolve, reject) {\n //collect form data\n //if(!this.validateForm())\n var postData = new FormData();\n //let projectImages = document.getElementById('projectImages');\n //var fileSelect = projectImages;\n var files = uploadFiles;\n for (var i = 0; i < files.length; i++) {\n var file = files[i];\n // Check the file type.\n if (!file.type.match('image.*')) {\n continue;\n }\n // Add the file to the request.\n postData.append('feature_image', file, file.name);\n }\n //var category = document.getElementById(\"content_category\");\n //let project_form = document.forms.namedItem(\"folio-project\");\n var txt = document.createElement(\"textarea\");\n txt.innerHTML = document.getElementById('edit-post-text').innerHTML;\n postData.append(\"title\", document.getElementById('post_title').value);\n postData.append('slug', new StringUtils().cleanString(document.getElementById('post_title').value));\n postData.append(\"post_plaintext\", txt.value);\n postData.append(\"origin_date\", document.getElementById('post-date').value);\n postData.append(\"tags\", document.getElementById('post_tags').value);\n postData.append(\"status_page\", document.getElementById('option-page').getAttribute('data-active'));\n postData.append(\"status_feature\", document.getElementById('option-feature').getAttribute('data-active'));\n postData.append(\"status_published\", document.getElementById('option-published').getAttribute('data-active'));\n\n let postURL;\n let postEventType;\n if (edit) {\n let postID = document.getElementById('edit-update').getAttribute('data-id');\n postURL = \"/api/post/update/\" + postID;\n postEventType = DataEvent.POST_UPDATED;\n\n } else {\n postURL = \"/api/post/add\";\n postEventType = DataEvent.POST_ADDED;\n }\n self.dataUtils.request(postURL, postEventType, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, postData)\n .then((response) => {\n resolve({\n response\n })\n }).catch((err) => {\n reject({\n err\n });\n })\n });\n }\n\n deletePost() {\n let self = this;\n let postID = document.getElementById('edit-update').getAttribute('data-id');\n return new Promise(function (resolve, reject) {\n self.dataUtils.request(\"/api/post/delete/\" + postID, DataEvent.POST_DELETED, REQUEST_TYPE_POST, CONTENT_TYPE_FORM)\n .then((response) => {\n resolve({\n response\n })\n }).catch((err) => {\n reject({\n err\n });\n })\n })\n //this.dataUtils.re\n }\n //--------------------------\n // event handlers\n //--------------------------\n}\nexport {\n PostActions as\n default\n}","export const EDITOR_DELETE = 'editorDelete';\nexport const EDITOR_UPLOAD_POST_IMAGE = 'editorUploadImage';\nexport const EDITOR_SAVE = 'editorSave';\nexport const EDITOR_UPDATE = 'editorUpdate';\n\nclass EditorEvent\n{\n\n //--------------------------\n // methods\n //--------------------------\n\n\n\n //--------------------------\n // event handlers\n //--------------------------\n}\nexport default new EditorEvent\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global.TinyDatePicker = factory());\n}(this, (function () { 'use strict';\n\n /**\n * @file A generic set of mutation-free date functions.\n */\n\n /**\n * now returns the current date without any time values\n *\n * @returns {Date}\n */\n function now() {\n var dt = new Date();\n dt.setHours(0, 0, 0, 0);\n return dt;\n }\n\n /**\n * dateEq compares two dates\n *\n * @param {Date} date1 the first date\n * @param {Date} date2 the second date\n * @returns {boolean}\n */\n function datesEq(date1, date2) {\n return (date1 && date1.toDateString()) === (date2 && date2.toDateString());\n }\n\n /**\n * shiftDay shifts the specified date by n days\n *\n * @param {Date} dt\n * @param {number} n\n * @returns {Date}\n */\n function shiftDay(dt, n) {\n dt = new Date(dt);\n dt.setDate(dt.getDate() + n);\n return dt;\n }\n\n /**\n * shiftMonth shifts the specified date by a specified number of months\n *\n * @param {Date} dt\n * @param {number} n\n * @param {boolean} wrap optional, if true, does not change year\n * value, defaults to false\n * @returns {Date}\n */\n function shiftMonth(dt, n, wrap) {\n dt = new Date(dt);\n\n var dayOfMonth = dt.getDate();\n var month = dt.getMonth() + n;\n\n dt.setDate(1);\n dt.setMonth(wrap ? (12 + month) % 12 : month);\n dt.setDate(dayOfMonth);\n\n // If dayOfMonth = 31, but the target month only has 30 or 29 or whatever...\n // head back to the max of the target month\n if (dt.getDate() < dayOfMonth) {\n dt.setDate(0);\n }\n\n return dt;\n }\n\n /**\n * shiftYear shifts the specified date by n years\n *\n * @param {Date} dt\n * @param {number} n\n * @returns {Date}\n */\n function shiftYear(dt, n) {\n dt = new Date(dt);\n dt.setFullYear(dt.getFullYear() + n);\n return dt;\n }\n\n /**\n * setYear changes the specified date to the specified year\n *\n * @param {Date} dt\n * @param {number} year\n */\n function setYear(dt, year) {\n dt = new Date(dt);\n dt.setFullYear(year);\n return dt;\n }\n\n /**\n * setMonth changes the specified date to the specified month\n *\n * @param {Date} dt\n * @param {number} month\n */\n function setMonth(dt, month) {\n return shiftMonth(dt, month - dt.getMonth());\n }\n\n /**\n * dateOrParse creates a function which, given a date or string, returns a date\n *\n * @param {function} parse the function used to parse strings\n * @returns {function}\n */\n function dateOrParse(parse) {\n return function (dt) {\n return dropTime(typeof dt === 'string' ? parse(dt) : dt);\n };\n }\n\n /**\n * constrainDate returns dt or min/max depending on whether dt is out of bounds (inclusive)\n *\n * @export\n * @param {Date} dt\n * @param {Date} min\n * @param {Date} max\n * @returns {Date}\n */\n function constrainDate(dt, min, max) {\n return (dt < min) ? min :\n (dt > max) ? max :\n dt;\n }\n\n function dropTime(dt) {\n dt = new Date(dt);\n dt.setHours(0, 0, 0, 0);\n return dt;\n }\n\n /**\n * @file Utility functions for function manipulation.\n */\n\n /**\n * bufferFn buffers calls to fn so they only happen every ms milliseconds\n *\n * @param {number} ms number of milliseconds\n * @param {function} fn the function to be buffered\n * @returns {function}\n */\n function bufferFn(ms, fn) {\n var timeout = undefined;\n return function () {\n clearTimeout(timeout);\n timeout = setTimeout(fn, ms);\n };\n }\n\n /**\n * noop is a function which does nothing at all.\n */\n function noop() { }\n\n /**\n * copy properties from object o2 to object o1.\n *\n * @params {Object} o1\n * @params {Object} o2\n * @returns {Object}\n */\n function cp() {\n var args = arguments;\n var o1 = args[0];\n for (var i = 1; i < args.length; ++i) {\n var o2 = args[i] || {};\n for (var key in o2) {\n o1[key] = o2[key];\n }\n }\n return o1;\n }\n\n /**\n * @file Responsible for sanitizing and creating date picker options.\n */\n\n var english = {\n days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],\n months: [\n 'January',\n 'February',\n 'March',\n 'April',\n 'May',\n 'June',\n 'July',\n 'August',\n 'September',\n 'October',\n 'November',\n 'December',\n ],\n today: 'Today',\n clear: 'Clear',\n close: 'Close',\n };\n\n /**\n * DatePickerOptions constructs a new date picker options object, overriding\n * default values with any values specified in opts.\n *\n * @param {DatePickerOptions} opts\n * @returns {DatePickerOptions}\n */\n function DatePickerOptions(opts) {\n opts = opts || {};\n opts = cp(defaults(), opts);\n var parse = dateOrParse(opts.parse);\n opts.lang = cp(english, opts.lang);\n opts.parse = parse;\n opts.inRange = makeInRangeFn(opts);\n opts.min = parse(opts.min || shiftYear(now(), -100));\n opts.max = parse(opts.max || shiftYear(now(), 100));\n opts.hilightedDate = opts.parse(opts.hilightedDate);\n\n return opts;\n }\n\n function defaults() {\n return {\n lang: english,\n\n // Possible values: dp-modal, dp-below, dp-permanent\n mode: 'dp-modal',\n\n // The date to hilight initially if the date picker has no\n // initial value.\n hilightedDate: now(),\n\n format: function (dt) {\n return (dt.getMonth() + 1) + '/' + dt.getDate() + '/' + dt.getFullYear();\n },\n\n parse: function (str) {\n var date = new Date(str);\n return isNaN(date) ? now() : date;\n },\n\n dateClass: function () { },\n\n inRange: function () {\n return true;\n }\n };\n }\n\n function makeInRangeFn(opts) {\n var inRange = opts.inRange; // Cache this version, and return a variant\n\n return function (dt, dp) {\n return inRange(dt, dp) && opts.min <= dt && opts.max >= dt;\n };\n }\n\n /**\n * @file Helper functions for dealing with dom elements.\n */\n\n var Key = {\n left: 37,\n up: 38,\n right: 39,\n down: 40,\n enter: 13,\n esc: 27,\n };\n\n /**\n * on attaches an event handler to the specified element, and returns an\n * off function which can be used to remove the handler.\n *\n * @param {string} evt the name of the event to handle\n * @param {HTMLElement} el the element to attach to\n * @param {function} handler the event handler\n * @returns {function} the off function\n */\n function on(evt, el, handler) {\n el.addEventListener(evt, handler, true);\n\n return function () {\n el.removeEventListener(evt, handler, true);\n };\n }\n\n var CustomEvent = shimCustomEvent();\n\n function shimCustomEvent() {\n var CustomEvent = window.CustomEvent;\n\n if (typeof CustomEvent !== 'function') {\n CustomEvent = function (event, params) {\n params = params || {bubbles: false, cancelable: false, detail: undefined};\n var evt = document.createEvent('CustomEvent');\n evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);\n return evt;\n };\n\n CustomEvent.prototype = window.Event.prototype;\n }\n\n return CustomEvent;\n }\n\n /**\n * @file Manages the calendar / day-picker view.\n */\n\n var dayPicker = {\n onKeyDown: keyDown,\n onClick: {\n 'dp-day': selectDay,\n 'dp-next': gotoNextMonth,\n 'dp-prev': gotoPrevMonth,\n 'dp-today': selectToday,\n 'dp-clear': clear,\n 'dp-close': close,\n 'dp-cal-month': showMonthPicker,\n 'dp-cal-year': showYearPicker,\n },\n render: render\n };\n\n /**\n * view renders the calendar (day picker) as an HTML string.\n *\n * @param {DatePickerContext} context the date picker being rendered\n * @returns {string}\n */\n function render(dp) {\n var opts = dp.opts;\n var lang = opts.lang;\n var state = dp.state;\n var dayNames = lang.days;\n var dayOffset = opts.dayOffset || 0;\n var selectedDate = state.selectedDate;\n var hilightedDate = state.hilightedDate;\n var hilightedMonth = hilightedDate.getMonth();\n var today = now().getTime();\n\n return (\n '<div class=\"dp-cal\">' +\n '<header class=\"dp-cal-header\">' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-prev\">Prev</button>' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-cal-month\">' +\n lang.months[hilightedMonth] +\n '</button>' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-cal-year\">' +\n hilightedDate.getFullYear() +\n '</button>' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-next\">Next</button>' +\n '</header>' +\n '<div class=\"dp-days\">' +\n dayNames.map(function (name, i) {\n return (\n '<span class=\"dp-col-header\">' + dayNames[(i + dayOffset) % dayNames.length] + '</span>'\n );\n }).join('') +\n mapDays(hilightedDate, dayOffset, function (date) {\n var isNotInMonth = date.getMonth() !== hilightedMonth;\n var isDisabled = !opts.inRange(date);\n var isToday = date.getTime() === today;\n var className = 'dp-day';\n className += (isNotInMonth ? ' dp-edge-day' : '');\n className += (datesEq(date, hilightedDate) ? ' dp-current' : '');\n className += (datesEq(date, selectedDate) ? ' dp-selected' : '');\n className += (isDisabled ? ' dp-day-disabled' : '');\n className += (isToday ? ' dp-day-today' : '');\n className += ' ' + opts.dateClass(date, dp);\n\n return (\n '<button tabindex=\"-1\" type=\"button\" class=\"' + className + '\" data-date=\"' + date.getTime() + '\">' +\n date.getDate() +\n '</button>'\n );\n }) +\n '</div>' +\n '<footer class=\"dp-cal-footer\">' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-today\">' + lang.today + '</button>' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-clear\">' + lang.clear + '</button>' +\n '<button tabindex=\"-1\" type=\"button\" class=\"dp-close\">' + lang.close + '</button>' +\n '</footer>' +\n '</div>'\n );\n }\n\n /**\n * keyDown handles the key down event for the day-picker\n *\n * @param {Event} e\n * @param {DatePickerContext} dp\n */\n function keyDown(e, dp) {\n var key = e.keyCode;\n var shiftBy =\n (key === Key.left) ? -1 :\n (key === Key.right) ? 1 :\n (key === Key.up) ? -7 :\n (key === Key.down) ? 7 :\n 0;\n\n if (key === Key.esc) {\n dp.close();\n } else if (shiftBy) {\n e.preventDefault();\n dp.setState({\n hilightedDate: shiftDay(dp.state.hilightedDate, shiftBy)\n });\n }\n }\n\n function selectToday(e, dp) {\n dp.setState({\n selectedDate: now(),\n });\n }\n\n function clear(e, dp) {\n dp.setState({\n selectedDate: null,\n });\n }\n\n function close(e, dp) {\n dp.close();\n }\n\n function showMonthPicker(e, dp) {\n dp.setState({\n view: 'month'\n });\n }\n\n function showYearPicker(e, dp) {\n dp.setState({\n view: 'year'\n });\n }\n\n function gotoNextMonth(e, dp) {\n var hilightedDate = dp.state.hilightedDate;\n dp.setState({\n hilightedDate: shiftMonth(hilightedDate, 1)\n });\n }\n\n function gotoPrevMonth(e, dp) {\n var hilightedDate = dp.state.hilightedDate;\n dp.setState({\n hilightedDate: shiftMonth(hilightedDate, -1)\n });\n }\n\n function selectDay(e, dp) {\n dp.setState({\n selectedDate: new Date(parseInt(e.target.getAttribute('data-date'))),\n });\n }\n\n function mapDays(currentDate, dayOffset, fn) {\n var result = '';\n var iter = new Date(currentDate);\n iter.setDate(1);\n iter.setDate(1 - iter.getDay() + dayOffset);\n\n // If we are showing monday as the 1st of the week,\n // and the monday is the 2nd of the month, the sunday won't\n // show, so we need to shift backwards\n if (dayOffset && iter.getDate() === dayOffset + 1) {\n iter.setDate(dayOffset - 6);\n }\n\n // We are going to have 6 weeks always displayed to keep a consistent\n // calendar size\n for (var day = 0; day < (6 * 7); ++day) {\n result += fn(iter);\n iter.setDate(iter.getDate() + 1);\n }\n\n return result;\n }\n\n /**\n * @file Manages the month-picker view.\n */\n\n var monthPicker = {\n onKeyDown: keyDown$1,\n onClick: {\n 'dp-month': onChooseMonth\n },\n render: render$1\n };\n\n function onChooseMonth(e, dp) {\n dp.setState({\n hilightedDate: setMonth(dp.state.hilightedDate, parseInt(e.target.getAttribute('data-month'))),\n view: 'day',\n });\n }\n\n /**\n * render renders the month picker as an HTML string\n *\n * @param {DatePickerContext} dp the date picker context\n * @returns {string}\n */\n function render$1(dp) {\n var opts = dp.opts;\n var lang = opts.lang;\n var months = lang.months;\n var currentDate = dp.state.hilightedDate;\n var currentMonth = currentDate.getMonth();\n\n return (\n '<div class=\"dp-months\">' +\n months.map(function (month, i) {\n var className = 'dp-month';\n className += (currentMonth === i ? ' dp-current' : '');\n\n return (\n '<button tabindex=\"-1\" type=\"button\" class=\"' + className + '\" data-month=\"' + i + '\">' +\n month +\n '</button>'\n );\n }).join('') +\n '</div>'\n );\n }\n\n /**\n * keyDown handles keydown events that occur in the month picker\n *\n * @param {Event} e\n * @param {DatePickerContext} dp\n */\n function keyDown$1(e, dp) {\n var key = e.keyCode;\n var shiftBy =\n (key === Key.left) ? -1 :\n (key === Key.right) ? 1 :\n (key === Key.up) ? -3 :\n (key === Key.down) ? 3 :\n 0;\n\n if (key === Key.esc) {\n dp.setState({\n view: 'day',\n });\n } else if (shiftBy) {\n e.preventDefault();\n dp.setState({\n hilightedDate: shiftMonth(dp.state.hilightedDate, shiftBy, true)\n });\n }\n }\n\n /**\n * @file Manages the year-picker view.\n */\n\n var yearPicker = {\n render: render$2,\n onKeyDown: keyDown$2,\n onClick: {\n 'dp-year': onChooseYear\n },\n };\n\n /**\n * view renders the year picker as an HTML string.\n *\n * @param {DatePickerContext} dp the date picker context\n * @returns {string}\n */\n function render$2(dp) {\n var state = dp.state;\n var currentYear = state.hilightedDate.getFullYear();\n var selectedYear = state.selectedDate.getFullYear();\n\n return (\n '<div class=\"dp-years\">' +\n mapYears(dp, function (year) {\n var className = 'dp-year';\n className += (year === currentYear ? ' dp-current' : '');\n className += (year === selectedYear ? ' dp-selected' : '');\n\n return (\n '<button tabindex=\"-1\" type=\"button\" class=\"' + className + '\" data-year=\"' + year + '\">' +\n year +\n '</button>'\n );\n }) +\n '</div>'\n );\n }\n\n function onChooseYear(e, dp) {\n dp.setState({\n hilightedDate: setYear(dp.state.hilightedDate, parseInt(e.target.getAttribute('data-year'))),\n view: 'day',\n });\n }\n\n function keyDown$2(e, dp) {\n var key = e.keyCode;\n var opts = dp.opts;\n var shiftBy =\n (key === Key.left || key === Key.up) ? 1 :\n (key === Key.right || key === Key.down) ? -1 :\n 0;\n\n if (key === Key.esc) {\n dp.setState({\n view: 'day',\n });\n } else if (shiftBy) {\n e.preventDefault();\n var shiftedYear = shiftYear(dp.state.hilightedDate, shiftBy);\n\n dp.setState({\n hilightedDate: constrainDate(shiftedYear, opts.min, opts.max),\n });\n }\n }\n\n function mapYears(dp, fn) {\n var result = '';\n var max = dp.opts.max.getFullYear();\n\n for (var i = max; i >= dp.opts.min.getFullYear(); --i) {\n result += fn(i);\n }\n\n return result;\n }\n\n /**\n * @file Defines the base date picker behavior, overridden by various modes.\n */\n\n var views = {\n day: dayPicker,\n year: yearPicker,\n month: monthPicker\n };\n\n function BaseMode(input, emit, opts) {\n var detatchInputEvents; // A function that detaches all events from the input\n var closing = false; // A hack to prevent calendar from re-opening when closing.\n var selectedDate; // The currently selected date\n var dp = {\n // The root DOM element for the date picker, initialized on first open.\n el: undefined,\n opts: opts,\n shouldFocusOnBlur: true,\n shouldFocusOnRender: true,\n state: initialState(),\n adjustPosition: noop,\n containerHTML: '<div class=\"dp\"></div>',\n\n attachToDom: function () {\n document.body.appendChild(dp.el);\n },\n\n updateInput: function (selectedDate) {\n var e = new CustomEvent('change', {bubbles: true});\n e.simulated = true;\n input.value = selectedDate ? opts.format(selectedDate) : '';\n input.dispatchEvent(e);\n },\n\n computeSelectedDate: function () {\n return opts.parse(input.value);\n },\n\n currentView: function() {\n return views[dp.state.view];\n },\n\n open: function () {\n if (closing) {\n return;\n }\n\n if (!dp.el) {\n dp.el = createContainerElement(opts, dp.containerHTML);\n attachContainerEvents(dp);\n }\n\n selectedDate = constrainDate(dp.computeSelectedDate(), opts.min, opts.max);\n dp.state.hilightedDate = selectedDate || opts.hilightedDate;\n dp.state.view = 'day';\n\n dp.attachToDom();\n dp.render();\n\n emit('open');\n },\n\n isVisible: function () {\n return !!dp.el && !!dp.el.parentNode;\n },\n\n hasFocus: function () {\n var focused = document.activeElement;\n return dp.el &&\n dp.el.contains(focused) &&\n focused.className.indexOf('dp-focuser') < 0;\n },\n\n shouldHide: function () {\n return dp.isVisible();\n },\n\n close: function (becauseOfBlur) {\n var el = dp.el;\n\n if (!dp.isVisible()) {\n return;\n }\n\n if (el) {\n var parent = el.parentNode;\n parent && parent.removeChild(el);\n }\n\n closing = true;\n\n if (becauseOfBlur && dp.shouldFocusOnBlur) {\n focusInput(input);\n }\n\n // When we close, the input often gains refocus, which\n // can then launch the date picker again, so we buffer\n // a bit and don't show the date picker within N ms of closing\n setTimeout(function() {\n closing = false;\n }, 100);\n\n emit('close');\n },\n\n destroy: function () {\n dp.close();\n detatchInputEvents();\n },\n\n render: function () {\n if (!dp.el) {\n return;\n }\n\n var hadFocus = dp.hasFocus();\n var html = dp.currentView().render(dp);\n html && (dp.el.firstChild.innerHTML = html);\n\n dp.adjustPosition();\n\n if (hadFocus || dp.shouldFocusOnRender) {\n focusCurrent(dp);\n }\n },\n\n // Conceptually similar to setState in React, updates\n // the view state and re-renders.\n setState: function (state) {\n for (var key in state) {\n dp.state[key] = state[key];\n }\n\n emit('statechange');\n dp.render();\n },\n };\n\n detatchInputEvents = attachInputEvents(input, dp);\n\n // Builds the initial view state\n // selectedDate is a special case and causes changes to hilightedDate\n // hilightedDate is set on open, so remains undefined initially\n // view is the current view (day, month, year)\n function initialState() {\n return {\n get selectedDate() {\n return selectedDate;\n },\n set selectedDate(dt) {\n if (dt && !opts.inRange(dt)) {\n return;\n }\n\n if (dt) {\n selectedDate = new Date(dt);\n dp.state.hilightedDate = selectedDate;\n } else {\n selectedDate = dt;\n }\n\n dp.updateInput(selectedDate);\n emit('select');\n dp.close();\n },\n view: 'day',\n };\n }\n\n return dp;\n }\n\n function createContainerElement(opts, containerHTML) {\n var el = document.createElement('div');\n\n el.className = opts.mode;\n el.innerHTML = containerHTML;\n\n return el;\n }\n\n function attachInputEvents(input, dp) {\n var bufferShow = bufferFn(5, function () {\n if (dp.shouldHide()) {\n dp.close();\n } else {\n dp.open();\n }\n });\n\n var off = [\n on('blur', input, bufferFn(150, function () {\n if (!dp.hasFocus()) {\n dp.close(true);\n }\n })),\n\n on('mousedown', input, function () {\n if (input === document.activeElement) {\n bufferShow();\n }\n }),\n\n on('focus', input, bufferShow),\n\n on('input', input, function (e) {\n var date = dp.opts.parse(e.target.value);\n isNaN(date) || dp.setState({\n hilightedDate: date\n });\n }),\n ];\n\n // Unregister all events that were registered above.\n return function() {\n off.forEach(function (f) {\n f();\n });\n };\n }\n\n function focusCurrent(dp) {\n var current = dp.el.querySelector('.dp-current');\n return current && current.focus();\n }\n\n function attachContainerEvents(dp) {\n var el = dp.el;\n var calEl = el.querySelector('.dp');\n\n // Hack to get iOS to show active CSS states\n el.ontouchstart = noop;\n\n function onClick(e) {\n e.target.className.split(' ').forEach(function(evt) {\n var handler = dp.currentView().onClick[evt];\n handler && handler(e, dp);\n });\n }\n\n // The calender fires a blur event *every* time we redraw\n // this means we need to buffer the blur event to see if\n // it still has no focus after redrawing, and only then\n // do we return focus to the input. A possible other approach\n // would be to set context.redrawing = true on redraw and\n // set it to false in the blur event.\n on('blur', calEl, bufferFn(150, function () {\n if (!dp.hasFocus()) {\n dp.close(true);\n }\n }));\n\n on('keydown', el, function (e) {\n if (e.keyCode === Key.enter) {\n onClick(e);\n } else {\n dp.currentView().onKeyDown(e, dp);\n }\n });\n\n // If the user clicks in non-focusable space, but\n // still within the date picker, we don't want to\n // hide, so we need to hack some things...\n on('mousedown', calEl, function (e) {\n e.target.focus && e.target.focus(); // IE hack\n if (document.activeElement !== e.target) {\n e.preventDefault();\n focusCurrent(dp);\n }\n });\n\n on('click', el, onClick);\n }\n\n function focusInput(input) {\n // When the modal closes, we need to focus the original input so the\n // user can continue tabbing from where they left off.\n input.focus();\n\n // iOS zonks out if we don't blur the input, so...\n if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {\n input.blur();\n }\n }\n\n /**\n * @file Defines the modal date picker behavior.\n */\n\n function ModalMode(input, emit, opts) {\n var dp = BaseMode(input, emit, opts);\n\n // In modal mode, users really shouldn't be able to type in\n // the input, as all input is done via the calendar.\n input.readonly = true;\n\n // In modal mode, we need to know when the user has tabbed\n // off the end of the calendar, and set focus to the original\n // input. To do this, we add a special element to the DOM.\n // When the user tabs off the bottom of the calendar, they\n // will tab onto this element.\n dp.containerHTML += '<a href=\"#\" class=\"dp-focuser\">.</a>';\n\n return dp;\n }\n\n /**\n * @file Defines the dropdown date picker behavior.\n */\n\n function DropdownMode(input, emit, opts) {\n var dp = BaseMode(input, emit, opts);\n\n dp.shouldFocusOnBlur = false;\n\n Object.defineProperty(dp, 'shouldFocusOnRender', {\n get: function() {\n return input !== document.activeElement;\n }\n });\n\n dp.adjustPosition = function () {\n autoPosition(input, dp);\n };\n\n return dp;\n }\n\n function autoPosition(input, dp) {\n var inputPos = input.getBoundingClientRect();\n var win = window;\n\n adjustCalY(dp, inputPos, win);\n adjustCalX(dp, inputPos, win);\n\n dp.el.style.visibility = '';\n }\n\n function adjustCalX(dp, inputPos, win) {\n var cal = dp.el;\n var scrollLeft = win.pageXOffset;\n var inputLeft = inputPos.left + scrollLeft;\n var maxRight = win.innerWidth + scrollLeft;\n var offsetWidth = cal.offsetWidth;\n var calRight = inputLeft + offsetWidth;\n var shiftedLeft = maxRight - offsetWidth;\n var left = calRight > maxRight && shiftedLeft > 0 ? shiftedLeft : inputLeft;\n\n cal.style.left = left + 'px';\n }\n\n function adjustCalY(dp, inputPos, win) {\n var cal = dp.el;\n var scrollTop = win.pageYOffset;\n var inputTop = scrollTop + inputPos.top;\n var calHeight = cal.offsetHeight;\n var belowTop = inputTop + inputPos.height + 8;\n var aboveTop = inputTop - calHeight - 8;\n var isAbove = (aboveTop > 0 && belowTop + calHeight > scrollTop + win.innerHeight);\n var top = isAbove ? aboveTop : belowTop;\n\n if (cal.classList) {\n cal.classList.toggle('dp-is-above', isAbove);\n cal.classList.toggle('dp-is-below', !isAbove);\n }\n cal.style.top = top + 'px';\n }\n\n /**\n * @file Defines the permanent date picker behavior.\n */\n\n function PermanentMode(root, emit, opts) {\n var dp = BaseMode(root, emit, opts);\n\n dp.close = noop;\n dp.destroy = noop;\n dp.updateInput = noop;\n dp.shouldFocusOnRender = opts.shouldFocusOnRender;\n\n dp.computeSelectedDate = function () {\n return opts.hilightedDate;\n };\n\n dp.attachToDom = function () {\n root.appendChild(dp.el);\n };\n\n dp.open();\n\n return dp;\n }\n\n /**\n * @file Defines the various date picker modes (modal, dropdown, permanent)\n */\n\n function Mode(input, emit, opts) {\n input = input && input.tagName ? input : document.querySelector(input);\n\n if (opts.mode === 'dp-modal') {\n return ModalMode(input, emit, opts);\n }\n\n if (opts.mode === 'dp-below') {\n return DropdownMode(input, emit, opts);\n }\n\n if (opts.mode === 'dp-permanent') {\n return PermanentMode(input, emit, opts);\n }\n }\n\n /**\n * @file Defines simple event emitter behavior.\n */\n\n /**\n * Emitter constructs a new emitter object which has on/off methods.\n *\n * @returns {EventEmitter}\n */\n function Emitter() {\n var handlers = {};\n\n function onOne(name, handler) {\n (handlers[name] = (handlers[name] || [])).push(handler);\n }\n\n function onMany(fns) {\n for (var name in fns) {\n onOne(name, fns[name]);\n }\n }\n\n return {\n on: function (name, handler) {\n if (handler) {\n onOne(name, handler);\n } else {\n onMany(name);\n }\n\n return this;\n },\n\n emit: function (name, arg) {\n (handlers[name] || []).forEach(function (handler) {\n handler(name, arg);\n });\n },\n\n off: function (name, handler) {\n if (!name) {\n handlers = {};\n } else if (!handler) {\n handlers[name] = [];\n } else {\n handlers[name] = (handlers[name] || []).filter(function (h) {\n return h !== handler;\n });\n }\n\n return this;\n }\n };\n }\n\n /**\n * @file The root date picker file, defines public exports for the library.\n */\n\n /**\n * The date picker language configuration\n * @typedef {Object} LangOptions\n * @property {Array.<string>} [days] - Days of the week\n * @property {Array.<string>} [months] - Months of the year\n * @property {string} today - The label for the 'today' button\n * @property {string} close - The label for the 'close' button\n * @property {string} clear - The label for the 'clear' button\n */\n\n /**\n * The configuration options for a date picker.\n *\n * @typedef {Object} DatePickerOptions\n * @property {LangOptions} [lang] - Configures the label text, defaults to English\n * @property {('dp-modal'|'dp-below'|'dp-permanent')} [mode] - The date picker mode, defaults to 'dp-modal'\n * @property {(string|Date)} [hilightedDate] - The date to hilight if no date is selected\n * @property {function(string|Date):Date} [parse] - Parses a date, the complement of the \"format\" function\n * @property {function(Date):string} [format] - Formats a date for displaying to user\n * @property {function(Date):string} [dateClass] - Associates a custom CSS class with a date\n * @property {function(Date):boolean} [inRange] - Indicates whether or not a date is selectable\n * @property {(string|Date)} [min] - The minimum selectable date (inclusive, default 100 years ago)\n * @property {(string|Date)} [max] - The maximum selectable date (inclusive, default 100 years from now)\n */\n\n /**\n * The state values for the date picker\n *\n * @typedef {Object} DatePickerState\n * @property {string} view - The current view 'day' | 'month' | 'year'\n * @property {Date} selectedDate - The date which has been selected by the user\n * @property {Date} hilightedDate - The date which is currently hilighted / active\n */\n\n /**\n * An instance of TinyDatePicker\n *\n * @typedef {Object} DatePicker\n * @property {DatePickerState} state - The values currently displayed.\n * @property {function} on - Adds an event handler\n * @property {function} off - Removes an event handler\n * @property {function} setState - Changes the current state of the date picker\n * @property {function} open - Opens the date picker\n * @property {function} close - Closes the date picker\n * @property {function} destroy - Destroys the date picker (removing all handlers from the input, too)\n */\n\n /**\n * TinyDatePicker constructs a new date picker for the specified input\n *\n * @param {HTMLElement | string} input The input or CSS selector associated with the datepicker\n * @param {DatePickerOptions} opts The options for initializing the date picker\n * @returns {DatePicker}\n */\n function TinyDatePicker(input, opts) {\n var emitter = Emitter();\n var options = DatePickerOptions(opts);\n var mode = Mode(input, emit, options);\n var me = {\n get state() {\n return mode.state;\n },\n on: emitter.on,\n off: emitter.off,\n setState: mode.setState,\n open: mode.open,\n close: mode.close,\n destroy: mode.destroy,\n };\n\n function emit(evt) {\n emitter.emit(evt, me);\n }\n\n return me;\n }\n\n return TinyDatePicker;\n\n})));\n","class DateUtils {\n\n //--------------------------\n // constructor\n //--------------------------\n constructor() {}\n\n //--------------------------\n // methods\n //--------------------------\n getMKtime() {\n var time = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), new Date().getHours(), new Date().getMinutes(), new Date().getSeconds(), 0).getTime() / 1000;\n return time;\n }\n\n convertMKtime(seconds) {\n var date = new Date(seconds * 1000);\n return date;\n }\n\n getDate(type, rawdate) {\n var day = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCDate()) : String(new Date().getUTCDate()));\n var month = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCMonth() + 1) : String(new Date().getUTCMonth() + 1));\n var year = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCFullYear()) : String(new Date().getUTCFullYear()));\n var hour = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCHours()) : String(new Date().getUTCHours()));\n var minute = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCMinutes()) : String(new Date().getUTCMinutes()));\n var seconds = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCSeconds()) : String(new Date().getUTCSeconds()));\n var millisecond = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getUTCMilliseconds()) : String(new Date().getUTCMilliseconds()));\n var offset = ((rawdate != null || rawdate != '') ? String(new Date(rawdate).getTimezoneOffset()) : String(new Date().getTimezoneOffset()));\n if (day.length == 1)\n day = String(\"0\" + day);\n if (month.length == 1)\n month = String(\"0\" + month);\n offset = String(offset / 60);\n if (offset.length == 1)\n offset = String(\"0\" + offset);\n switch (type) {\n case \"day\":\n return day;\n break;\n case \"month\":\n return month;\n break;\n case \"year\":\n return year;\n break;\n case \"stamp\":\n return String(year + \"-\" + month + \"-\" + day + \" \" + hour + \":\" + minute + \":\" + seconds + \".\" + millisecond + \"-\" + (offset));\n break\n default:\n return String(year + \"-\" + month + \"-\" + day);\n break;\n }\n }\n\n //--------------------------\n // event handlers\n //--------------------------\n}\n\nexport default DateUtils","const attributes = [\n 'borderBottomWidth',\n 'borderLeftWidth',\n 'borderRightWidth',\n 'borderTopStyle',\n 'borderRightStyle',\n 'borderBottomStyle',\n 'borderLeftStyle',\n 'borderTopWidth',\n 'boxSizing',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'height',\n 'letterSpacing',\n 'lineHeight',\n 'marginBottom',\n 'marginLeft',\n 'marginRight',\n 'marginTop',\n 'outlineWidth',\n 'overflow',\n 'overflowX',\n 'overflowY',\n 'paddingBottom',\n 'paddingLeft',\n 'paddingRight',\n 'paddingTop',\n 'textAlign',\n 'textOverflow',\n 'textTransform',\n 'whiteSpace',\n 'wordBreak',\n 'wordWrap',\n];\n\n/**\n * Create a mirror\n *\n * @param {Element} element The element\n * @param {string} html The html\n *\n * @return {object} The mirror object\n */\nconst createMirror = (element, html) => {\n\n /**\n * The mirror element\n */\n const mirror = document.createElement('div');\n\n /**\n * Create the CSS for the mirror object\n *\n * @return {object} The style object\n */\n const mirrorCss = () => {\n const css = {\n position: 'absolute',\n left: -9999,\n top: 0,\n zIndex: -2000\n };\n\n if (element.tagName === 'TEXTAREA') {\n attributes.push('width');\n }\n\n attributes.forEach((attr) => {\n css[attr] = getComputedStyle(element)[attr];\n });\n\n return css;\n };\n\n /**\n * Initialize the mirror\n *\n * @param {string} html The html\n *\n * @return {void}\n */\n const initialize = (html) => {\n const styles = mirrorCss();\n Object.keys(styles).forEach(key => {\n mirror.style[key] = styles[key];\n });\n mirror.innerHTML = html;\n element.parentNode.insertBefore(mirror, element.nextSibling);\n };\n\n /**\n * Get the rect\n *\n * @return {Rect} The bounding rect\n */\n const rect = () => {\n const marker = mirror.ownerDocument.getElementById('caret-position-marker');\n const boundingRect = {\n left: marker.offsetLeft,\n top: marker.offsetTop,\n height: marker.offsetHeight\n };\n mirror.parentNode.removeChild(mirror);\n\n return boundingRect;\n };\n\n initialize(html);\n\n return {\n rect,\n };\n};\n\nexport default createMirror;\n","/**\n * Check if a DOM Element is content editable\n *\n * @param {Element} element The DOM element\n *\n * @return {bool} If it is content editable\n */\nexport const isContentEditable = (element) => !!(\n element.contentEditable &&\n element.contentEditable === 'true'\n);\n\n/**\n * Get the context from settings passed in\n *\n * @param {object} settings The settings object\n *\n * @return {object} window and document\n */\nexport const getContext = (settings = {}) => {\n const { customPos, iframe, noShadowCaret } = settings;\n if (iframe) {\n return {\n iframe,\n window: iframe.contentWindow,\n document: iframe.contentDocument || iframe.contentWindow.document,\n noShadowCaret,\n customPos,\n };\n }\n\n return {\n window,\n document,\n noShadowCaret,\n customPos,\n };\n};\n\n/**\n * Get the offset of an element\n *\n * @param {Element} element The DOM element\n * @param {object} ctx The context\n *\n * @return {object} top and left\n */\nexport const getOffset = (element, ctx) => {\n const win = ctx && ctx.window || window;\n const doc = ctx && ctx.document || document;\n const rect = element.getBoundingClientRect();\n const docEl = doc.documentElement;\n const scrollLeft = win.pageXOffset || docEl.scrollLeft;\n const scrollTop = win.pageYOffset || docEl.scrollTop;\n\n return {\n top: rect.top + scrollTop,\n left: rect.left + scrollLeft\n };\n};\n\n/**\n * Check if a value is an object\n *\n * @param {any} value The value to check\n *\n * @return {bool} If it is an object\n */\nexport const isObject = (value) => typeof value === 'object' && value !== null;\n","import createMirror from './mirror';\nimport { getOffset as elementOffset } from './utils';\n\n/**\n * Create a Input caret object.\n *\n * @param {Element} element The element\n * @param {Object} ctx The context\n */\nconst createInputCaret = (element, ctx) => {\n\n /**\n * Get the current position\n *\n * @returns {int} The caret position\n */\n const getPos = () => {\n return element.selectionStart;\n };\n\n /**\n * Set the position\n *\n * @param {int} pos The position\n *\n * @return {Element} The element\n */\n const setPos = (pos) => {\n element.setSelectionRange(pos, pos);\n\n return element;\n };\n\n /**\n * The offset\n *\n * @param {int} pos The position\n *\n * @return {object} The offset\n */\n const getOffset = (pos) => {\n const rect = elementOffset(element);\n const position = getPosition(pos);\n\n return {\n top: rect.top + position.top + ctx.document.body.scrollTop,\n left: rect.left + position.left + ctx.document.body.scrollLeft,\n height: position.height,\n };\n };\n\n /**\n * Get the current position\n *\n * @param {int} pos The position\n *\n * @return {object} The position\n */\n const getPosition = (pos) => {\n const format = (val) => {\n let value = val.replace(/<|>|`|\"|&/g, '?')\n .replace(/\\r\\n|\\r|\\n/g,'<br/>');\n return value;\n };\n\n if (ctx.customPos || ctx.customPos === 0) {\n pos = ctx.customPos;\n }\n\n const position = pos === undefined ? getPos() : pos;\n const startRange = element.value.slice(0, position);\n const endRange = element.value.slice(position);\n let html = `<span style=\"position: relative; display: inline;\">${format(startRange)}</span>`;\n html += '<span id=\"caret-position-marker\" style=\"position: relative; display: inline;\">|</span>';\n html += `<span style=\"position: relative; display: inline;\">${format(endRange)}</span>`;\n\n const mirror = createMirror(element, html);\n const rect = mirror.rect();\n rect.pos = getPos();\n\n return rect;\n };\n\n return {\n getPos,\n setPos,\n getOffset,\n getPosition,\n };\n};\n\nexport default createInputCaret;\n","/**\n * Create an Editable Caret\n * @param {Element} element The editable element\n * @param {object|null} ctx The context\n *\n * @return {EditableCaret}\n */\nconst createEditableCaret = (element, ctx) => {\n\n /**\n * Set the caret position\n *\n * @param {int} pos The position to se\n *\n * @return {Element} The element\n */\n const setPos = (pos) => {\n const sel = ctx.window.getSelection();\n if (sel) {\n let offset = 0;\n let found = false;\n const find = (position, parent) => {\n for (let i = 0; i < parent.childNodes.length; i++) {\n const node = parent.childNodes[i];\n if (found) {\n break;\n }\n if (node.nodeType === 3) {\n if (offset + node.length >= position) {\n found = true;\n const range = ctx.document.createRange();\n range.setStart(node, position - offset);\n sel.removeAllRanges();\n sel.addRange(range);\n break;\n } else {\n offset += node.length;\n }\n } else {\n find(pos, node);\n }\n }\n };\n find(pos, element);\n }\n\n return element;\n };\n\n /**\n * Get the offset\n *\n * @return {object} The offset\n */\n const getOffset = () => {\n const range = getRange();\n let offset = {\n height: 0,\n left: 0,\n right: 0,\n };\n\n if (!range) {\n return offset;\n }\n\n const hasCustomPos = ctx.customPos || ctx.customPos === 0;\n\n // endContainer in Firefox would be the element at the start of\n // the line\n if ((range.endOffset - 1 > 0 && range.endContainer !== element) || hasCustomPos) {\n const clonedRange = range.cloneRange();\n const fixedPosition = hasCustomPos ? ctx.customPos : range.endOffset;\n clonedRange.setStart(range.endContainer, fixedPosition - 1 < 0 ? 0 : fixedPosition - 1);\n clonedRange.setEnd(range.endContainer, fixedPosition);\n const rect = clonedRange.getBoundingClientRect();\n offset = {\n height: rect.height,\n left: rect.left + rect.width,\n top: rect.top,\n };\n clonedRange.detach();\n }\n\n if ((!offset || (offset && offset.height === 0)) && !ctx.noShadowCaret) {\n const clonedRange = range.cloneRange();\n const shadowCaret = ctx.document.createTextNode('|');\n clonedRange.insertNode(shadowCaret);\n clonedRange.selectNode(shadowCaret);\n const rect = clonedRange.getBoundingClientRect();\n offset = {\n height: rect.height,\n left: rect.left,\n top: rect.top,\n };\n shadowCaret.parentNode.removeChild(shadowCaret);\n clonedRange.detach();\n }\n\n if (offset) {\n const doc = ctx.document.documentElement;\n offset.top += ctx.window.pageYOffset - (doc.clientTop || 0);\n offset.left += ctx.window.pageXOffset - (doc.clientLeft || 0);\n }\n\n return offset;\n };\n\n /**\n * Get the position\n *\n * @return {object} The position\n */\n const getPosition = () => {\n const offset = getOffset();\n const pos = getPos();\n const rect = element.getBoundingClientRect();\n const inputOffset = {\n top: rect.top + ctx.document.body.scrollTop,\n left: rect.left + ctx.document.body.scrollLeft\n };\n offset.left -= inputOffset.left;\n offset.top -= inputOffset.top;\n offset.pos = pos;\n\n return offset;\n };\n\n /**\n * Get the range\n *\n * @return {Range|null}\n */\n const getRange = () => {\n if (!ctx.window.getSelection) {\n return;\n }\n const sel = ctx.window.getSelection();\n\n return sel.rangeCount > 0 ? sel.getRangeAt(0) : null;\n };\n\n /**\n * Get the caret position\n *\n * @return {int} The position\n */\n const getPos = () => {\n const range = getRange();\n const clonedRange = range.cloneRange();\n clonedRange.selectNodeContents(element);\n clonedRange.setEnd(range.endContainer, range.endOffset);\n const pos = clonedRange.toString().length;\n clonedRange.detach();\n\n return pos;\n };\n\n return {\n getPos,\n setPos,\n getPosition,\n getOffset,\n getRange,\n };\n};\n\nexport default createEditableCaret;\n","import createInputCaret from './input';\nimport createEditableCaret from './editable';\nimport {\n isContentEditable,\n getContext,\n isObject,\n} from './utils';\n\nexport { getOffset } from './utils';\n\nconst createCaret = (element, ctx) => {\n if (isContentEditable(element)) {\n return createEditableCaret(element, ctx);\n }\n\n return createInputCaret(element, ctx);\n};\n\nexport const position = (element, value, settings = {}) => {\n let options = settings;\n if (isObject(value)) {\n options = value;\n value = null;\n }\n const ctx = getContext(options);\n const caret = createCaret(element, ctx);\n\n if (value || value === 0) {\n return caret.setPos(value);\n }\n\n return caret.getPosition();\n};\n\n/**\n *\n * @param {Element} element The DOM element\n * @param {number|undefined} value The value to set\n * @param {object} settings Any settings for context\n */\nexport const offset = (element, value, settings = {}) => {\n let options = settings;\n if (isObject(value)) {\n options = value;\n value = null;\n }\n\n const ctx = getContext(options);\n const caret = createCaret(element, ctx);\n return caret.getOffset(value);\n};\n","import * as DataEvent from '../events/DataEvent';\nimport DateUtils from '../utilities/DateUtils';\nimport\n{\n position,\n offset\n}\nfrom 'caret-pos';\nimport EventEmitter from '../events/EventEmitter';\nimport * as EditorEvent from '../events/EditorEvent';\nclass TextEditor extends EventEmitter\n{\n //--------------------------\n // constructor\n //--------------------------\n constructor(textEditor, scrollLimit)\n {\n super();\n hljs.initHighlightingOnLoad();\n this.dateUtils = new DateUtils();\n this.textEditor = textEditor;\n this.fixLimit = scrollLimit;\n this.caretPos = null;\n this.url = '';\n let self = this;\n this.setInputs();\n window.addEventListener(\"scroll\", f =>\n {\n var fixLimit = this.fixLimit;\n if (window.pageYOffset >= fixLimit)\n {\n document.getElementById('edit-control').style.position = \"fixed\"\n }\n else\n {\n document.getElementById('edit-control').style.position = \"relative\"\n }\n });\n this.refresh();\n }\n //--------------------------\n // methods\n //--------------------------\n setInputs()\n {\n let self = this;\n var editorButtons = document.querySelectorAll('.editor-button');\n for (var i = 0, length = editorButtons.length; i < length; i++)\n {\n editorButtons[i].addEventListener('click', e => this.handleEditorOption(e), false);\n }\n this.textEditor.addEventListener('input', f =>\n {\n if (f.inputType == \"insertParagraph\")\n {\n var caret = position(self.textEditor).pos + 1;\n var spiffed = hljs.highlight('markdown', self.textEditor.innerText).value;\n var temp = document.createElement(\"div\");\n temp.innerText = spiffed;\n self.textEditor.innerHTML = temp.innerText;\n position(self.textEditor, caret)\n }\n else\n {\n self.refresh()\n }\n })\n }\n refresh()\n {\n var caret = position(this.textEditor).pos;\n var spiffed = hljs.highlight('markdown', this.textEditor.innerText).value;\n var temp = document.createElement(\"div\");\n temp.innerText = spiffed;\n this.textEditor.innerHTML = temp.innerText;\n position(this.textEditor, caret)\n }\n notify(type, data)\n {\n switch (type)\n {\n case DataEvent.POST_UPDATED:\n document.getElementById('submit-update').classList.add('icon-hide');\n document.getElementById('submit-good').classList.remove('icon-hide');\n document.getElementById('edit-update').classList.remove('submit-start');\n document.getElementById('edit-update').classList.add('submit-cool');\n setTimeout(f =>\n {\n document.getElementById('submit-update').classList.remove('icon-hide');\n document.getElementById('submit-good').classList.add('icon-hide');\n document.getElementById('edit-update').classList.add('submit-start');\n document.getElementById('edit-update').classList.remove('submit-cool');\n }, 2000);\n break;\n case DataEvent.POST_ADDED:\n // do nothing\n break;\n case EditorEvent.EDITOR_UPLOAD_POST_IMAGE:\n position(this.textEditor, this.caretPos);\n var sel, range, pulled;\n sel = window.getSelection(); //console.log(sel)\n //console.log(note.message)\n if (sel.rangeCount)\n {\n range = sel.getRangeAt(0);\n pulled = sel.getRangeAt(0).toString();\n range.deleteContents();\n range.insertNode(document.createTextNode(\"![image alt text](\" + data + \" 'image title')\"));\n }\n this.refresh();\n break;\n }\n }\n //--------------------------\n // event handlers\n //--------------------------\n handleEditorOption(e)\n {\n e.preventDefault();\n var self = this;\n var sel, range, pulled;\n sel = window.getSelection(); //console.log(sel)\n if (sel.rangeCount)\n {\n range = sel.getRangeAt(0);\n pulled = sel.getRangeAt(0).toString();\n range.deleteContents();\n switch (e.target.id)\n {\n case \"edit-bold\":\n range.insertNode(document.createTextNode(\"**\" + pulled + \"**\"));\n break;\n case \"edit-italic\":\n range.insertNode(document.createTextNode(\"*\" + pulled + \"*\"));\n break;\n case \"edit-strikethrough\":\n range.insertNode(document.createTextNode(\"<del>\" + pulled + \"</del>\"));\n break;\n case \"edit-header1\":\n range.insertNode(document.createTextNode(\"# \" + pulled));\n break;\n case \"edit-header2\":\n range.insertNode(document.createTextNode(\"## \" + pulled));\n break;\n case \"edit-header3\":\n range.insertNode(document.createTextNode(\"### \" + pulled));\n break;\n case \"edit-image\":\n this.caretPos = position(this.textEditor).pos;\n this.emitEvent(EditorEvent.EDITOR_UPLOAD_POST_IMAGE);\n break;\n case \"submit-save\":\n case \"edit-save\":\n this.emitEvent(EditorEvent.EDITOR_SAVE);\n break;\n case \"submit-update\":\n case \"edit-update\":\n this.emitEvent(EditorEvent.EDITOR_UPDATE);\n break\n case \"edit-link\":\n range.insertNode(document.createTextNode(\"[\" + pulled + \"](PASTE URL HERE)\"));\n break;\n case \"edit-delete\":\n this.emitEvent(EditorEvent.EDITOR_DELETE);\n break\n default:\n //range.insertNode(document.createTextNode(\"[\" + self.url + \"](PASTE URL HERE)\"));\n break;\n }\n }\n this.refresh()\n }\n}\nexport default TextEditor","//TOOLS\nimport DataUtils,\n{\n REQUEST_TYPE_GET,\n REQUEST_TYPE_PUT,\n REQUEST_TYPE_POST,\n REQUEST_TYPE_DELETE,\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_FORM\n}\nfrom '../../../../../brain/tools/utilities/DataUtils';\nimport * as DataEvent from '../../../../../brain/tools/events/DataEvent';\nimport Animate from '../../../../../brain/tools/effects/Animate';\nimport PostActions from '../actions/PostActions';\nimport * as EditorEvent from '../../../../../brain/tools/events/EditorEvent';\nimport TinyDatePicker from 'tiny-date-picker';\nimport DateUtils from '../../../../../brain/tools/utilities/DateUtils';\nimport TextEditor from '../../../../../brain/tools/ui/TextEditor';\nclass PostEditor\n{\n //--------------------------\n // constructor\n //--------------------------\n constructor()\n {\n //reframe('iframe');\n let self = this;\n this.uploadFiles;\n this.anim = new Animate();\n this.dataUtils = new DataUtils\n this.dateUtils = new DateUtils();\n if (document.getElementById('edit-post-text'))\n {\n this.editor = new TextEditor(document.getElementById('edit-post-text'), document.getElementById('header').offsetHeight + document.getElementById('post-header').offsetHeight + document.getElementById('post-feature').offsetHeight);\n this.editor.addListener(EditorEvent.EDITOR_DELETE, f => this.handleEditorOptions(EditorEvent.EDITOR_DELETE), false)\n this.editor.addListener(EditorEvent.EDITOR_UPLOAD_POST_IMAGE, f => this.handleEditorOptions(EditorEvent.EDITOR_UPLOAD_POST_IMAGE), false)\n this.editor.addListener(EditorEvent.EDITOR_UPDATE, f => this.handleEditorOptions(EditorEvent.EDITOR_UPDATE), false)\n this.editor.addListener(EditorEvent.EDITOR_SAVE, f => this.handleEditorOptions(EditorEvent.EDITOR_SAVE), false)\n document.getElementById('post-image').addEventListener('change', e => this.handlePostImageAdd(e), false);\n TinyDatePicker(document.getElementById('post-date'),\n {\n mode: 'dp-below',\n format(date)\n {\n //return date;\n return self.dateUtils.getDate('origin', date);\n }\n });\n }\n this.start();\n }\n //--------------------------\n // methods\n //--------------------------\n start()\n {\n let self = this;\n new Animate().object(\n {\n targets: document.getElementById('loader'),\n duration: 300,\n opacity: 0,\n easing: 'easeInOutQuad',\n complete: function()\n {\n document.getElementById('loader').style.display = 'none';\n document.getElementById('loader').style.visibility = 'hidden';\n new Animate().object(\n {\n targets: document.getElementById('header'),\n duration: 10,\n opacity: 1,\n easing: 'easeInOutQuad',\n complete: function()\n {\n if (document.getElementById('the-intro')) document.getElementById('the-intro').style.opacity = 1;\n if (document.getElementById('blog-entry')) document.getElementById('blog-entry').style.opacity = 1;\n }\n });\n }\n });\n if (document.getElementById('featured-image-drop'))\n {\n document.getElementById('featured-image-drop').addEventListener('dragover', this.handleDragOver, false);\n document.getElementById('featured-image-drop').addEventListener('drop', this.handleDrop, false);\n document.getElementById('featured-click').addEventListener('change', this.handleClicked, false);\n if (document.getElementById('new-upload-link'))\n {\n document.getElementById('new-upload-link').addEventListener('click', e =>\n {\n document.getElementById('featured-click').click();\n })\n }\n var optionButtons = document.querySelectorAll('.post-option-btn');\n for (var i = 0, length = optionButtons.length; i < length; i++)\n {\n optionButtons[i].addEventListener('click', e => this.handlePostOptions(e), false);\n }\n }\n }\n //--------------------------\n // event handlers\n //--------------------------\n handlePostOptions(e)\n {\n let currentOption;\n switch (e.target.id)\n {\n case \"option-page-icon\":\n case \"option-page\":\n currentOption = document.getElementById('option-page');\n break;\n case \"option-feature-icon\":\n case \"option-feature\":\n currentOption = document.getElementById('option-feature');\n break;\n case \"option-published-icon\":\n case \"option-published\":\n currentOption = document.getElementById('option-published');\n break;\n }\n let active = currentOption.getAttribute('data-active');\n (active == 'false') ? currentOption.setAttribute('data-active', 'true'): currentOption.setAttribute('data-active', 'false')\n }\n handleEditorOptions(e)\n {\n switch (e)\n {\n case EditorEvent.EDITOR_SAVE:\n case EditorEvent.EDITOR_UPDATE:\n let edit = false;\n if (e == EditorEvent.EDITOR_UPDATE) edit = true;\n new PostActions().submitPost(edit, PostEditor.uploadFiles).then((response) =>\n {\n let note = JSON.parse(response['response']['request'].response);\n this.editor.notify(note.message, note.postID);\n if (note.message == DataEvent.POST_ADDED) window.location = \"/@/dashboard/posts/edit/\" + note.postID;\n }).catch((err) =>\n {\n console.log(err)\n });\n break;\n case EditorEvent.EDITOR_DELETE:\n if (confirm('Aye! You know you\\'re deleting this post, right?'))\n {\n new PostActions().deletePost().then((response) =>\n {\n let note = JSON.parse(response['response']['request'].response);\n window.location = \"/@/dashboard/posts/\";\n //console.log(note);\n }).catch((err) =>\n {\n console.log(err)\n });\n }\n else\n {\n // Do nothing!\n }\n break;\n case EditorEvent.EDITOR_UPLOAD_POST_IMAGE:\n document.getElementById('post-image').click();\n break;\n }\n }\n handleDragOver(e)\n {\n e.stopPropagation();\n e.preventDefault();\n e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.\n }\n handleClicked(e)\n {\n e.stopPropagation();\n e.preventDefault();\n //console.log(\"IMAGES \" + e.target.files);\n PostEditor.uploadFiles = e.target.files;\n for (var i = 0, f; f = PostEditor.uploadFiles[i]; i++)\n {\n // Only process image files.\n if (!f.type.match('image.*'))\n {\n continue;\n }\n var reader = new FileReader();\n // Closure to capture the file information.\n reader.onload = (function(theFile)\n {\n return function(f)\n {\n // Render thumbnail.\n var image = document.createElement('img');\n image.src = f.target.result;\n image.title = escape(theFile.name);\n var span = document.createElement('div');\n span.innerHTML = ['<img src=\"',\n f.target.result, '\" title=\"',\n escape(theFile.name), '\"/>'\n ].join('');\n //document.getElementById('featured-image-drop').insertBefore(span, null);\n document.getElementById('featured-image-drop').innerHTML = '';\n document.getElementById('featured-image-drop').appendChild(image);\n };\n })(f);\n // Read in the image file as a data URL.\n reader.readAsDataURL(f);\n }\n }\n handleDrop(e)\n {\n e.stopPropagation();\n e.preventDefault();\n PostEditor.uploadFiles = e.dataTransfer.files;\n //console.log(MemberArea.uploadFiles.length);\n for (var i = 0, f; f = PostEditor.uploadFiles[i]; i++)\n {\n // Only process image files.\n if (!f.type.match('image.*'))\n {\n continue;\n }\n var reader = new FileReader();\n // Closure to capture the file information.\n reader.onload = (function(theFile)\n {\n return function(f)\n {\n // Render thumbnail.\n var span = document.createElement('span');\n span.innerHTML = ['<img src=\"',\n f.target.result, '\" title=\"',\n escape(theFile.name), '\"/>'\n ].join('');\n //document.getElementById('featured-image-drop').insertBefore(span, null);\n document.getElementById('featured-image-drop').innerHTML = '';\n document.getElementById('featured-image-drop').appendChild(span);\n };\n })(f);\n // Read in the image file as a data URL.\n reader.readAsDataURL(f);\n }\n }\n handlePostImageAdd(e)\n {\n e.stopPropagation();\n e.preventDefault();\n let self = this;\n var postData = new FormData();\n var files = e.target.files;\n for (var i = 0; i < files.length; i++)\n {\n var file = files[i];\n // Check the file type.\n if (!file.type.match('image.*'))\n {\n continue;\n }\n postData.append('post_image', file, file.name);\n }\n this.dataUtils.request(\"/api/blog/add-post-image\", DataEvent.POST_IMAGE_ADDED, REQUEST_TYPE_POST, CONTENT_TYPE_FORM, postData).then((response) =>\n {\n self.editor.notify(EditorEvent.EDITOR_UPLOAD_POST_IMAGE, JSON.parse(response.request['response']).url);\n }).catch((err) =>\n {\n console.log(err)\n })\n }\n}\nPostEditor.uploadFiles = [];\nexport\n{\n PostEditor as\n default\n}","//TOOLS\nimport DataUtils, {\n REQUEST_TYPE_GET,\n REQUEST_TYPE_PUT,\n REQUEST_TYPE_POST,\n REQUEST_TYPE_DELETE,\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_FORM\n} from '../../../../../brain/tools/utilities/DataUtils';\nimport PostEditor from './PostEditor';\nimport Animate from '../../../../../brain/tools/effects/Animate';\n\nclass DisplayManager {\n //--------------------------\n // constructor\n //--------------------------\n constructor() {\n this.dataUtils = new DataUtils();\n this.currentDisplay = '';\n this.urlPieces = document.URL.split(\"/\");\n //grab url so system knows what to display \n this.chooseDisplay(this.urlPieces[5], this.urlPieces[6]);\n }\n //--------------------------\n // methods\n //--------------------------\n start() {\n let self = this;\n // new stuff\n new Animate().object({\n targets: document.getElementById('loader'),\n duration: 300,\n opacity: 0,\n easing: 'easeInOutQuad',\n complete: function () {\n document.getElementById('loader').style.display = 'none';\n document.getElementById('loader').style.visibility = 'hidden';\n new Animate().object({\n targets: document.getElementById('header'),\n duration: 10,\n opacity: 1,\n easing: 'easeInOutQuad',\n complete: function () {\n document.getElementById('loader').style.display = 'none';\n document.getElementById('loader').style.visibility = 'hidden';\n }\n });\n }\n });\n }\n\n chooseDisplay(section, page) {\n this.currentDisplay = '';\n switch (section) {\n case 'posts':\n this.currentDisplay = new PostEditor();\n break;\n \n default:\n // just chill\n break;\n }\n this.start();\n\n }\n //--------------------------\n // event handlers\n //--------------------------\n\n}\nexport {\n DisplayManager as\n default\n}","'use strict';\n\nmodule.exports = argsArray;\n\nfunction argsArray(fun) {\n return function () {\n var len = arguments.length;\n if (len) {\n var args = [];\n var i = -1;\n while (++i < len) {\n args[i] = arguments[i];\n }\n return fun.call(this, args);\n } else {\n return fun.call(this, []);\n }\n };\n}","'use strict';\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nvar scheduleDrain;\n\n{\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = (called = ++called % 2);\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n\n // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n","(function (factory) {\n if (typeof exports === 'object') {\n // Node/CommonJS\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD\n define(factory);\n } else {\n // Browser globals (with support for web workers)\n var glob;\n\n try {\n glob = window;\n } catch (e) {\n glob = self;\n }\n\n glob.SparkMD5 = factory();\n }\n}(function (undefined) {\n\n 'use strict';\n\n /*\n * Fastest md5 implementation around (JKM md5).\n * Credits: Joseph Myers\n *\n * @see http://www.myersdaily.org/joseph/javascript/md5-text.html\n * @see http://jsperf.com/md5-shootout/7\n */\n\n /* this function is much faster,\n so if possible we use it. Some IEs\n are the only ones I know of that\n need the idiotic second function,\n generated by an if clause. */\n var add32 = function (a, b) {\n return (a + b) & 0xFFFFFFFF;\n },\n hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\n\n\n function cmn(q, a, b, x, s, t) {\n a = add32(add32(a, q), add32(x, t));\n return add32((a << s) | (a >>> (32 - s)), b);\n }\n\n function md5cycle(x, k) {\n var a = x[0],\n b = x[1],\n c = x[2],\n d = x[3];\n\n a += (b & c | ~b & d) + k[0] - 680876936 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[1] - 389564586 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[2] + 606105819 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[3] - 1044525330 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[4] - 176418897 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[5] + 1200080426 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[6] - 1473231341 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[7] - 45705983 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[8] + 1770035416 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[9] - 1958414417 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[10] - 42063 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[11] - 1990404162 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n a += (b & c | ~b & d) + k[12] + 1804603682 | 0;\n a = (a << 7 | a >>> 25) + b | 0;\n d += (a & b | ~a & c) + k[13] - 40341101 | 0;\n d = (d << 12 | d >>> 20) + a | 0;\n c += (d & a | ~d & b) + k[14] - 1502002290 | 0;\n c = (c << 17 | c >>> 15) + d | 0;\n b += (c & d | ~c & a) + k[15] + 1236535329 | 0;\n b = (b << 22 | b >>> 10) + c | 0;\n\n a += (b & d | c & ~d) + k[1] - 165796510 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[6] - 1069501632 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[11] + 643717713 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[0] - 373897302 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[5] - 701558691 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[10] + 38016083 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[15] - 660478335 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[4] - 405537848 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[9] + 568446438 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[14] - 1019803690 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[3] - 187363961 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[8] + 1163531501 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n a += (b & d | c & ~d) + k[13] - 1444681467 | 0;\n a = (a << 5 | a >>> 27) + b | 0;\n d += (a & c | b & ~c) + k[2] - 51403784 | 0;\n d = (d << 9 | d >>> 23) + a | 0;\n c += (d & b | a & ~b) + k[7] + 1735328473 | 0;\n c = (c << 14 | c >>> 18) + d | 0;\n b += (c & a | d & ~a) + k[12] - 1926607734 | 0;\n b = (b << 20 | b >>> 12) + c | 0;\n\n a += (b ^ c ^ d) + k[5] - 378558 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[8] - 2022574463 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[11] + 1839030562 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[14] - 35309556 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[1] - 1530992060 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[4] + 1272893353 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[7] - 155497632 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[10] - 1094730640 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[13] + 681279174 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[0] - 358537222 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[3] - 722521979 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[6] + 76029189 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n a += (b ^ c ^ d) + k[9] - 640364487 | 0;\n a = (a << 4 | a >>> 28) + b | 0;\n d += (a ^ b ^ c) + k[12] - 421815835 | 0;\n d = (d << 11 | d >>> 21) + a | 0;\n c += (d ^ a ^ b) + k[15] + 530742520 | 0;\n c = (c << 16 | c >>> 16) + d | 0;\n b += (c ^ d ^ a) + k[2] - 995338651 | 0;\n b = (b << 23 | b >>> 9) + c | 0;\n\n a += (c ^ (b | ~d)) + k[0] - 198630844 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[7] + 1126891415 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[14] - 1416354905 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[5] - 57434055 | 0;\n b = (b << 21 |b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[12] + 1700485571 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[3] - 1894986606 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[10] - 1051523 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[1] - 2054922799 | 0;\n b = (b << 21 |b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[8] + 1873313359 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[15] - 30611744 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[6] - 1560198380 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[13] + 1309151649 | 0;\n b = (b << 21 |b >>> 11) + c | 0;\n a += (c ^ (b | ~d)) + k[4] - 145523070 | 0;\n a = (a << 6 | a >>> 26) + b | 0;\n d += (b ^ (a | ~c)) + k[11] - 1120210379 | 0;\n d = (d << 10 | d >>> 22) + a | 0;\n c += (a ^ (d | ~b)) + k[2] + 718787259 | 0;\n c = (c << 15 | c >>> 17) + d | 0;\n b += (d ^ (c | ~a)) + k[9] - 343485551 | 0;\n b = (b << 21 | b >>> 11) + c | 0;\n\n x[0] = a + x[0] | 0;\n x[1] = b + x[1] | 0;\n x[2] = c + x[2] | 0;\n x[3] = d + x[3] | 0;\n }\n\n function md5blk(s) {\n var md5blks = [],\n i; /* Andy King said do it this way. */\n\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);\n }\n return md5blks;\n }\n\n function md5blk_array(a) {\n var md5blks = [],\n i; /* Andy King said do it this way. */\n\n for (i = 0; i < 64; i += 4) {\n md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);\n }\n return md5blks;\n }\n\n function md51(s) {\n var n = s.length,\n state = [1732584193, -271733879, -1732584194, 271733878],\n i,\n length,\n tail,\n tmp,\n lo,\n hi;\n\n for (i = 64; i <= n; i += 64) {\n md5cycle(state, md5blk(s.substring(i - 64, i)));\n }\n s = s.substring(i - 64);\n length = s.length;\n tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);\n }\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n\n // Beware that the final length might not fit in 32 bits so we take care of that\n tmp = n * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n\n tail[14] = lo;\n tail[15] = hi;\n\n md5cycle(state, tail);\n return state;\n }\n\n function md51_array(a) {\n var n = a.length,\n state = [1732584193, -271733879, -1732584194, 271733878],\n i,\n length,\n tail,\n tmp,\n lo,\n hi;\n\n for (i = 64; i <= n; i += 64) {\n md5cycle(state, md5blk_array(a.subarray(i - 64, i)));\n }\n\n // Not sure if it is a bug, however IE10 will always produce a sub array of length 1\n // containing the last element of the parent array if the sub array specified starts\n // beyond the length of the parent array - weird.\n // https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue\n a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);\n\n length = a.length;\n tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= a[i] << ((i % 4) << 3);\n }\n\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(state, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n\n // Beware that the final length might not fit in 32 bits so we take care of that\n tmp = n * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n\n tail[14] = lo;\n tail[15] = hi;\n\n md5cycle(state, tail);\n\n return state;\n }\n\n function rhex(n) {\n var s = '',\n j;\n for (j = 0; j < 4; j += 1) {\n s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];\n }\n return s;\n }\n\n function hex(x) {\n var i;\n for (i = 0; i < x.length; i += 1) {\n x[i] = rhex(x[i]);\n }\n return x.join('');\n }\n\n // In some cases the fast add32 function cannot be used..\n if (hex(md51('hello')) !== '5d41402abc4b2a76b9719d911017c592') {\n add32 = function (x, y) {\n var lsw = (x & 0xFFFF) + (y & 0xFFFF),\n msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return (msw << 16) | (lsw & 0xFFFF);\n };\n }\n\n // ---------------------------------------------------\n\n /**\n * ArrayBuffer slice polyfill.\n *\n * @see https://github.com/ttaubert/node-arraybuffer-slice\n */\n\n if (typeof ArrayBuffer !== 'undefined' && !ArrayBuffer.prototype.slice) {\n (function () {\n function clamp(val, length) {\n val = (val | 0) || 0;\n\n if (val < 0) {\n return Math.max(val + length, 0);\n }\n\n return Math.min(val, length);\n }\n\n ArrayBuffer.prototype.slice = function (from, to) {\n var length = this.byteLength,\n begin = clamp(from, length),\n end = length,\n num,\n target,\n targetArray,\n sourceArray;\n\n if (to !== undefined) {\n end = clamp(to, length);\n }\n\n if (begin > end) {\n return new ArrayBuffer(0);\n }\n\n num = end - begin;\n target = new ArrayBuffer(num);\n targetArray = new Uint8Array(target);\n\n sourceArray = new Uint8Array(this, begin, num);\n targetArray.set(sourceArray);\n\n return target;\n };\n })();\n }\n\n // ---------------------------------------------------\n\n /**\n * Helpers.\n */\n\n function toUtf8(str) {\n if (/[\\u0080-\\uFFFF]/.test(str)) {\n str = unescape(encodeURIComponent(str));\n }\n\n return str;\n }\n\n function utf8Str2ArrayBuffer(str, returnUInt8Array) {\n var length = str.length,\n buff = new ArrayBuffer(length),\n arr = new Uint8Array(buff),\n i;\n\n for (i = 0; i < length; i += 1) {\n arr[i] = str.charCodeAt(i);\n }\n\n return returnUInt8Array ? arr : buff;\n }\n\n function arrayBuffer2Utf8Str(buff) {\n return String.fromCharCode.apply(null, new Uint8Array(buff));\n }\n\n function concatenateArrayBuffers(first, second, returnUInt8Array) {\n var result = new Uint8Array(first.byteLength + second.byteLength);\n\n result.set(new Uint8Array(first));\n result.set(new Uint8Array(second), first.byteLength);\n\n return returnUInt8Array ? result : result.buffer;\n }\n\n function hexToBinaryString(hex) {\n var bytes = [],\n length = hex.length,\n x;\n\n for (x = 0; x < length - 1; x += 2) {\n bytes.push(parseInt(hex.substr(x, 2), 16));\n }\n\n return String.fromCharCode.apply(String, bytes);\n }\n\n // ---------------------------------------------------\n\n /**\n * SparkMD5 OOP implementation.\n *\n * Use this class to perform an incremental md5, otherwise use the\n * static methods instead.\n */\n\n function SparkMD5() {\n // call reset to init the instance\n this.reset();\n }\n\n /**\n * Appends a string.\n * A conversion will be applied if an utf8 string is detected.\n *\n * @param {String} str The string to be appended\n *\n * @return {SparkMD5} The instance itself\n */\n SparkMD5.prototype.append = function (str) {\n // Converts the string to utf8 bytes if necessary\n // Then append as binary\n this.appendBinary(toUtf8(str));\n\n return this;\n };\n\n /**\n * Appends a binary string.\n *\n * @param {String} contents The binary string to be appended\n *\n * @return {SparkMD5} The instance itself\n */\n SparkMD5.prototype.appendBinary = function (contents) {\n this._buff += contents;\n this._length += contents.length;\n\n var length = this._buff.length,\n i;\n\n for (i = 64; i <= length; i += 64) {\n md5cycle(this._hash, md5blk(this._buff.substring(i - 64, i)));\n }\n\n this._buff = this._buff.substring(i - 64);\n\n return this;\n };\n\n /**\n * Finishes the incremental computation, reseting the internal state and\n * returning the result.\n *\n * @param {Boolean} raw True to get the raw string, false to get the hex string\n *\n * @return {String} The result\n */\n SparkMD5.prototype.end = function (raw) {\n var buff = this._buff,\n length = buff.length,\n i,\n tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n ret;\n\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);\n }\n\n this._finish(tail, length);\n ret = hex(this._hash);\n\n if (raw) {\n ret = hexToBinaryString(ret);\n }\n\n this.reset();\n\n return ret;\n };\n\n /**\n * Resets the internal state of the computation.\n *\n * @return {SparkMD5} The instance itself\n */\n SparkMD5.prototype.reset = function () {\n this._buff = '';\n this._length = 0;\n this._hash = [1732584193, -271733879, -1732584194, 271733878];\n\n return this;\n };\n\n /**\n * Gets the internal state of the computation.\n *\n * @return {Object} The state\n */\n SparkMD5.prototype.getState = function () {\n return {\n buff: this._buff,\n length: this._length,\n hash: this._hash\n };\n };\n\n /**\n * Gets the internal state of the computation.\n *\n * @param {Object} state The state\n *\n * @return {SparkMD5} The instance itself\n */\n SparkMD5.prototype.setState = function (state) {\n this._buff = state.buff;\n this._length = state.length;\n this._hash = state.hash;\n\n return this;\n };\n\n /**\n * Releases memory used by the incremental buffer and other additional\n * resources. If you plan to use the instance again, use reset instead.\n */\n SparkMD5.prototype.destroy = function () {\n delete this._hash;\n delete this._buff;\n delete this._length;\n };\n\n /**\n * Finish the final calculation based on the tail.\n *\n * @param {Array} tail The tail (will be modified)\n * @param {Number} length The length of the remaining buffer\n */\n SparkMD5.prototype._finish = function (tail, length) {\n var i = length,\n tmp,\n lo,\n hi;\n\n tail[i >> 2] |= 0x80 << ((i % 4) << 3);\n if (i > 55) {\n md5cycle(this._hash, tail);\n for (i = 0; i < 16; i += 1) {\n tail[i] = 0;\n }\n }\n\n // Do the final computation based on the tail and length\n // Beware that the final length may not fit in 32 bits so we take care of that\n tmp = this._length * 8;\n tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);\n lo = parseInt(tmp[2], 16);\n hi = parseInt(tmp[1], 16) || 0;\n\n tail[14] = lo;\n tail[15] = hi;\n md5cycle(this._hash, tail);\n };\n\n /**\n * Performs the md5 hash on a string.\n * A conversion will be applied if utf8 string is detected.\n *\n * @param {String} str The string\n * @param {Boolean} raw True to get the raw string, false to get the hex string\n *\n * @return {String} The result\n */\n SparkMD5.hash = function (str, raw) {\n // Converts the string to utf8 bytes if necessary\n // Then compute it using the binary function\n return SparkMD5.hashBinary(toUtf8(str), raw);\n };\n\n /**\n * Performs the md5 hash on a binary string.\n *\n * @param {String} content The binary string\n * @param {Boolean} raw True to get the raw string, false to get the hex string\n *\n * @return {String} The result\n */\n SparkMD5.hashBinary = function (content, raw) {\n var hash = md51(content),\n ret = hex(hash);\n\n return raw ? hexToBinaryString(ret) : ret;\n };\n\n // ---------------------------------------------------\n\n /**\n * SparkMD5 OOP implementation for array buffers.\n *\n * Use this class to perform an incremental md5 ONLY for array buffers.\n */\n SparkMD5.ArrayBuffer = function () {\n // call reset to init the instance\n this.reset();\n };\n\n /**\n * Appends an array buffer.\n *\n * @param {ArrayBuffer} arr The array to be appended\n *\n * @return {SparkMD5.ArrayBuffer} The instance itself\n */\n SparkMD5.ArrayBuffer.prototype.append = function (arr) {\n var buff = concatenateArrayBuffers(this._buff.buffer, arr, true),\n length = buff.length,\n i;\n\n this._length += arr.byteLength;\n\n for (i = 64; i <= length; i += 64) {\n md5cycle(this._hash, md5blk_array(buff.subarray(i - 64, i)));\n }\n\n this._buff = (i - 64) < length ? new Uint8Array(buff.buffer.slice(i - 64)) : new Uint8Array(0);\n\n return this;\n };\n\n /**\n * Finishes the incremental computation, reseting the internal state and\n * returning the result.\n *\n * @param {Boolean} raw True to get the raw string, false to get the hex string\n *\n * @return {String} The result\n */\n SparkMD5.ArrayBuffer.prototype.end = function (raw) {\n var buff = this._buff,\n length = buff.length,\n tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n i,\n ret;\n\n for (i = 0; i < length; i += 1) {\n tail[i >> 2] |= buff[i] << ((i % 4) << 3);\n }\n\n this._finish(tail, length);\n ret = hex(this._hash);\n\n if (raw) {\n ret = hexToBinaryString(ret);\n }\n\n this.reset();\n\n return ret;\n };\n\n /**\n * Resets the internal state of the computation.\n *\n * @return {SparkMD5.ArrayBuffer} The instance itself\n */\n SparkMD5.ArrayBuffer.prototype.reset = function () {\n this._buff = new Uint8Array(0);\n this._length = 0;\n this._hash = [1732584193, -271733879, -1732584194, 271733878];\n\n return this;\n };\n\n /**\n * Gets the internal state of the computation.\n *\n * @return {Object} The state\n */\n SparkMD5.ArrayBuffer.prototype.getState = function () {\n var state = SparkMD5.prototype.getState.call(this);\n\n // Convert buffer to a string\n state.buff = arrayBuffer2Utf8Str(state.buff);\n\n return state;\n };\n\n /**\n * Gets the internal state of the computation.\n *\n * @param {Object} state The state\n *\n * @return {SparkMD5.ArrayBuffer} The instance itself\n */\n SparkMD5.ArrayBuffer.prototype.setState = function (state) {\n // Convert string to buffer\n state.buff = utf8Str2ArrayBuffer(state.buff, true);\n\n return SparkMD5.prototype.setState.call(this, state);\n };\n\n SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;\n\n SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;\n\n /**\n * Performs the md5 hash on an array buffer.\n *\n * @param {ArrayBuffer} arr The array buffer\n * @param {Boolean} raw True to get the raw string, false to get the hex one\n *\n * @return {String} The result\n */\n SparkMD5.ArrayBuffer.hash = function (arr, raw) {\n var hash = md51_array(new Uint8Array(arr)),\n ret = hex(hash);\n\n return raw ? hexToBinaryString(ret) : ret;\n };\n\n return SparkMD5;\n}));\n","// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n return bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] + '-' +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]] +\n bth[buf[i++]] + bth[buf[i++]];\n}\n\nmodule.exports = bytesToUuid;\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\nvar _clockseq;\n\n// Previous uuid creation time\nvar _lastMSecs = 0;\nvar _lastNSecs = 0;\n\n// See https://github.com/broofa/node-uuid for API details\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;\n\n // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n if (node == null || clockseq == null) {\n var seedBytes = rng();\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [\n seedBytes[0] | 0x01,\n seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]\n ];\n }\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n }\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : bytesToUuid(b);\n}\n\nmodule.exports = v1;\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n","var v1 = require('./v1');\nvar v4 = require('./v4');\n\nvar uuid = v4;\nuuid.v1 = v1;\nuuid.v4 = v4;\n\nmodule.exports = uuid;\n","'use strict';\n\n/**\n * Stringify/parse functions that don't operate\n * recursively, so they avoid call stack exceeded\n * errors.\n */\nexports.stringify = function stringify(input) {\n var queue = [];\n queue.push({obj: input});\n\n var res = '';\n var next, obj, prefix, val, i, arrayPrefix, keys, k, key, value, objPrefix;\n while ((next = queue.pop())) {\n obj = next.obj;\n prefix = next.prefix || '';\n val = next.val || '';\n res += prefix;\n if (val) {\n res += val;\n } else if (typeof obj !== 'object') {\n res += typeof obj === 'undefined' ? null : JSON.stringify(obj);\n } else if (obj === null) {\n res += 'null';\n } else if (Array.isArray(obj)) {\n queue.push({val: ']'});\n for (i = obj.length - 1; i >= 0; i--) {\n arrayPrefix = i === 0 ? '' : ',';\n queue.push({obj: obj[i], prefix: arrayPrefix});\n }\n queue.push({val: '['});\n } else { // object\n keys = [];\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n keys.push(k);\n }\n }\n queue.push({val: '}'});\n for (i = keys.length - 1; i >= 0; i--) {\n key = keys[i];\n value = obj[key];\n objPrefix = (i > 0 ? ',' : '');\n objPrefix += JSON.stringify(key) + ':';\n queue.push({obj: value, prefix: objPrefix});\n }\n queue.push({val: '{'});\n }\n }\n return res;\n};\n\n// Convenience function for the parse function.\n// This pop function is basically copied from\n// pouchCollate.parseIndexableString\nfunction pop(obj, stack, metaStack) {\n var lastMetaElement = metaStack[metaStack.length - 1];\n if (obj === lastMetaElement.element) {\n // popping a meta-element, e.g. an object whose value is another object\n metaStack.pop();\n lastMetaElement = metaStack[metaStack.length - 1];\n }\n var element = lastMetaElement.element;\n var lastElementIndex = lastMetaElement.index;\n if (Array.isArray(element)) {\n element.push(obj);\n } else if (lastElementIndex === stack.length - 2) { // obj with key+value\n var key = stack.pop();\n element[key] = obj;\n } else {\n stack.push(obj); // obj with key only\n }\n}\n\nexports.parse = function (str) {\n var stack = [];\n var metaStack = []; // stack for arrays and objects\n var i = 0;\n var collationIndex,parsedNum,numChar;\n var parsedString,lastCh,numConsecutiveSlashes,ch;\n var arrayElement, objElement;\n while (true) {\n collationIndex = str[i++];\n if (collationIndex === '}' ||\n collationIndex === ']' ||\n typeof collationIndex === 'undefined') {\n if (stack.length === 1) {\n return stack.pop();\n } else {\n pop(stack.pop(), stack, metaStack);\n continue;\n }\n }\n switch (collationIndex) {\n case ' ':\n case '\\t':\n case '\\n':\n case ':':\n case ',':\n break;\n case 'n':\n i += 3; // 'ull'\n pop(null, stack, metaStack);\n break;\n case 't':\n i += 3; // 'rue'\n pop(true, stack, metaStack);\n break;\n case 'f':\n i += 4; // 'alse'\n pop(false, stack, metaStack);\n break;\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n case '-':\n parsedNum = '';\n i--;\n while (true) {\n numChar = str[i++];\n if (/[\\d\\.\\-e\\+]/.test(numChar)) {\n parsedNum += numChar;\n } else {\n i--;\n break;\n }\n }\n pop(parseFloat(parsedNum), stack, metaStack);\n break;\n case '\"':\n parsedString = '';\n lastCh = void 0;\n numConsecutiveSlashes = 0;\n while (true) {\n ch = str[i++];\n if (ch !== '\"' || (lastCh === '\\\\' &&\n numConsecutiveSlashes % 2 === 1)) {\n parsedString += ch;\n lastCh = ch;\n if (lastCh === '\\\\') {\n numConsecutiveSlashes++;\n } else {\n numConsecutiveSlashes = 0;\n }\n } else {\n break;\n }\n }\n pop(JSON.parse('\"' + parsedString + '\"'), stack, metaStack);\n break;\n case '[':\n arrayElement = { element: [], index: stack.length };\n stack.push(arrayElement.element);\n metaStack.push(arrayElement);\n break;\n case '{':\n objElement = { element: {}, index: stack.length };\n stack.push(objElement.element);\n metaStack.push(objElement);\n break;\n default:\n throw new Error(\n 'unexpectedly reached end of input: ' + collationIndex);\n }\n }\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","import getArguments from 'argsarray';\nimport nextTick from 'immediate';\nimport { EventEmitter } from 'events';\nimport inherits from 'inherits';\nimport Md5 from 'spark-md5';\nimport uuidV4 from 'uuid';\nimport vuvuzela from 'vuvuzela';\n\nfunction isBinaryObject(object) {\n return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||\n (typeof Blob !== 'undefined' && object instanceof Blob);\n}\n\nfunction cloneArrayBuffer(buff) {\n if (typeof buff.slice === 'function') {\n return buff.slice(0);\n }\n // IE10-11 slice() polyfill\n var target = new ArrayBuffer(buff.byteLength);\n var targetArray = new Uint8Array(target);\n var sourceArray = new Uint8Array(buff);\n targetArray.set(sourceArray);\n return target;\n}\n\nfunction cloneBinaryObject(object) {\n if (object instanceof ArrayBuffer) {\n return cloneArrayBuffer(object);\n }\n var size = object.size;\n var type = object.type;\n // Blob\n if (typeof object.slice === 'function') {\n return object.slice(0, size, type);\n }\n // PhantomJS slice() replacement\n return object.webkitSlice(0, size, type);\n}\n\n// most of this is borrowed from lodash.isPlainObject:\n// https://github.com/fis-components/lodash.isplainobject/\n// blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js\n\nvar funcToString = Function.prototype.toString;\nvar objectCtorString = funcToString.call(Object);\n\nfunction isPlainObject(value) {\n var proto = Object.getPrototypeOf(value);\n /* istanbul ignore if */\n if (proto === null) { // not sure when this happens, but I guess it can\n return true;\n }\n var Ctor = proto.constructor;\n return (typeof Ctor == 'function' &&\n Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);\n}\n\nfunction clone(object) {\n var newObject;\n var i;\n var len;\n\n if (!object || typeof object !== 'object') {\n return object;\n }\n\n if (Array.isArray(object)) {\n newObject = [];\n for (i = 0, len = object.length; i < len; i++) {\n newObject[i] = clone(object[i]);\n }\n return newObject;\n }\n\n // special case: to avoid inconsistencies between IndexedDB\n // and other backends, we automatically stringify Dates\n if (object instanceof Date) {\n return object.toISOString();\n }\n\n if (isBinaryObject(object)) {\n return cloneBinaryObject(object);\n }\n\n if (!isPlainObject(object)) {\n return object; // don't clone objects like Workers\n }\n\n newObject = {};\n for (i in object) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(object, i)) {\n var value = clone(object[i]);\n if (typeof value !== 'undefined') {\n newObject[i] = value;\n }\n }\n }\n return newObject;\n}\n\nfunction once(fun) {\n var called = false;\n return getArguments(function (args) {\n /* istanbul ignore if */\n if (called) {\n // this is a smoke test and should never actually happen\n throw new Error('once called more than once');\n } else {\n called = true;\n fun.apply(this, args);\n }\n });\n}\n\nfunction toPromise(func) {\n //create the function we will be returning\n return getArguments(function (args) {\n // Clone arguments\n args = clone(args);\n var self = this;\n // if the last argument is a function, assume its a callback\n var usedCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;\n var promise = new Promise(function (fulfill, reject) {\n var resp;\n try {\n var callback = once(function (err, mesg) {\n if (err) {\n reject(err);\n } else {\n fulfill(mesg);\n }\n });\n // create a callback for this invocation\n // apply the function in the orig context\n args.push(callback);\n resp = func.apply(self, args);\n if (resp && typeof resp.then === 'function') {\n fulfill(resp);\n }\n } catch (e) {\n reject(e);\n }\n });\n // if there is a callback, call it back\n if (usedCB) {\n promise.then(function (result) {\n usedCB(null, result);\n }, usedCB);\n }\n return promise;\n });\n}\n\nfunction logApiCall(self, name, args) {\n /* istanbul ignore if */\n if (self.constructor.listeners('debug').length) {\n var logArgs = ['api', self.name, name];\n for (var i = 0; i < args.length - 1; i++) {\n logArgs.push(args[i]);\n }\n self.constructor.emit('debug', logArgs);\n\n // override the callback itself to log the response\n var origCallback = args[args.length - 1];\n args[args.length - 1] = function (err, res) {\n var responseArgs = ['api', self.name, name];\n responseArgs = responseArgs.concat(\n err ? ['error', err] : ['success', res]\n );\n self.constructor.emit('debug', responseArgs);\n origCallback(err, res);\n };\n }\n}\n\nfunction adapterFun(name, callback) {\n return toPromise(getArguments(function (args) {\n if (this._closed) {\n return Promise.reject(new Error('database is closed'));\n }\n if (this._destroyed) {\n return Promise.reject(new Error('database is destroyed'));\n }\n var self = this;\n logApiCall(self, name, args);\n if (!this.taskqueue.isReady) {\n return new Promise(function (fulfill, reject) {\n self.taskqueue.addTask(function (failed) {\n if (failed) {\n reject(failed);\n } else {\n fulfill(self[name].apply(self, args));\n }\n });\n });\n }\n return callback.apply(this, args);\n }));\n}\n\nfunction mangle(key) {\n return '$' + key;\n}\nfunction unmangle(key) {\n return key.substring(1);\n}\nfunction Map$1() {\n this._store = {};\n}\nMap$1.prototype.get = function (key) {\n var mangled = mangle(key);\n return this._store[mangled];\n};\nMap$1.prototype.set = function (key, value) {\n var mangled = mangle(key);\n this._store[mangled] = value;\n return true;\n};\nMap$1.prototype.has = function (key) {\n var mangled = mangle(key);\n return mangled in this._store;\n};\nMap$1.prototype.delete = function (key) {\n var mangled = mangle(key);\n var res = mangled in this._store;\n delete this._store[mangled];\n return res;\n};\nMap$1.prototype.forEach = function (cb) {\n var keys = Object.keys(this._store);\n for (var i = 0, len = keys.length; i < len; i++) {\n var key = keys[i];\n var value = this._store[key];\n key = unmangle(key);\n cb(value, key);\n }\n};\nObject.defineProperty(Map$1.prototype, 'size', {\n get: function () {\n return Object.keys(this._store).length;\n }\n});\n\nfunction Set$1(array) {\n this._store = new Map$1();\n\n // init with an array\n if (array && Array.isArray(array)) {\n for (var i = 0, len = array.length; i < len; i++) {\n this.add(array[i]);\n }\n }\n}\nSet$1.prototype.add = function (key) {\n return this._store.set(key, true);\n};\nSet$1.prototype.has = function (key) {\n return this._store.has(key);\n};\nSet$1.prototype.forEach = function (cb) {\n this._store.forEach(function (value, key) {\n cb(key);\n });\n};\nObject.defineProperty(Set$1.prototype, 'size', {\n get: function () {\n return this._store.size;\n }\n});\n\n/* global Map,Set,Symbol */\n// Based on https://kangax.github.io/compat-table/es6/ we can sniff out\n// incomplete Map/Set implementations which would otherwise cause our tests to fail.\n// Notably they fail in IE11 and iOS 8.4, which this prevents.\nfunction supportsMapAndSet() {\n if (typeof Symbol === 'undefined' || typeof Map === 'undefined' || typeof Set === 'undefined') {\n return false;\n }\n var prop = Object.getOwnPropertyDescriptor(Map, Symbol.species);\n return prop && 'get' in prop && Map[Symbol.species] === Map;\n}\n\n// based on https://github.com/montagejs/collections\n\nvar ExportedSet;\nvar ExportedMap;\n\n{\n if (supportsMapAndSet()) { // prefer built-in Map/Set\n ExportedSet = Set;\n ExportedMap = Map;\n } else { // fall back to our polyfill\n ExportedSet = Set$1;\n ExportedMap = Map$1;\n }\n}\n\n// like underscore/lodash _.pick()\nfunction pick(obj, arr) {\n var res = {};\n for (var i = 0, len = arr.length; i < len; i++) {\n var prop = arr[i];\n if (prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\n\n// Most browsers throttle concurrent requests at 6, so it's silly\n// to shim _bulk_get by trying to launch potentially hundreds of requests\n// and then letting the majority time out. We can handle this ourselves.\nvar MAX_NUM_CONCURRENT_REQUESTS = 6;\n\nfunction identityFunction(x) {\n return x;\n}\n\nfunction formatResultForOpenRevsGet(result) {\n return [{\n ok: result\n }];\n}\n\n// shim for P/CouchDB adapters that don't directly implement _bulk_get\nfunction bulkGet(db, opts, callback) {\n var requests = opts.docs;\n\n // consolidate into one request per doc if possible\n var requestsById = new ExportedMap();\n requests.forEach(function (request) {\n if (requestsById.has(request.id)) {\n requestsById.get(request.id).push(request);\n } else {\n requestsById.set(request.id, [request]);\n }\n });\n\n var numDocs = requestsById.size;\n var numDone = 0;\n var perDocResults = new Array(numDocs);\n\n function collapseResultsAndFinish() {\n var results = [];\n perDocResults.forEach(function (res) {\n res.docs.forEach(function (info) {\n results.push({\n id: res.id,\n docs: [info]\n });\n });\n });\n callback(null, {results: results});\n }\n\n function checkDone() {\n if (++numDone === numDocs) {\n collapseResultsAndFinish();\n }\n }\n\n function gotResult(docIndex, id, docs) {\n perDocResults[docIndex] = {id: id, docs: docs};\n checkDone();\n }\n\n var allRequests = [];\n requestsById.forEach(function (value, key) {\n allRequests.push(key);\n });\n\n var i = 0;\n\n function nextBatch() {\n\n if (i >= allRequests.length) {\n return;\n }\n\n var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);\n var batch = allRequests.slice(i, upTo);\n processBatch(batch, i);\n i += batch.length;\n }\n\n function processBatch(batch, offset) {\n batch.forEach(function (docId, j) {\n var docIdx = offset + j;\n var docRequests = requestsById.get(docId);\n\n // just use the first request as the \"template\"\n // TODO: The _bulk_get API allows for more subtle use cases than this,\n // but for now it is unlikely that there will be a mix of different\n // \"atts_since\" or \"attachments\" in the same request, since it's just\n // replicate.js that is using this for the moment.\n // Also, atts_since is aspirational, since we don't support it yet.\n var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);\n docOpts.open_revs = docRequests.map(function (request) {\n // rev is optional, open_revs disallowed\n return request.rev;\n });\n\n // remove falsey / undefined revisions\n docOpts.open_revs = docOpts.open_revs.filter(identityFunction);\n\n var formatResult = identityFunction;\n\n if (docOpts.open_revs.length === 0) {\n delete docOpts.open_revs;\n\n // when fetching only the \"winning\" leaf,\n // transform the result so it looks like an open_revs\n // request\n formatResult = formatResultForOpenRevsGet;\n }\n\n // globally-supplied options\n ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {\n if (param in opts) {\n docOpts[param] = opts[param];\n }\n });\n db.get(docId, docOpts, function (err, res) {\n var result;\n /* istanbul ignore if */\n if (err) {\n result = [{error: err}];\n } else {\n result = formatResult(res);\n }\n gotResult(docIdx, docId, result);\n nextBatch();\n });\n });\n }\n\n nextBatch();\n\n}\n\nvar hasLocal;\n\ntry {\n localStorage.setItem('_pouch_check_localstorage', 1);\n hasLocal = !!localStorage.getItem('_pouch_check_localstorage');\n} catch (e) {\n hasLocal = false;\n}\n\nfunction hasLocalStorage() {\n return hasLocal;\n}\n\n// Custom nextTick() shim for browsers. In node, this will just be process.nextTick(). We\n\ninherits(Changes, EventEmitter);\n\n/* istanbul ignore next */\nfunction attachBrowserEvents(self) {\n if (hasLocalStorage()) {\n addEventListener(\"storage\", function (e) {\n self.emit(e.key);\n });\n }\n}\n\nfunction Changes() {\n EventEmitter.call(this);\n this._listeners = {};\n\n attachBrowserEvents(this);\n}\nChanges.prototype.addListener = function (dbName, id, db, opts) {\n /* istanbul ignore if */\n if (this._listeners[id]) {\n return;\n }\n var self = this;\n var inprogress = false;\n function eventFunction() {\n /* istanbul ignore if */\n if (!self._listeners[id]) {\n return;\n }\n if (inprogress) {\n inprogress = 'waiting';\n return;\n }\n inprogress = true;\n var changesOpts = pick(opts, [\n 'style', 'include_docs', 'attachments', 'conflicts', 'filter',\n 'doc_ids', 'view', 'since', 'query_params', 'binary', 'return_docs'\n ]);\n\n /* istanbul ignore next */\n function onError() {\n inprogress = false;\n }\n\n db.changes(changesOpts).on('change', function (c) {\n if (c.seq > opts.since && !opts.cancelled) {\n opts.since = c.seq;\n opts.onChange(c);\n }\n }).on('complete', function () {\n if (inprogress === 'waiting') {\n nextTick(eventFunction);\n }\n inprogress = false;\n }).on('error', onError);\n }\n this._listeners[id] = eventFunction;\n this.on(dbName, eventFunction);\n};\n\nChanges.prototype.removeListener = function (dbName, id) {\n /* istanbul ignore if */\n if (!(id in this._listeners)) {\n return;\n }\n EventEmitter.prototype.removeListener.call(this, dbName,\n this._listeners[id]);\n delete this._listeners[id];\n};\n\n\n/* istanbul ignore next */\nChanges.prototype.notifyLocalWindows = function (dbName) {\n //do a useless change on a storage thing\n //in order to get other windows's listeners to activate\n if (hasLocalStorage()) {\n localStorage[dbName] = (localStorage[dbName] === \"a\") ? \"b\" : \"a\";\n }\n};\n\nChanges.prototype.notify = function (dbName) {\n this.emit(dbName);\n this.notifyLocalWindows(dbName);\n};\n\nfunction guardedConsole(method) {\n /* istanbul ignore else */\n if (typeof console !== 'undefined' && typeof console[method] === 'function') {\n var args = Array.prototype.slice.call(arguments, 1);\n console[method].apply(console, args);\n }\n}\n\nfunction randomNumber(min, max) {\n var maxTimeout = 600000; // Hard-coded default of 10 minutes\n min = parseInt(min, 10) || 0;\n max = parseInt(max, 10);\n if (max !== max || max <= min) {\n max = (min || 1) << 1; //doubling\n } else {\n max = max + 1;\n }\n // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout\n if (max > maxTimeout) {\n min = maxTimeout >> 1; // divide by two\n max = maxTimeout;\n }\n var ratio = Math.random();\n var range = max - min;\n\n return ~~(range * ratio + min); // ~~ coerces to an int, but fast.\n}\n\nfunction defaultBackOff(min) {\n var max = 0;\n if (!min) {\n max = 2000;\n }\n return randomNumber(min, max);\n}\n\n// designed to give info to browser users, who are disturbed\n// when they see http errors in the console\nfunction explainError(status, str) {\n guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);\n}\n\nvar assign;\n{\n if (typeof Object.assign === 'function') {\n assign = Object.assign;\n } else {\n // lite Object.assign polyfill based on\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\n assign = function (target) {\n var to = Object(target);\n\n for (var index = 1; index < arguments.length; index++) {\n var nextSource = arguments[index];\n\n if (nextSource != null) { // Skip over if undefined or null\n for (var nextKey in nextSource) {\n // Avoid bugs when hasOwnProperty is shadowed\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n }\n return to;\n };\n }\n}\n\nvar $inject_Object_assign = assign;\n\ninherits(PouchError, Error);\n\nfunction PouchError(status, error, reason) {\n Error.call(this, reason);\n this.status = status;\n this.name = error;\n this.message = reason;\n this.error = true;\n}\n\nPouchError.prototype.toString = function () {\n return JSON.stringify({\n status: this.status,\n name: this.name,\n message: this.message,\n reason: this.reason\n });\n};\n\nvar UNAUTHORIZED = new PouchError(401, 'unauthorized', \"Name or password is incorrect.\");\nvar MISSING_BULK_DOCS = new PouchError(400, 'bad_request', \"Missing JSON list of 'docs'\");\nvar MISSING_DOC = new PouchError(404, 'not_found', 'missing');\nvar REV_CONFLICT = new PouchError(409, 'conflict', 'Document update conflict');\nvar INVALID_ID = new PouchError(400, 'bad_request', '_id field must contain a string');\nvar MISSING_ID = new PouchError(412, 'missing_id', '_id is required for puts');\nvar RESERVED_ID = new PouchError(400, 'bad_request', 'Only reserved document ids may start with underscore.');\nvar NOT_OPEN = new PouchError(412, 'precondition_failed', 'Database not open');\nvar UNKNOWN_ERROR = new PouchError(500, 'unknown_error', 'Database encountered an unknown error');\nvar BAD_ARG = new PouchError(500, 'badarg', 'Some query argument is invalid');\nvar INVALID_REQUEST = new PouchError(400, 'invalid_request', 'Request was invalid');\nvar QUERY_PARSE_ERROR = new PouchError(400, 'query_parse_error', 'Some query parameter is invalid');\nvar DOC_VALIDATION = new PouchError(500, 'doc_validation', 'Bad special document member');\nvar BAD_REQUEST = new PouchError(400, 'bad_request', 'Something wrong with the request');\nvar NOT_AN_OBJECT = new PouchError(400, 'bad_request', 'Document must be a JSON object');\nvar DB_MISSING = new PouchError(404, 'not_found', 'Database not found');\nvar IDB_ERROR = new PouchError(500, 'indexed_db_went_bad', 'unknown');\nvar WSQ_ERROR = new PouchError(500, 'web_sql_went_bad', 'unknown');\nvar LDB_ERROR = new PouchError(500, 'levelDB_went_went_bad', 'unknown');\nvar FORBIDDEN = new PouchError(403, 'forbidden', 'Forbidden by design doc validate_doc_update function');\nvar INVALID_REV = new PouchError(400, 'bad_request', 'Invalid rev format');\nvar FILE_EXISTS = new PouchError(412, 'file_exists', 'The database could not be created, the file already exists.');\nvar MISSING_STUB = new PouchError(412, 'missing_stub', 'A pre-existing attachment stub wasn\\'t found');\nvar INVALID_URL = new PouchError(413, 'invalid_url', 'Provided URL is invalid');\n\nfunction createError(error, reason) {\n function CustomPouchError(reason) {\n // inherit error properties from our parent error manually\n // so as to allow proper JSON parsing.\n /* jshint ignore:start */\n for (var p in error) {\n if (typeof error[p] !== 'function') {\n this[p] = error[p];\n }\n }\n /* jshint ignore:end */\n if (reason !== undefined) {\n this.reason = reason;\n }\n }\n CustomPouchError.prototype = PouchError.prototype;\n return new CustomPouchError(reason);\n}\n\nfunction generateErrorFromResponse(err) {\n\n if (typeof err !== 'object') {\n var data = err;\n err = UNKNOWN_ERROR;\n err.data = data;\n }\n\n if ('error' in err && err.error === 'conflict') {\n err.name = 'conflict';\n err.status = 409;\n }\n\n if (!('name' in err)) {\n err.name = err.error || 'unknown';\n }\n\n if (!('status' in err)) {\n err.status = 500;\n }\n\n if (!('message' in err)) {\n err.message = err.message || err.reason;\n }\n\n return err;\n}\n\nfunction tryFilter(filter, doc, req) {\n try {\n return !filter(doc, req);\n } catch (err) {\n var msg = 'Filter function threw: ' + err.toString();\n return createError(BAD_REQUEST, msg);\n }\n}\n\nfunction filterChange(opts) {\n var req = {};\n var hasFilter = opts.filter && typeof opts.filter === 'function';\n req.query = opts.query_params;\n\n return function filter(change) {\n if (!change.doc) {\n // CSG sends events on the changes feed that don't have documents,\n // this hack makes a whole lot of existing code robust.\n change.doc = {};\n }\n\n var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);\n\n if (typeof filterReturn === 'object') {\n return filterReturn;\n }\n\n if (filterReturn) {\n return false;\n }\n\n if (!opts.include_docs) {\n delete change.doc;\n } else if (!opts.attachments) {\n for (var att in change.doc._attachments) {\n /* istanbul ignore else */\n if (change.doc._attachments.hasOwnProperty(att)) {\n change.doc._attachments[att].stub = true;\n }\n }\n }\n return true;\n };\n}\n\nfunction flatten(arrs) {\n var res = [];\n for (var i = 0, len = arrs.length; i < len; i++) {\n res = res.concat(arrs[i]);\n }\n return res;\n}\n\n// shim for Function.prototype.name,\n\n// Determine id an ID is valid\n// - invalid IDs begin with an underescore that does not begin '_design' or\n// '_local'\n// - any other string value is a valid id\n// Returns the specific error object for each case\nfunction invalidIdError(id) {\n var err;\n if (!id) {\n err = createError(MISSING_ID);\n } else if (typeof id !== 'string') {\n err = createError(INVALID_ID);\n } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {\n err = createError(RESERVED_ID);\n }\n if (err) {\n throw err;\n }\n}\n\n// Checks if a PouchDB object is \"remote\" or not. This is\n\nfunction isRemote(db) {\n if (typeof db._remote === 'boolean') {\n return db._remote;\n }\n /* istanbul ignore next */\n if (typeof db.type === 'function') {\n guardedConsole('warn',\n 'db.type() is deprecated and will be removed in ' +\n 'a future version of PouchDB');\n return db.type() === 'http';\n }\n /* istanbul ignore next */\n return false;\n}\n\nfunction listenerCount(ee, type) {\n return 'listenerCount' in ee ? ee.listenerCount(type) :\n EventEmitter.listenerCount(ee, type);\n}\n\nfunction parseDesignDocFunctionName(s) {\n if (!s) {\n return null;\n }\n var parts = s.split('/');\n if (parts.length === 2) {\n return parts;\n }\n if (parts.length === 1) {\n return [s, s];\n }\n return null;\n}\n\nfunction normalizeDesignDocFunctionName(s) {\n var normalized = parseDesignDocFunctionName(s);\n return normalized ? normalized.join('/') : null;\n}\n\n// originally parseUri 1.2.2, now patched by us\n// (c) Steven Levithan <stevenlevithan.com>\n// MIT License\nvar keys = [\"source\", \"protocol\", \"authority\", \"userInfo\", \"user\", \"password\",\n \"host\", \"port\", \"relative\", \"path\", \"directory\", \"file\", \"query\", \"anchor\"];\nvar qName =\"queryKey\";\nvar qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;\n\n// use the \"loose\" parser\n/* eslint maxlen: 0, no-useless-escape: 0 */\nvar parser = /^(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\n\nfunction parseUri(str) {\n var m = parser.exec(str);\n var uri = {};\n var i = 14;\n\n while (i--) {\n var key = keys[i];\n var value = m[i] || \"\";\n var encoded = ['user', 'password'].indexOf(key) !== -1;\n uri[key] = encoded ? decodeURIComponent(value) : value;\n }\n\n uri[qName] = {};\n uri[keys[12]].replace(qParser, function ($0, $1, $2) {\n if ($1) {\n uri[qName][$1] = $2;\n }\n });\n\n return uri;\n}\n\n// Based on https://github.com/alexdavid/scope-eval v0.0.3\n// (source: https://unpkg.com/scope-eval@0.0.3/scope_eval.js)\n// This is basically just a wrapper around new Function()\n\nfunction scopeEval(source, scope) {\n var keys = [];\n var values = [];\n for (var key in scope) {\n if (scope.hasOwnProperty(key)) {\n keys.push(key);\n values.push(scope[key]);\n }\n }\n keys.push(source);\n return Function.apply(null, keys).apply(null, values);\n}\n\n// this is essentially the \"update sugar\" function from daleharvey/pouchdb#1388\n// the diffFun tells us what delta to apply to the doc. it either returns\n// the doc, or false if it doesn't need to do an update after all\nfunction upsert(db, docId, diffFun) {\n return new Promise(function (fulfill, reject) {\n db.get(docId, function (err, doc) {\n if (err) {\n /* istanbul ignore next */\n if (err.status !== 404) {\n return reject(err);\n }\n doc = {};\n }\n\n // the user might change the _rev, so save it for posterity\n var docRev = doc._rev;\n var newDoc = diffFun(doc);\n\n if (!newDoc) {\n // if the diffFun returns falsy, we short-circuit as\n // an optimization\n return fulfill({updated: false, rev: docRev});\n }\n\n // users aren't allowed to modify these values,\n // so reset them here\n newDoc._id = docId;\n newDoc._rev = docRev;\n fulfill(tryAndPut(db, newDoc, diffFun));\n });\n });\n}\n\nfunction tryAndPut(db, doc, diffFun) {\n return db.put(doc).then(function (res) {\n return {\n updated: true,\n rev: res.rev\n };\n }, function (err) {\n /* istanbul ignore next */\n if (err.status !== 409) {\n throw err;\n }\n return upsert(db, doc._id, diffFun);\n });\n}\n\nvar thisAtob = function (str) {\n return atob(str);\n};\n\nvar thisBtoa = function (str) {\n return btoa(str);\n};\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor (e.g.\n// old QtWebKit versions, Android < 4.4).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== \"TypeError\") {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :\n typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :\n typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :\n WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction binaryStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\nfunction binStringToBluffer(binString, type) {\n return createBlob([binaryStringToArrayBuffer(binString)], {type: type});\n}\n\nfunction b64ToBluffer(b64, type) {\n return binStringToBluffer(thisAtob(b64), type);\n}\n\n//Can't find original post, but this is close\n//http://stackoverflow.com/questions/6965107/ (continues on next line)\n//converting-between-strings-and-arraybuffers\nfunction arrayBufferToBinaryString(buffer) {\n var binary = '';\n var bytes = new Uint8Array(buffer);\n var length = bytes.byteLength;\n for (var i = 0; i < length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return binary;\n}\n\n// shim for browsers that don't support it\nfunction readAsBinaryString(blob, callback) {\n var reader = new FileReader();\n var hasBinaryString = typeof reader.readAsBinaryString === 'function';\n reader.onloadend = function (e) {\n var result = e.target.result || '';\n if (hasBinaryString) {\n return callback(result);\n }\n callback(arrayBufferToBinaryString(result));\n };\n if (hasBinaryString) {\n reader.readAsBinaryString(blob);\n } else {\n reader.readAsArrayBuffer(blob);\n }\n}\n\nfunction blobToBinaryString(blobOrBuffer, callback) {\n readAsBinaryString(blobOrBuffer, function (bin) {\n callback(bin);\n });\n}\n\nfunction blobToBase64(blobOrBuffer, callback) {\n blobToBinaryString(blobOrBuffer, function (base64) {\n callback(thisBtoa(base64));\n });\n}\n\n// simplified API. universal browser support is assumed\nfunction readAsArrayBuffer(blob, callback) {\n var reader = new FileReader();\n reader.onloadend = function (e) {\n var result = e.target.result || new ArrayBuffer(0);\n callback(result);\n };\n reader.readAsArrayBuffer(blob);\n}\n\n// this is not used in the browser\n\nvar setImmediateShim = global.setImmediate || global.setTimeout;\nvar MD5_CHUNK_SIZE = 32768;\n\nfunction rawToBase64(raw) {\n return thisBtoa(raw);\n}\n\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n }\n return blob.slice(start, end);\n}\n\nfunction appendBlob(buffer, blob, start, end, callback) {\n if (start > 0 || end < blob.size) {\n // only slice blob if we really need to\n blob = sliceBlob(blob, start, end);\n }\n readAsArrayBuffer(blob, function (arrayBuffer) {\n buffer.append(arrayBuffer);\n callback();\n });\n}\n\nfunction appendString(buffer, string, start, end, callback) {\n if (start > 0 || end < string.length) {\n // only create a substring if we really need to\n string = string.substring(start, end);\n }\n buffer.appendBinary(string);\n callback();\n}\n\nfunction binaryMd5(data, callback) {\n var inputIsString = typeof data === 'string';\n var len = inputIsString ? data.length : data.size;\n var chunkSize = Math.min(MD5_CHUNK_SIZE, len);\n var chunks = Math.ceil(len / chunkSize);\n var currentChunk = 0;\n var buffer = inputIsString ? new Md5() : new Md5.ArrayBuffer();\n\n var append = inputIsString ? appendString : appendBlob;\n\n function next() {\n setImmediateShim(loadNextChunk);\n }\n\n function done() {\n var raw = buffer.end(true);\n var base64 = rawToBase64(raw);\n callback(base64);\n buffer.destroy();\n }\n\n function loadNextChunk() {\n var start = currentChunk * chunkSize;\n var end = start + chunkSize;\n currentChunk++;\n if (currentChunk < chunks) {\n append(buffer, data, start, end, next);\n } else {\n append(buffer, data, start, end, done);\n }\n }\n loadNextChunk();\n}\n\nfunction stringMd5(string) {\n return Md5.hash(string);\n}\n\nfunction rev$$1(doc, deterministic_revs) {\n var clonedDoc = clone(doc);\n if (!deterministic_revs) {\n return uuidV4.v4().replace(/-/g, '').toLowerCase();\n }\n\n delete clonedDoc._rev_tree;\n return stringMd5(JSON.stringify(clonedDoc));\n}\n\nvar uuid = uuidV4.v4;\n\n// We fetch all leafs of the revision tree, and sort them based on tree length\n// and whether they were deleted, undeleted documents with the longest revision\n// tree (most edits) win\n// The final sort algorithm is slightly documented in a sidebar here:\n// http://guide.couchdb.org/draft/conflicts.html\nfunction winningRev(metadata) {\n var winningId;\n var winningPos;\n var winningDeleted;\n var toVisit = metadata.rev_tree.slice();\n var node;\n while ((node = toVisit.pop())) {\n var tree = node.ids;\n var branches = tree[2];\n var pos = node.pos;\n if (branches.length) { // non-leaf\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: pos + 1, ids: branches[i]});\n }\n continue;\n }\n var deleted = !!tree[1].deleted;\n var id = tree[0];\n // sort by deleted, then pos, then id\n if (!winningId || (winningDeleted !== deleted ? winningDeleted :\n winningPos !== pos ? winningPos < pos : winningId < id)) {\n winningId = id;\n winningPos = pos;\n winningDeleted = deleted;\n }\n }\n\n return winningPos + '-' + winningId;\n}\n\n// Pretty much all below can be combined into a higher order function to\n// traverse revisions\n// The return value from the callback will be passed as context to all\n// children of that node\nfunction traverseRevTree(revs, callback) {\n var toVisit = revs.slice();\n\n var node;\n while ((node = toVisit.pop())) {\n var pos = node.pos;\n var tree = node.ids;\n var branches = tree[2];\n var newCtx =\n callback(branches.length === 0, pos, tree[0], node.ctx, tree[1]);\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: pos + 1, ids: branches[i], ctx: newCtx});\n }\n }\n}\n\nfunction sortByPos(a, b) {\n return a.pos - b.pos;\n}\n\nfunction collectLeaves(revs) {\n var leaves = [];\n traverseRevTree(revs, function (isLeaf, pos, id, acc, opts) {\n if (isLeaf) {\n leaves.push({rev: pos + \"-\" + id, pos: pos, opts: opts});\n }\n });\n leaves.sort(sortByPos).reverse();\n for (var i = 0, len = leaves.length; i < len; i++) {\n delete leaves[i].pos;\n }\n return leaves;\n}\n\n// returns revs of all conflicts that is leaves such that\n// 1. are not deleted and\n// 2. are different than winning revision\nfunction collectConflicts(metadata) {\n var win = winningRev(metadata);\n var leaves = collectLeaves(metadata.rev_tree);\n var conflicts = [];\n for (var i = 0, len = leaves.length; i < len; i++) {\n var leaf = leaves[i];\n if (leaf.rev !== win && !leaf.opts.deleted) {\n conflicts.push(leaf.rev);\n }\n }\n return conflicts;\n}\n\n// compact a tree by marking its non-leafs as missing,\n// and return a list of revs to delete\nfunction compactTree(metadata) {\n var revs = [];\n traverseRevTree(metadata.rev_tree, function (isLeaf, pos,\n revHash, ctx, opts) {\n if (opts.status === 'available' && !isLeaf) {\n revs.push(pos + '-' + revHash);\n opts.status = 'missing';\n }\n });\n return revs;\n}\n\n// build up a list of all the paths to the leafs in this revision tree\nfunction rootToLeaf(revs) {\n var paths = [];\n var toVisit = revs.slice();\n var node;\n while ((node = toVisit.pop())) {\n var pos = node.pos;\n var tree = node.ids;\n var id = tree[0];\n var opts = tree[1];\n var branches = tree[2];\n var isLeaf = branches.length === 0;\n\n var history = node.history ? node.history.slice() : [];\n history.push({id: id, opts: opts});\n if (isLeaf) {\n paths.push({pos: (pos + 1 - history.length), ids: history});\n }\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: pos + 1, ids: branches[i], history: history});\n }\n }\n return paths.reverse();\n}\n\n// for a better overview of what this is doing, read:\n\nfunction sortByPos$1(a, b) {\n return a.pos - b.pos;\n}\n\n// classic binary search\nfunction binarySearch(arr, item, comparator) {\n var low = 0;\n var high = arr.length;\n var mid;\n while (low < high) {\n mid = (low + high) >>> 1;\n if (comparator(arr[mid], item) < 0) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n}\n\n// assuming the arr is sorted, insert the item in the proper place\nfunction insertSorted(arr, item, comparator) {\n var idx = binarySearch(arr, item, comparator);\n arr.splice(idx, 0, item);\n}\n\n// Turn a path as a flat array into a tree with a single branch.\n// If any should be stemmed from the beginning of the array, that's passed\n// in as the second argument\nfunction pathToTree(path, numStemmed) {\n var root;\n var leaf;\n for (var i = numStemmed, len = path.length; i < len; i++) {\n var node = path[i];\n var currentLeaf = [node.id, node.opts, []];\n if (leaf) {\n leaf[2].push(currentLeaf);\n leaf = currentLeaf;\n } else {\n root = leaf = currentLeaf;\n }\n }\n return root;\n}\n\n// compare the IDs of two trees\nfunction compareTree(a, b) {\n return a[0] < b[0] ? -1 : 1;\n}\n\n// Merge two trees together\n// The roots of tree1 and tree2 must be the same revision\nfunction mergeTree(in_tree1, in_tree2) {\n var queue = [{tree1: in_tree1, tree2: in_tree2}];\n var conflicts = false;\n while (queue.length > 0) {\n var item = queue.pop();\n var tree1 = item.tree1;\n var tree2 = item.tree2;\n\n if (tree1[1].status || tree2[1].status) {\n tree1[1].status =\n (tree1[1].status === 'available' ||\n tree2[1].status === 'available') ? 'available' : 'missing';\n }\n\n for (var i = 0; i < tree2[2].length; i++) {\n if (!tree1[2][0]) {\n conflicts = 'new_leaf';\n tree1[2][0] = tree2[2][i];\n continue;\n }\n\n var merged = false;\n for (var j = 0; j < tree1[2].length; j++) {\n if (tree1[2][j][0] === tree2[2][i][0]) {\n queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});\n merged = true;\n }\n }\n if (!merged) {\n conflicts = 'new_branch';\n insertSorted(tree1[2], tree2[2][i], compareTree);\n }\n }\n }\n return {conflicts: conflicts, tree: in_tree1};\n}\n\nfunction doMerge(tree, path, dontExpand) {\n var restree = [];\n var conflicts = false;\n var merged = false;\n var res;\n\n if (!tree.length) {\n return {tree: [path], conflicts: 'new_leaf'};\n }\n\n for (var i = 0, len = tree.length; i < len; i++) {\n var branch = tree[i];\n if (branch.pos === path.pos && branch.ids[0] === path.ids[0]) {\n // Paths start at the same position and have the same root, so they need\n // merged\n res = mergeTree(branch.ids, path.ids);\n restree.push({pos: branch.pos, ids: res.tree});\n conflicts = conflicts || res.conflicts;\n merged = true;\n } else if (dontExpand !== true) {\n // The paths start at a different position, take the earliest path and\n // traverse up until it as at the same point from root as the path we\n // want to merge. If the keys match we return the longer path with the\n // other merged After stemming we dont want to expand the trees\n\n var t1 = branch.pos < path.pos ? branch : path;\n var t2 = branch.pos < path.pos ? path : branch;\n var diff = t2.pos - t1.pos;\n\n var candidateParents = [];\n\n var trees = [];\n trees.push({ids: t1.ids, diff: diff, parent: null, parentIdx: null});\n while (trees.length > 0) {\n var item = trees.pop();\n if (item.diff === 0) {\n if (item.ids[0] === t2.ids[0]) {\n candidateParents.push(item);\n }\n continue;\n }\n var elements = item.ids[2];\n for (var j = 0, elementsLen = elements.length; j < elementsLen; j++) {\n trees.push({\n ids: elements[j],\n diff: item.diff - 1,\n parent: item.ids,\n parentIdx: j\n });\n }\n }\n\n var el = candidateParents[0];\n\n if (!el) {\n restree.push(branch);\n } else {\n res = mergeTree(el.ids, t2.ids);\n el.parent[2][el.parentIdx] = res.tree;\n restree.push({pos: t1.pos, ids: t1.ids});\n conflicts = conflicts || res.conflicts;\n merged = true;\n }\n } else {\n restree.push(branch);\n }\n }\n\n // We didnt find\n if (!merged) {\n restree.push(path);\n }\n\n restree.sort(sortByPos$1);\n\n return {\n tree: restree,\n conflicts: conflicts || 'internal_node'\n };\n}\n\n// To ensure we dont grow the revision tree infinitely, we stem old revisions\nfunction stem(tree, depth) {\n // First we break out the tree into a complete list of root to leaf paths\n var paths = rootToLeaf(tree);\n var stemmedRevs;\n\n var result;\n for (var i = 0, len = paths.length; i < len; i++) {\n // Then for each path, we cut off the start of the path based on the\n // `depth` to stem to, and generate a new set of flat trees\n var path = paths[i];\n var stemmed = path.ids;\n var node;\n if (stemmed.length > depth) {\n // only do the stemming work if we actually need to stem\n if (!stemmedRevs) {\n stemmedRevs = {}; // avoid allocating this object unnecessarily\n }\n var numStemmed = stemmed.length - depth;\n node = {\n pos: path.pos + numStemmed,\n ids: pathToTree(stemmed, numStemmed)\n };\n\n for (var s = 0; s < numStemmed; s++) {\n var rev = (path.pos + s) + '-' + stemmed[s].id;\n stemmedRevs[rev] = true;\n }\n } else { // no need to actually stem\n node = {\n pos: path.pos,\n ids: pathToTree(stemmed, 0)\n };\n }\n\n // Then we remerge all those flat trees together, ensuring that we dont\n // connect trees that would go beyond the depth limit\n if (result) {\n result = doMerge(result, node, true).tree;\n } else {\n result = [node];\n }\n }\n\n // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed\n if (stemmedRevs) {\n traverseRevTree(result, function (isLeaf, pos, revHash) {\n // some revisions may have been removed in a branch but not in another\n delete stemmedRevs[pos + '-' + revHash];\n });\n }\n\n return {\n tree: result,\n revs: stemmedRevs ? Object.keys(stemmedRevs) : []\n };\n}\n\nfunction merge(tree, path, depth) {\n var newTree = doMerge(tree, path);\n var stemmed = stem(newTree.tree, depth);\n return {\n tree: stemmed.tree,\n stemmedRevs: stemmed.revs,\n conflicts: newTree.conflicts\n };\n}\n\n// return true if a rev exists in the rev tree, false otherwise\nfunction revExists(revs, rev) {\n var toVisit = revs.slice();\n var splitRev = rev.split('-');\n var targetPos = parseInt(splitRev[0], 10);\n var targetId = splitRev[1];\n\n var node;\n while ((node = toVisit.pop())) {\n if (node.pos === targetPos && node.ids[0] === targetId) {\n return true;\n }\n var branches = node.ids[2];\n for (var i = 0, len = branches.length; i < len; i++) {\n toVisit.push({pos: node.pos + 1, ids: branches[i]});\n }\n }\n return false;\n}\n\nfunction getTrees(node) {\n return node.ids;\n}\n\n// check if a specific revision of a doc has been deleted\n// - metadata: the metadata object from the doc store\n// - rev: (optional) the revision to check. defaults to winning revision\nfunction isDeleted(metadata, rev) {\n if (!rev) {\n rev = winningRev(metadata);\n }\n var id = rev.substring(rev.indexOf('-') + 1);\n var toVisit = metadata.rev_tree.map(getTrees);\n\n var tree;\n while ((tree = toVisit.pop())) {\n if (tree[0] === id) {\n return !!tree[1].deleted;\n }\n toVisit = toVisit.concat(tree[2]);\n }\n}\n\nfunction isLocalId(id) {\n return (/^_local/).test(id);\n}\n\n// returns the current leaf node for a given revision\nfunction latest(rev, metadata) {\n var toVisit = metadata.rev_tree.slice();\n var node;\n while ((node = toVisit.pop())) {\n var pos = node.pos;\n var tree = node.ids;\n var id = tree[0];\n var opts = tree[1];\n var branches = tree[2];\n var isLeaf = branches.length === 0;\n\n var history = node.history ? node.history.slice() : [];\n history.push({id: id, pos: pos, opts: opts});\n\n if (isLeaf) {\n for (var i = 0, len = history.length; i < len; i++) {\n var historyNode = history[i];\n var historyRev = historyNode.pos + '-' + historyNode.id;\n\n if (historyRev === rev) {\n // return the rev of this leaf\n return pos + '-' + id;\n }\n }\n }\n\n for (var j = 0, l = branches.length; j < l; j++) {\n toVisit.push({pos: pos + 1, ids: branches[j], history: history});\n }\n }\n\n /* istanbul ignore next */\n throw new Error('Unable to resolve latest revision for id ' + metadata.id + ', rev ' + rev);\n}\n\ninherits(Changes$1, EventEmitter);\n\nfunction tryCatchInChangeListener(self, change, pending, lastSeq) {\n // isolate try/catches to avoid V8 deoptimizations\n try {\n self.emit('change', change, pending, lastSeq);\n } catch (e) {\n guardedConsole('error', 'Error in .on(\"change\", function):', e);\n }\n}\n\nfunction Changes$1(db, opts, callback) {\n EventEmitter.call(this);\n var self = this;\n this.db = db;\n opts = opts ? clone(opts) : {};\n var complete = opts.complete = once(function (err, resp) {\n if (err) {\n if (listenerCount(self, 'error') > 0) {\n self.emit('error', err);\n }\n } else {\n self.emit('complete', resp);\n }\n self.removeAllListeners();\n db.removeListener('destroyed', onDestroy);\n });\n if (callback) {\n self.on('complete', function (resp) {\n callback(null, resp);\n });\n self.on('error', callback);\n }\n function onDestroy() {\n self.cancel();\n }\n db.once('destroyed', onDestroy);\n\n opts.onChange = function (change, pending, lastSeq) {\n /* istanbul ignore if */\n if (self.isCancelled) {\n return;\n }\n tryCatchInChangeListener(self, change, pending, lastSeq);\n };\n\n var promise = new Promise(function (fulfill, reject) {\n opts.complete = function (err, res) {\n if (err) {\n reject(err);\n } else {\n fulfill(res);\n }\n };\n });\n self.once('cancel', function () {\n db.removeListener('destroyed', onDestroy);\n opts.complete(null, {status: 'cancelled'});\n });\n this.then = promise.then.bind(promise);\n this['catch'] = promise['catch'].bind(promise);\n this.then(function (result) {\n complete(null, result);\n }, complete);\n\n\n\n if (!db.taskqueue.isReady) {\n db.taskqueue.addTask(function (failed) {\n if (failed) {\n opts.complete(failed);\n } else if (self.isCancelled) {\n self.emit('cancel');\n } else {\n self.validateChanges(opts);\n }\n });\n } else {\n self.validateChanges(opts);\n }\n}\nChanges$1.prototype.cancel = function () {\n this.isCancelled = true;\n if (this.db.taskqueue.isReady) {\n this.emit('cancel');\n }\n};\nfunction processChange(doc, metadata, opts) {\n var changeList = [{rev: doc._rev}];\n if (opts.style === 'all_docs') {\n changeList = collectLeaves(metadata.rev_tree)\n .map(function (x) { return {rev: x.rev}; });\n }\n var change = {\n id: metadata.id,\n changes: changeList,\n doc: doc\n };\n\n if (isDeleted(metadata, doc._rev)) {\n change.deleted = true;\n }\n if (opts.conflicts) {\n change.doc._conflicts = collectConflicts(metadata);\n if (!change.doc._conflicts.length) {\n delete change.doc._conflicts;\n }\n }\n return change;\n}\n\nChanges$1.prototype.validateChanges = function (opts) {\n var callback = opts.complete;\n var self = this;\n\n /* istanbul ignore else */\n if (PouchDB._changesFilterPlugin) {\n PouchDB._changesFilterPlugin.validate(opts, function (err) {\n if (err) {\n return callback(err);\n }\n self.doChanges(opts);\n });\n } else {\n self.doChanges(opts);\n }\n};\n\nChanges$1.prototype.doChanges = function (opts) {\n var self = this;\n var callback = opts.complete;\n\n opts = clone(opts);\n if ('live' in opts && !('continuous' in opts)) {\n opts.continuous = opts.live;\n }\n opts.processChange = processChange;\n\n if (opts.since === 'latest') {\n opts.since = 'now';\n }\n if (!opts.since) {\n opts.since = 0;\n }\n if (opts.since === 'now') {\n this.db.info().then(function (info) {\n /* istanbul ignore if */\n if (self.isCancelled) {\n callback(null, {status: 'cancelled'});\n return;\n }\n opts.since = info.update_seq;\n self.doChanges(opts);\n }, callback);\n return;\n }\n\n /* istanbul ignore else */\n if (PouchDB._changesFilterPlugin) {\n PouchDB._changesFilterPlugin.normalize(opts);\n if (PouchDB._changesFilterPlugin.shouldFilter(this, opts)) {\n return PouchDB._changesFilterPlugin.filter(this, opts);\n }\n } else {\n ['doc_ids', 'filter', 'selector', 'view'].forEach(function (key) {\n if (key in opts) {\n guardedConsole('warn',\n 'The \"' + key + '\" option was passed in to changes/replicate, ' +\n 'but pouchdb-changes-filter plugin is not installed, so it ' +\n 'was ignored. Please install the plugin to enable filtering.'\n );\n }\n });\n }\n\n if (!('descending' in opts)) {\n opts.descending = false;\n }\n\n // 0 and 1 should return 1 document\n opts.limit = opts.limit === 0 ? 1 : opts.limit;\n opts.complete = callback;\n var newPromise = this.db._changes(opts);\n /* istanbul ignore else */\n if (newPromise && typeof newPromise.cancel === 'function') {\n var cancel = self.cancel;\n self.cancel = getArguments(function (args) {\n newPromise.cancel();\n cancel.apply(this, args);\n });\n }\n};\n\n/*\n * A generic pouch adapter\n */\n\nfunction compare(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n// Wrapper for functions that call the bulkdocs api with a single doc,\n// if the first result is an error, return an error\nfunction yankError(callback, docId) {\n return function (err, results) {\n if (err || (results[0] && results[0].error)) {\n err = err || results[0];\n err.docId = docId;\n callback(err);\n } else {\n callback(null, results.length ? results[0] : results);\n }\n };\n}\n\n// clean docs given to us by the user\nfunction cleanDocs(docs) {\n for (var i = 0; i < docs.length; i++) {\n var doc = docs[i];\n if (doc._deleted) {\n delete doc._attachments; // ignore atts for deleted docs\n } else if (doc._attachments) {\n // filter out extraneous keys from _attachments\n var atts = Object.keys(doc._attachments);\n for (var j = 0; j < atts.length; j++) {\n var att = atts[j];\n doc._attachments[att] = pick(doc._attachments[att],\n ['data', 'digest', 'content_type', 'length', 'revpos', 'stub']);\n }\n }\n }\n}\n\n// compare two docs, first by _id then by _rev\nfunction compareByIdThenRev(a, b) {\n var idCompare = compare(a._id, b._id);\n if (idCompare !== 0) {\n return idCompare;\n }\n var aStart = a._revisions ? a._revisions.start : 0;\n var bStart = b._revisions ? b._revisions.start : 0;\n return compare(aStart, bStart);\n}\n\n// for every node in a revision tree computes its distance from the closest\n// leaf\nfunction computeHeight(revs) {\n var height = {};\n var edges = [];\n traverseRevTree(revs, function (isLeaf, pos, id, prnt) {\n var rev = pos + \"-\" + id;\n if (isLeaf) {\n height[rev] = 0;\n }\n if (prnt !== undefined) {\n edges.push({from: prnt, to: rev});\n }\n return rev;\n });\n\n edges.reverse();\n edges.forEach(function (edge) {\n if (height[edge.from] === undefined) {\n height[edge.from] = 1 + height[edge.to];\n } else {\n height[edge.from] = Math.min(height[edge.from], 1 + height[edge.to]);\n }\n });\n return height;\n}\n\nfunction allDocsKeysParse(opts) {\n var keys = ('limit' in opts) ?\n opts.keys.slice(opts.skip, opts.limit + opts.skip) :\n (opts.skip > 0) ? opts.keys.slice(opts.skip) : opts.keys;\n opts.keys = keys;\n opts.skip = 0;\n delete opts.limit;\n if (opts.descending) {\n keys.reverse();\n opts.descending = false;\n }\n}\n\n// all compaction is done in a queue, to avoid attaching\n// too many listeners at once\nfunction doNextCompaction(self) {\n var task = self._compactionQueue[0];\n var opts = task.opts;\n var callback = task.callback;\n self.get('_local/compaction').catch(function () {\n return false;\n }).then(function (doc) {\n if (doc && doc.last_seq) {\n opts.last_seq = doc.last_seq;\n }\n self._compact(opts, function (err, res) {\n /* istanbul ignore if */\n if (err) {\n callback(err);\n } else {\n callback(null, res);\n }\n nextTick(function () {\n self._compactionQueue.shift();\n if (self._compactionQueue.length) {\n doNextCompaction(self);\n }\n });\n });\n });\n}\n\nfunction attachmentNameError(name) {\n if (name.charAt(0) === '_') {\n return name + ' is not a valid attachment name, attachment ' +\n 'names cannot start with \\'_\\'';\n }\n return false;\n}\n\ninherits(AbstractPouchDB, EventEmitter);\n\nfunction AbstractPouchDB() {\n EventEmitter.call(this);\n\n // re-bind prototyped methods\n for (var p in AbstractPouchDB.prototype) {\n if (typeof this[p] === 'function') {\n this[p] = this[p].bind(this);\n }\n }\n}\n\nAbstractPouchDB.prototype.post =\n adapterFun('post', function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n return callback(createError(NOT_AN_OBJECT));\n }\n this.bulkDocs({docs: [doc]}, opts, yankError(callback, doc._id));\n});\n\nAbstractPouchDB.prototype.put = adapterFun('put', function (doc, opts, cb) {\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof doc !== 'object' || Array.isArray(doc)) {\n return cb(createError(NOT_AN_OBJECT));\n }\n invalidIdError(doc._id);\n if (isLocalId(doc._id) && typeof this._putLocal === 'function') {\n if (doc._deleted) {\n return this._removeLocal(doc, cb);\n } else {\n return this._putLocal(doc, cb);\n }\n }\n var self = this;\n if (opts.force && doc._rev) {\n transformForceOptionToNewEditsOption();\n putDoc(function (err) {\n var result = err ? null : {ok: true, id: doc._id, rev: doc._rev};\n cb(err, result);\n });\n } else {\n putDoc(cb);\n }\n\n function transformForceOptionToNewEditsOption() {\n var parts = doc._rev.split('-');\n var oldRevId = parts[1];\n var oldRevNum = parseInt(parts[0], 10);\n\n var newRevNum = oldRevNum + 1;\n var newRevId = rev$$1();\n\n doc._revisions = {\n start: newRevNum,\n ids: [newRevId, oldRevId]\n };\n doc._rev = newRevNum + '-' + newRevId;\n opts.new_edits = false;\n }\n function putDoc(next) {\n if (typeof self._put === 'function' && opts.new_edits !== false) {\n self._put(doc, opts, next);\n } else {\n self.bulkDocs({docs: [doc]}, opts, yankError(next, doc._id));\n }\n }\n});\n\nAbstractPouchDB.prototype.putAttachment =\n adapterFun('putAttachment', function (docId, attachmentId, rev,\n blob, type) {\n var api = this;\n if (typeof type === 'function') {\n type = blob;\n blob = rev;\n rev = null;\n }\n // Lets fix in https://github.com/pouchdb/pouchdb/issues/3267\n /* istanbul ignore if */\n if (typeof type === 'undefined') {\n type = blob;\n blob = rev;\n rev = null;\n }\n if (!type) {\n guardedConsole('warn', 'Attachment', attachmentId, 'on document', docId, 'is missing content_type');\n }\n\n function createAttachment(doc) {\n var prevrevpos = '_rev' in doc ? parseInt(doc._rev, 10) : 0;\n doc._attachments = doc._attachments || {};\n doc._attachments[attachmentId] = {\n content_type: type,\n data: blob,\n revpos: ++prevrevpos\n };\n return api.put(doc);\n }\n\n return api.get(docId).then(function (doc) {\n if (doc._rev !== rev) {\n throw createError(REV_CONFLICT);\n }\n\n return createAttachment(doc);\n }, function (err) {\n // create new doc\n /* istanbul ignore else */\n if (err.reason === MISSING_DOC.message) {\n return createAttachment({_id: docId});\n } else {\n throw err;\n }\n });\n});\n\nAbstractPouchDB.prototype.removeAttachment =\n adapterFun('removeAttachment', function (docId, attachmentId, rev,\n callback) {\n var self = this;\n self.get(docId, function (err, obj) {\n /* istanbul ignore if */\n if (err) {\n callback(err);\n return;\n }\n if (obj._rev !== rev) {\n callback(createError(REV_CONFLICT));\n return;\n }\n /* istanbul ignore if */\n if (!obj._attachments) {\n return callback();\n }\n delete obj._attachments[attachmentId];\n if (Object.keys(obj._attachments).length === 0) {\n delete obj._attachments;\n }\n self.put(obj, callback);\n });\n});\n\nAbstractPouchDB.prototype.remove =\n adapterFun('remove', function (docOrId, optsOrRev, opts, callback) {\n var doc;\n if (typeof optsOrRev === 'string') {\n // id, rev, opts, callback style\n doc = {\n _id: docOrId,\n _rev: optsOrRev\n };\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n } else {\n // doc, opts, callback style\n doc = docOrId;\n if (typeof optsOrRev === 'function') {\n callback = optsOrRev;\n opts = {};\n } else {\n callback = opts;\n opts = optsOrRev;\n }\n }\n opts = opts || {};\n opts.was_delete = true;\n var newDoc = {_id: doc._id, _rev: (doc._rev || opts.rev)};\n newDoc._deleted = true;\n if (isLocalId(newDoc._id) && typeof this._removeLocal === 'function') {\n return this._removeLocal(doc, callback);\n }\n this.bulkDocs({docs: [newDoc]}, opts, yankError(callback, newDoc._id));\n});\n\nAbstractPouchDB.prototype.revsDiff =\n adapterFun('revsDiff', function (req, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var ids = Object.keys(req);\n\n if (!ids.length) {\n return callback(null, {});\n }\n\n var count = 0;\n var missing = new ExportedMap();\n\n function addToMissing(id, revId) {\n if (!missing.has(id)) {\n missing.set(id, {missing: []});\n }\n missing.get(id).missing.push(revId);\n }\n\n function processDoc(id, rev_tree) {\n // Is this fast enough? Maybe we should switch to a set simulated by a map\n var missingForId = req[id].slice(0);\n traverseRevTree(rev_tree, function (isLeaf, pos, revHash, ctx,\n opts) {\n var rev = pos + '-' + revHash;\n var idx = missingForId.indexOf(rev);\n if (idx === -1) {\n return;\n }\n\n missingForId.splice(idx, 1);\n /* istanbul ignore if */\n if (opts.status !== 'available') {\n addToMissing(id, rev);\n }\n });\n\n // Traversing the tree is synchronous, so now `missingForId` contains\n // revisions that were not found in the tree\n missingForId.forEach(function (rev) {\n addToMissing(id, rev);\n });\n }\n\n ids.map(function (id) {\n this._getRevisionTree(id, function (err, rev_tree) {\n if (err && err.status === 404 && err.message === 'missing') {\n missing.set(id, {missing: req[id]});\n } else if (err) {\n /* istanbul ignore next */\n return callback(err);\n } else {\n processDoc(id, rev_tree);\n }\n\n if (++count === ids.length) {\n // convert LazyMap to object\n var missingObj = {};\n missing.forEach(function (value, key) {\n missingObj[key] = value;\n });\n return callback(null, missingObj);\n }\n });\n }, this);\n});\n\n// _bulk_get API for faster replication, as described in\n// https://github.com/apache/couchdb-chttpd/pull/33\n// At the \"abstract\" level, it will just run multiple get()s in\n// parallel, because this isn't much of a performance cost\n// for local databases (except the cost of multiple transactions, which is\n// small). The http adapter overrides this in order\n// to do a more efficient single HTTP request.\nAbstractPouchDB.prototype.bulkGet =\n adapterFun('bulkGet', function (opts, callback) {\n bulkGet(this, opts, callback);\n});\n\n// compact one document and fire callback\n// by compacting we mean removing all revisions which\n// are further from the leaf in revision tree than max_height\nAbstractPouchDB.prototype.compactDocument =\n adapterFun('compactDocument', function (docId, maxHeight, callback) {\n var self = this;\n this._getRevisionTree(docId, function (err, revTree) {\n /* istanbul ignore if */\n if (err) {\n return callback(err);\n }\n var height = computeHeight(revTree);\n var candidates = [];\n var revs = [];\n Object.keys(height).forEach(function (rev) {\n if (height[rev] > maxHeight) {\n candidates.push(rev);\n }\n });\n\n traverseRevTree(revTree, function (isLeaf, pos, revHash, ctx, opts) {\n var rev = pos + '-' + revHash;\n if (opts.status === 'available' && candidates.indexOf(rev) !== -1) {\n revs.push(rev);\n }\n });\n self._doCompaction(docId, revs, callback);\n });\n});\n\n// compact the whole database using single document\n// compaction\nAbstractPouchDB.prototype.compact =\n adapterFun('compact', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n var self = this;\n opts = opts || {};\n\n self._compactionQueue = self._compactionQueue || [];\n self._compactionQueue.push({opts: opts, callback: callback});\n if (self._compactionQueue.length === 1) {\n doNextCompaction(self);\n }\n});\nAbstractPouchDB.prototype._compact = function (opts, callback) {\n var self = this;\n var changesOpts = {\n return_docs: false,\n last_seq: opts.last_seq || 0\n };\n var promises = [];\n\n function onChange(row) {\n promises.push(self.compactDocument(row.id, 0));\n }\n function onComplete(resp) {\n var lastSeq = resp.last_seq;\n Promise.all(promises).then(function () {\n return upsert(self, '_local/compaction', function deltaFunc(doc) {\n if (!doc.last_seq || doc.last_seq < lastSeq) {\n doc.last_seq = lastSeq;\n return doc;\n }\n return false; // somebody else got here first, don't update\n });\n }).then(function () {\n callback(null, {ok: true});\n }).catch(callback);\n }\n self.changes(changesOpts)\n .on('change', onChange)\n .on('complete', onComplete)\n .on('error', callback);\n};\n\n/* Begin api wrappers. Specific functionality to storage belongs in the\n _[method] */\nAbstractPouchDB.prototype.get = adapterFun('get', function (id, opts, cb) {\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof id !== 'string') {\n return cb(createError(INVALID_ID));\n }\n if (isLocalId(id) && typeof this._getLocal === 'function') {\n return this._getLocal(id, cb);\n }\n var leaves = [], self = this;\n\n function finishOpenRevs() {\n var result = [];\n var count = leaves.length;\n /* istanbul ignore if */\n if (!count) {\n return cb(null, result);\n }\n\n // order with open_revs is unspecified\n leaves.forEach(function (leaf) {\n self.get(id, {\n rev: leaf,\n revs: opts.revs,\n latest: opts.latest,\n attachments: opts.attachments,\n binary: opts.binary\n }, function (err, doc) {\n if (!err) {\n // using latest=true can produce duplicates\n var existing;\n for (var i = 0, l = result.length; i < l; i++) {\n if (result[i].ok && result[i].ok._rev === doc._rev) {\n existing = true;\n break;\n }\n }\n if (!existing) {\n result.push({ok: doc});\n }\n } else {\n result.push({missing: leaf});\n }\n count--;\n if (!count) {\n cb(null, result);\n }\n });\n });\n }\n\n if (opts.open_revs) {\n if (opts.open_revs === \"all\") {\n this._getRevisionTree(id, function (err, rev_tree) {\n /* istanbul ignore if */\n if (err) {\n return cb(err);\n }\n leaves = collectLeaves(rev_tree).map(function (leaf) {\n return leaf.rev;\n });\n finishOpenRevs();\n });\n } else {\n if (Array.isArray(opts.open_revs)) {\n leaves = opts.open_revs;\n for (var i = 0; i < leaves.length; i++) {\n var l = leaves[i];\n // looks like it's the only thing couchdb checks\n if (!(typeof (l) === \"string\" && /^\\d+-/.test(l))) {\n return cb(createError(INVALID_REV));\n }\n }\n finishOpenRevs();\n } else {\n return cb(createError(UNKNOWN_ERROR, 'function_clause'));\n }\n }\n return; // open_revs does not like other options\n }\n\n return this._get(id, opts, function (err, result) {\n if (err) {\n err.docId = id;\n return cb(err);\n }\n\n var doc = result.doc;\n var metadata = result.metadata;\n var ctx = result.ctx;\n\n if (opts.conflicts) {\n var conflicts = collectConflicts(metadata);\n if (conflicts.length) {\n doc._conflicts = conflicts;\n }\n }\n\n if (isDeleted(metadata, doc._rev)) {\n doc._deleted = true;\n }\n\n if (opts.revs || opts.revs_info) {\n var splittedRev = doc._rev.split('-');\n var revNo = parseInt(splittedRev[0], 10);\n var revHash = splittedRev[1];\n\n var paths = rootToLeaf(metadata.rev_tree);\n var path = null;\n\n for (var i = 0; i < paths.length; i++) {\n var currentPath = paths[i];\n var hashIndex = currentPath.ids.map(function (x) { return x.id; })\n .indexOf(revHash);\n var hashFoundAtRevPos = hashIndex === (revNo - 1);\n\n if (hashFoundAtRevPos || (!path && hashIndex !== -1)) {\n path = currentPath;\n }\n }\n\n var indexOfRev = path.ids.map(function (x) { return x.id; })\n .indexOf(doc._rev.split('-')[1]) + 1;\n var howMany = path.ids.length - indexOfRev;\n path.ids.splice(indexOfRev, howMany);\n path.ids.reverse();\n\n if (opts.revs) {\n doc._revisions = {\n start: (path.pos + path.ids.length) - 1,\n ids: path.ids.map(function (rev) {\n return rev.id;\n })\n };\n }\n if (opts.revs_info) {\n var pos = path.pos + path.ids.length;\n doc._revs_info = path.ids.map(function (rev) {\n pos--;\n return {\n rev: pos + '-' + rev.id,\n status: rev.opts.status\n };\n });\n }\n }\n\n if (opts.attachments && doc._attachments) {\n var attachments = doc._attachments;\n var count = Object.keys(attachments).length;\n if (count === 0) {\n return cb(null, doc);\n }\n Object.keys(attachments).forEach(function (key) {\n this._getAttachment(doc._id, key, attachments[key], {\n // Previously the revision handling was done in adapter.js\n // getAttachment, however since idb-next doesnt we need to\n // pass the rev through\n rev: doc._rev,\n binary: opts.binary,\n ctx: ctx\n }, function (err, data) {\n var att = doc._attachments[key];\n att.data = data;\n delete att.stub;\n delete att.length;\n if (!--count) {\n cb(null, doc);\n }\n });\n }, self);\n } else {\n if (doc._attachments) {\n for (var key in doc._attachments) {\n /* istanbul ignore else */\n if (doc._attachments.hasOwnProperty(key)) {\n doc._attachments[key].stub = true;\n }\n }\n }\n cb(null, doc);\n }\n });\n});\n\n// TODO: I dont like this, it forces an extra read for every\n// attachment read and enforces a confusing api between\n// adapter.js and the adapter implementation\nAbstractPouchDB.prototype.getAttachment =\n adapterFun('getAttachment', function (docId, attachmentId, opts, callback) {\n var self = this;\n if (opts instanceof Function) {\n callback = opts;\n opts = {};\n }\n this._get(docId, opts, function (err, res) {\n if (err) {\n return callback(err);\n }\n if (res.doc._attachments && res.doc._attachments[attachmentId]) {\n opts.ctx = res.ctx;\n opts.binary = true;\n self._getAttachment(docId, attachmentId,\n res.doc._attachments[attachmentId], opts, callback);\n } else {\n return callback(createError(MISSING_DOC));\n }\n });\n});\n\nAbstractPouchDB.prototype.allDocs =\n adapterFun('allDocs', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts.skip = typeof opts.skip !== 'undefined' ? opts.skip : 0;\n if (opts.start_key) {\n opts.startkey = opts.start_key;\n }\n if (opts.end_key) {\n opts.endkey = opts.end_key;\n }\n if ('keys' in opts) {\n if (!Array.isArray(opts.keys)) {\n return callback(new TypeError('options.keys must be an array'));\n }\n var incompatibleOpt =\n ['startkey', 'endkey', 'key'].filter(function (incompatibleOpt) {\n return incompatibleOpt in opts;\n })[0];\n if (incompatibleOpt) {\n callback(createError(QUERY_PARSE_ERROR,\n 'Query parameter `' + incompatibleOpt +\n '` is not compatible with multi-get'\n ));\n return;\n }\n if (!isRemote(this)) {\n allDocsKeysParse(opts);\n if (opts.keys.length === 0) {\n return this._allDocs({limit: 0}, callback);\n }\n }\n }\n\n return this._allDocs(opts, callback);\n});\n\nAbstractPouchDB.prototype.changes = function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n opts = opts || {};\n\n // By default set return_docs to false if the caller has opts.live = true,\n // this will prevent us from collecting the set of changes indefinitely\n // resulting in growing memory\n opts.return_docs = ('return_docs' in opts) ? opts.return_docs : !opts.live;\n\n return new Changes$1(this, opts, callback);\n};\n\nAbstractPouchDB.prototype.close = adapterFun('close', function (callback) {\n this._closed = true;\n this.emit('closed');\n return this._close(callback);\n});\n\nAbstractPouchDB.prototype.info = adapterFun('info', function (callback) {\n var self = this;\n this._info(function (err, info) {\n if (err) {\n return callback(err);\n }\n // assume we know better than the adapter, unless it informs us\n info.db_name = info.db_name || self.name;\n info.auto_compaction = !!(self.auto_compaction && !isRemote(self));\n info.adapter = self.adapter;\n callback(null, info);\n });\n});\n\nAbstractPouchDB.prototype.id = adapterFun('id', function (callback) {\n return this._id(callback);\n});\n\n/* istanbul ignore next */\nAbstractPouchDB.prototype.type = function () {\n return (typeof this._type === 'function') ? this._type() : this.adapter;\n};\n\nAbstractPouchDB.prototype.bulkDocs =\n adapterFun('bulkDocs', function (req, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n opts = opts || {};\n\n if (Array.isArray(req)) {\n req = {\n docs: req\n };\n }\n\n if (!req || !req.docs || !Array.isArray(req.docs)) {\n return callback(createError(MISSING_BULK_DOCS));\n }\n\n for (var i = 0; i < req.docs.length; ++i) {\n if (typeof req.docs[i] !== 'object' || Array.isArray(req.docs[i])) {\n return callback(createError(NOT_AN_OBJECT));\n }\n }\n\n var attachmentError;\n req.docs.forEach(function (doc) {\n if (doc._attachments) {\n Object.keys(doc._attachments).forEach(function (name) {\n attachmentError = attachmentError || attachmentNameError(name);\n if (!doc._attachments[name].content_type) {\n guardedConsole('warn', 'Attachment', name, 'on document', doc._id, 'is missing content_type');\n }\n });\n }\n });\n\n if (attachmentError) {\n return callback(createError(BAD_REQUEST, attachmentError));\n }\n\n if (!('new_edits' in opts)) {\n if ('new_edits' in req) {\n opts.new_edits = req.new_edits;\n } else {\n opts.new_edits = true;\n }\n }\n\n var adapter = this;\n if (!opts.new_edits && !isRemote(adapter)) {\n // ensure revisions of the same doc are sorted, so that\n // the local adapter processes them correctly (#2935)\n req.docs.sort(compareByIdThenRev);\n }\n\n cleanDocs(req.docs);\n\n // in the case of conflicts, we want to return the _ids to the user\n // however, the underlying adapter may destroy the docs array, so\n // create a copy here\n var ids = req.docs.map(function (doc) {\n return doc._id;\n });\n\n return this._bulkDocs(req, opts, function (err, res) {\n if (err) {\n return callback(err);\n }\n if (!opts.new_edits) {\n // this is what couch does when new_edits is false\n res = res.filter(function (x) {\n return x.error;\n });\n }\n // add ids for error/conflict responses (not required for CouchDB)\n if (!isRemote(adapter)) {\n for (var i = 0, l = res.length; i < l; i++) {\n res[i].id = res[i].id || ids[i];\n }\n }\n\n callback(null, res);\n });\n});\n\nAbstractPouchDB.prototype.registerDependentDatabase =\n adapterFun('registerDependentDatabase', function (dependentDb,\n callback) {\n var depDB = new this.constructor(dependentDb, this.__opts);\n\n function diffFun(doc) {\n doc.dependentDbs = doc.dependentDbs || {};\n if (doc.dependentDbs[dependentDb]) {\n return false; // no update required\n }\n doc.dependentDbs[dependentDb] = true;\n return doc;\n }\n upsert(this, '_local/_pouch_dependentDbs', diffFun)\n .then(function () {\n callback(null, {db: depDB});\n }).catch(callback);\n});\n\nAbstractPouchDB.prototype.destroy =\n adapterFun('destroy', function (opts, callback) {\n\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n var self = this;\n var usePrefix = 'use_prefix' in self ? self.use_prefix : true;\n\n function destroyDb() {\n // call destroy method of the particular adaptor\n self._destroy(opts, function (err, resp) {\n if (err) {\n return callback(err);\n }\n self._destroyed = true;\n self.emit('destroyed');\n callback(null, resp || { 'ok': true });\n });\n }\n\n if (isRemote(self)) {\n // no need to check for dependent DBs if it's a remote DB\n return destroyDb();\n }\n\n self.get('_local/_pouch_dependentDbs', function (err, localDoc) {\n if (err) {\n /* istanbul ignore if */\n if (err.status !== 404) {\n return callback(err);\n } else { // no dependencies\n return destroyDb();\n }\n }\n var dependentDbs = localDoc.dependentDbs;\n var PouchDB = self.constructor;\n var deletedMap = Object.keys(dependentDbs).map(function (name) {\n // use_prefix is only false in the browser\n /* istanbul ignore next */\n var trueName = usePrefix ?\n name.replace(new RegExp('^' + PouchDB.prefix), '') : name;\n return new PouchDB(trueName, self.__opts).destroy();\n });\n Promise.all(deletedMap).then(destroyDb, callback);\n });\n});\n\nfunction TaskQueue() {\n this.isReady = false;\n this.failed = false;\n this.queue = [];\n}\n\nTaskQueue.prototype.execute = function () {\n var fun;\n if (this.failed) {\n while ((fun = this.queue.shift())) {\n fun(this.failed);\n }\n } else {\n while ((fun = this.queue.shift())) {\n fun();\n }\n }\n};\n\nTaskQueue.prototype.fail = function (err) {\n this.failed = err;\n this.execute();\n};\n\nTaskQueue.prototype.ready = function (db) {\n this.isReady = true;\n this.db = db;\n this.execute();\n};\n\nTaskQueue.prototype.addTask = function (fun) {\n this.queue.push(fun);\n if (this.failed) {\n this.execute();\n }\n};\n\nfunction parseAdapter(name, opts) {\n var match = name.match(/([a-z-]*):\\/\\/(.*)/);\n if (match) {\n // the http adapter expects the fully qualified name\n return {\n name: /https?/.test(match[1]) ? match[1] + '://' + match[2] : match[2],\n adapter: match[1]\n };\n }\n\n var adapters = PouchDB.adapters;\n var preferredAdapters = PouchDB.preferredAdapters;\n var prefix = PouchDB.prefix;\n var adapterName = opts.adapter;\n\n if (!adapterName) { // automatically determine adapter\n for (var i = 0; i < preferredAdapters.length; ++i) {\n adapterName = preferredAdapters[i];\n // check for browsers that have been upgraded from websql-only to websql+idb\n /* istanbul ignore if */\n if (adapterName === 'idb' && 'websql' in adapters &&\n hasLocalStorage() && localStorage['_pouch__websqldb_' + prefix + name]) {\n // log it, because this can be confusing during development\n guardedConsole('log', 'PouchDB is downgrading \"' + name + '\" to WebSQL to' +\n ' avoid data loss, because it was already opened with WebSQL.');\n continue; // keep using websql to avoid user data loss\n }\n break;\n }\n }\n\n var adapter = adapters[adapterName];\n\n // if adapter is invalid, then an error will be thrown later\n var usePrefix = (adapter && 'use_prefix' in adapter) ?\n adapter.use_prefix : true;\n\n return {\n name: usePrefix ? (prefix + name) : name,\n adapter: adapterName\n };\n}\n\n// OK, so here's the deal. Consider this code:\n// var db1 = new PouchDB('foo');\n// var db2 = new PouchDB('foo');\n// db1.destroy();\n// ^ these two both need to emit 'destroyed' events,\n// as well as the PouchDB constructor itself.\n// So we have one db object (whichever one got destroy() called on it)\n// responsible for emitting the initial event, which then gets emitted\n// by the constructor, which then broadcasts it to any other dbs\n// that may have been created with the same name.\nfunction prepareForDestruction(self) {\n\n function onDestroyed(from_constructor) {\n self.removeListener('closed', onClosed);\n if (!from_constructor) {\n self.constructor.emit('destroyed', self.name);\n }\n }\n\n function onClosed() {\n self.removeListener('destroyed', onDestroyed);\n self.constructor.emit('unref', self);\n }\n\n self.once('destroyed', onDestroyed);\n self.once('closed', onClosed);\n self.constructor.emit('ref', self);\n}\n\ninherits(PouchDB, AbstractPouchDB);\nfunction PouchDB(name, opts) {\n // In Node our test suite only tests this for PouchAlt unfortunately\n /* istanbul ignore if */\n if (!(this instanceof PouchDB)) {\n return new PouchDB(name, opts);\n }\n\n var self = this;\n opts = opts || {};\n\n if (name && typeof name === 'object') {\n opts = name;\n name = opts.name;\n delete opts.name;\n }\n\n if (opts.deterministic_revs === undefined) {\n opts.deterministic_revs = true;\n }\n\n this.__opts = opts = clone(opts);\n\n self.auto_compaction = opts.auto_compaction;\n self.prefix = PouchDB.prefix;\n\n if (typeof name !== 'string') {\n throw new Error('Missing/invalid DB name');\n }\n\n var prefixedName = (opts.prefix || '') + name;\n var backend = parseAdapter(prefixedName, opts);\n\n opts.name = backend.name;\n opts.adapter = opts.adapter || backend.adapter;\n\n self.name = name;\n self._adapter = opts.adapter;\n PouchDB.emit('debug', ['adapter', 'Picked adapter: ', opts.adapter]);\n\n if (!PouchDB.adapters[opts.adapter] ||\n !PouchDB.adapters[opts.adapter].valid()) {\n throw new Error('Invalid Adapter: ' + opts.adapter);\n }\n\n AbstractPouchDB.call(self);\n self.taskqueue = new TaskQueue();\n\n self.adapter = opts.adapter;\n\n PouchDB.adapters[opts.adapter].call(self, opts, function (err) {\n if (err) {\n return self.taskqueue.fail(err);\n }\n prepareForDestruction(self);\n\n self.emit('created', self);\n PouchDB.emit('created', self.name);\n self.taskqueue.ready(self);\n });\n\n}\n\n// AbortController was introduced quite a while after fetch and\n// isnt required for PouchDB to function so polyfill if needed\nvar a = (typeof AbortController !== 'undefined')\n ? AbortController\n : function () { return {abort: function () {}}; };\n\nvar f$1 = fetch;\nvar h = Headers;\n\nPouchDB.adapters = {};\nPouchDB.preferredAdapters = [];\n\nPouchDB.prefix = '_pouch_';\n\nvar eventEmitter = new EventEmitter();\n\nfunction setUpEventEmitter(Pouch) {\n Object.keys(EventEmitter.prototype).forEach(function (key) {\n if (typeof EventEmitter.prototype[key] === 'function') {\n Pouch[key] = eventEmitter[key].bind(eventEmitter);\n }\n });\n\n // these are created in constructor.js, and allow us to notify each DB with\n // the same name that it was destroyed, via the constructor object\n var destructListeners = Pouch._destructionListeners = new ExportedMap();\n\n Pouch.on('ref', function onConstructorRef(db) {\n if (!destructListeners.has(db.name)) {\n destructListeners.set(db.name, []);\n }\n destructListeners.get(db.name).push(db);\n });\n\n Pouch.on('unref', function onConstructorUnref(db) {\n if (!destructListeners.has(db.name)) {\n return;\n }\n var dbList = destructListeners.get(db.name);\n var pos = dbList.indexOf(db);\n if (pos < 0) {\n /* istanbul ignore next */\n return;\n }\n dbList.splice(pos, 1);\n if (dbList.length > 1) {\n /* istanbul ignore next */\n destructListeners.set(db.name, dbList);\n } else {\n destructListeners.delete(db.name);\n }\n });\n\n Pouch.on('destroyed', function onConstructorDestroyed(name) {\n if (!destructListeners.has(name)) {\n return;\n }\n var dbList = destructListeners.get(name);\n destructListeners.delete(name);\n dbList.forEach(function (db) {\n db.emit('destroyed',true);\n });\n });\n}\n\nsetUpEventEmitter(PouchDB);\n\nPouchDB.adapter = function (id, obj, addToPreferredAdapters) {\n /* istanbul ignore else */\n if (obj.valid()) {\n PouchDB.adapters[id] = obj;\n if (addToPreferredAdapters) {\n PouchDB.preferredAdapters.push(id);\n }\n }\n};\n\nPouchDB.plugin = function (obj) {\n if (typeof obj === 'function') { // function style for plugins\n obj(PouchDB);\n } else if (typeof obj !== 'object' || Object.keys(obj).length === 0) {\n throw new Error('Invalid plugin: got \"' + obj + '\", expected an object or a function');\n } else {\n Object.keys(obj).forEach(function (id) { // object style for plugins\n PouchDB.prototype[id] = obj[id];\n });\n }\n if (this.__defaults) {\n PouchDB.__defaults = $inject_Object_assign({}, this.__defaults);\n }\n return PouchDB;\n};\n\nPouchDB.defaults = function (defaultOpts) {\n function PouchAlt(name, opts) {\n if (!(this instanceof PouchAlt)) {\n return new PouchAlt(name, opts);\n }\n\n opts = opts || {};\n\n if (name && typeof name === 'object') {\n opts = name;\n name = opts.name;\n delete opts.name;\n }\n\n opts = $inject_Object_assign({}, PouchAlt.__defaults, opts);\n PouchDB.call(this, name, opts);\n }\n\n inherits(PouchAlt, PouchDB);\n\n PouchAlt.preferredAdapters = PouchDB.preferredAdapters.slice();\n Object.keys(PouchDB).forEach(function (key) {\n if (!(key in PouchAlt)) {\n PouchAlt[key] = PouchDB[key];\n }\n });\n\n // make default options transitive\n // https://github.com/pouchdb/pouchdb/issues/5922\n PouchAlt.__defaults = $inject_Object_assign({}, this.__defaults, defaultOpts);\n\n return PouchAlt;\n};\n\nPouchDB.fetch = function (url, opts) {\n return f$1(url, opts);\n};\n\n// managed automatically by set-version.js\nvar version = \"7.0.0\";\n\n// this would just be \"return doc[field]\", but fields\n// can be \"deep\" due to dot notation\nfunction getFieldFromDoc(doc, parsedField) {\n var value = doc;\n for (var i = 0, len = parsedField.length; i < len; i++) {\n var key = parsedField[i];\n value = value[key];\n if (!value) {\n break;\n }\n }\n return value;\n}\n\nfunction compare$1(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n// Converts a string in dot notation to an array of its components, with backslash escaping\nfunction parseField(fieldName) {\n // fields may be deep (e.g. \"foo.bar.baz\"), so parse\n var fields = [];\n var current = '';\n for (var i = 0, len = fieldName.length; i < len; i++) {\n var ch = fieldName[i];\n if (ch === '.') {\n if (i > 0 && fieldName[i - 1] === '\\\\') { // escaped delimiter\n current = current.substring(0, current.length - 1) + '.';\n } else { // not escaped, so delimiter\n fields.push(current);\n current = '';\n }\n } else { // normal character\n current += ch;\n }\n }\n fields.push(current);\n return fields;\n}\n\nvar combinationFields = ['$or', '$nor', '$not'];\nfunction isCombinationalField(field) {\n return combinationFields.indexOf(field) > -1;\n}\n\nfunction getKey(obj) {\n return Object.keys(obj)[0];\n}\n\nfunction getValue(obj) {\n return obj[getKey(obj)];\n}\n\n\n// flatten an array of selectors joined by an $and operator\nfunction mergeAndedSelectors(selectors) {\n\n // sort to ensure that e.g. if the user specified\n // $and: [{$gt: 'a'}, {$gt: 'b'}], then it's collapsed into\n // just {$gt: 'b'}\n var res = {};\n\n selectors.forEach(function (selector) {\n Object.keys(selector).forEach(function (field) {\n var matcher = selector[field];\n if (typeof matcher !== 'object') {\n matcher = {$eq: matcher};\n }\n\n if (isCombinationalField(field)) {\n if (matcher instanceof Array) {\n res[field] = matcher.map(function (m) {\n return mergeAndedSelectors([m]);\n });\n } else {\n res[field] = mergeAndedSelectors([matcher]);\n }\n } else {\n var fieldMatchers = res[field] = res[field] || {};\n Object.keys(matcher).forEach(function (operator) {\n var value = matcher[operator];\n\n if (operator === '$gt' || operator === '$gte') {\n return mergeGtGte(operator, value, fieldMatchers);\n } else if (operator === '$lt' || operator === '$lte') {\n return mergeLtLte(operator, value, fieldMatchers);\n } else if (operator === '$ne') {\n return mergeNe(value, fieldMatchers);\n } else if (operator === '$eq') {\n return mergeEq(value, fieldMatchers);\n }\n fieldMatchers[operator] = value;\n });\n }\n });\n });\n\n return res;\n}\n\n\n\n// collapse logically equivalent gt/gte values\nfunction mergeGtGte(operator, value, fieldMatchers) {\n if (typeof fieldMatchers.$eq !== 'undefined') {\n return; // do nothing\n }\n if (typeof fieldMatchers.$gte !== 'undefined') {\n if (operator === '$gte') {\n if (value > fieldMatchers.$gte) { // more specificity\n fieldMatchers.$gte = value;\n }\n } else { // operator === '$gt'\n if (value >= fieldMatchers.$gte) { // more specificity\n delete fieldMatchers.$gte;\n fieldMatchers.$gt = value;\n }\n }\n } else if (typeof fieldMatchers.$gt !== 'undefined') {\n if (operator === '$gte') {\n if (value > fieldMatchers.$gt) { // more specificity\n delete fieldMatchers.$gt;\n fieldMatchers.$gte = value;\n }\n } else { // operator === '$gt'\n if (value > fieldMatchers.$gt) { // more specificity\n fieldMatchers.$gt = value;\n }\n }\n } else {\n fieldMatchers[operator] = value;\n }\n}\n\n// collapse logically equivalent lt/lte values\nfunction mergeLtLte(operator, value, fieldMatchers) {\n if (typeof fieldMatchers.$eq !== 'undefined') {\n return; // do nothing\n }\n if (typeof fieldMatchers.$lte !== 'undefined') {\n if (operator === '$lte') {\n if (value < fieldMatchers.$lte) { // more specificity\n fieldMatchers.$lte = value;\n }\n } else { // operator === '$gt'\n if (value <= fieldMatchers.$lte) { // more specificity\n delete fieldMatchers.$lte;\n fieldMatchers.$lt = value;\n }\n }\n } else if (typeof fieldMatchers.$lt !== 'undefined') {\n if (operator === '$lte') {\n if (value < fieldMatchers.$lt) { // more specificity\n delete fieldMatchers.$lt;\n fieldMatchers.$lte = value;\n }\n } else { // operator === '$gt'\n if (value < fieldMatchers.$lt) { // more specificity\n fieldMatchers.$lt = value;\n }\n }\n } else {\n fieldMatchers[operator] = value;\n }\n}\n\n// combine $ne values into one array\nfunction mergeNe(value, fieldMatchers) {\n if ('$ne' in fieldMatchers) {\n // there are many things this could \"not\" be\n fieldMatchers.$ne.push(value);\n } else { // doesn't exist yet\n fieldMatchers.$ne = [value];\n }\n}\n\n// add $eq into the mix\nfunction mergeEq(value, fieldMatchers) {\n // these all have less specificity than the $eq\n // TODO: check for user errors here\n delete fieldMatchers.$gt;\n delete fieldMatchers.$gte;\n delete fieldMatchers.$lt;\n delete fieldMatchers.$lte;\n delete fieldMatchers.$ne;\n fieldMatchers.$eq = value;\n}\n\n\n//\n// normalize the selector\n//\nfunction massageSelector(input) {\n var result = clone(input);\n var wasAnded = false;\n if ('$and' in result) {\n result = mergeAndedSelectors(result['$and']);\n wasAnded = true;\n }\n\n ['$or', '$nor'].forEach(function (orOrNor) {\n if (orOrNor in result) {\n // message each individual selector\n // e.g. {foo: 'bar'} becomes {foo: {$eq: 'bar'}}\n result[orOrNor].forEach(function (subSelector) {\n var fields = Object.keys(subSelector);\n for (var i = 0; i < fields.length; i++) {\n var field = fields[i];\n var matcher = subSelector[field];\n if (typeof matcher !== 'object' || matcher === null) {\n subSelector[field] = {$eq: matcher};\n }\n }\n });\n }\n });\n\n if ('$not' in result) {\n //This feels a little like forcing, but it will work for now,\n //I would like to come back to this and make the merging of selectors a little more generic\n result['$not'] = mergeAndedSelectors([result['$not']]);\n }\n\n var fields = Object.keys(result);\n\n for (var i = 0; i < fields.length; i++) {\n var field = fields[i];\n var matcher = result[field];\n\n if (typeof matcher !== 'object' || matcher === null) {\n matcher = {$eq: matcher};\n } else if ('$ne' in matcher && !wasAnded) {\n // I put these in an array, since there may be more than one\n // but in the \"mergeAnded\" operation, I already take care of that\n matcher.$ne = [matcher.$ne];\n }\n result[field] = matcher;\n }\n\n return result;\n}\n\nfunction pad(str, padWith, upToLength) {\n var padding = '';\n var targetLength = upToLength - str.length;\n /* istanbul ignore next */\n while (padding.length < targetLength) {\n padding += padWith;\n }\n return padding;\n}\n\nfunction padLeft(str, padWith, upToLength) {\n var padding = pad(str, padWith, upToLength);\n return padding + str;\n}\n\nvar MIN_MAGNITUDE = -324; // verified by -Number.MIN_VALUE\nvar MAGNITUDE_DIGITS = 3; // ditto\nvar SEP = ''; // set to '_' for easier debugging \n\nfunction collate(a, b) {\n\n if (a === b) {\n return 0;\n }\n\n a = normalizeKey(a);\n b = normalizeKey(b);\n\n var ai = collationIndex(a);\n var bi = collationIndex(b);\n if ((ai - bi) !== 0) {\n return ai - bi;\n }\n switch (typeof a) {\n case 'number':\n return a - b;\n case 'boolean':\n return a < b ? -1 : 1;\n case 'string':\n return stringCollate(a, b);\n }\n return Array.isArray(a) ? arrayCollate(a, b) : objectCollate(a, b);\n}\n\n// couch considers null/NaN/Infinity/-Infinity === undefined,\n// for the purposes of mapreduce indexes. also, dates get stringified.\nfunction normalizeKey(key) {\n switch (typeof key) {\n case 'undefined':\n return null;\n case 'number':\n if (key === Infinity || key === -Infinity || isNaN(key)) {\n return null;\n }\n return key;\n case 'object':\n var origKey = key;\n if (Array.isArray(key)) {\n var len = key.length;\n key = new Array(len);\n for (var i = 0; i < len; i++) {\n key[i] = normalizeKey(origKey[i]);\n }\n /* istanbul ignore next */\n } else if (key instanceof Date) {\n return key.toJSON();\n } else if (key !== null) { // generic object\n key = {};\n for (var k in origKey) {\n if (origKey.hasOwnProperty(k)) {\n var val = origKey[k];\n if (typeof val !== 'undefined') {\n key[k] = normalizeKey(val);\n }\n }\n }\n }\n }\n return key;\n}\n\nfunction indexify(key) {\n if (key !== null) {\n switch (typeof key) {\n case 'boolean':\n return key ? 1 : 0;\n case 'number':\n return numToIndexableString(key);\n case 'string':\n // We've to be sure that key does not contain \\u0000\n // Do order-preserving replacements:\n // 0 -> 1, 1\n // 1 -> 1, 2\n // 2 -> 2, 2\n /* eslint-disable no-control-regex */\n return key\n .replace(/\\u0002/g, '\\u0002\\u0002')\n .replace(/\\u0001/g, '\\u0001\\u0002')\n .replace(/\\u0000/g, '\\u0001\\u0001');\n /* eslint-enable no-control-regex */\n case 'object':\n var isArray = Array.isArray(key);\n var arr = isArray ? key : Object.keys(key);\n var i = -1;\n var len = arr.length;\n var result = '';\n if (isArray) {\n while (++i < len) {\n result += toIndexableString(arr[i]);\n }\n } else {\n while (++i < len) {\n var objKey = arr[i];\n result += toIndexableString(objKey) +\n toIndexableString(key[objKey]);\n }\n }\n return result;\n }\n }\n return '';\n}\n\n// convert the given key to a string that would be appropriate\n// for lexical sorting, e.g. within a database, where the\n// sorting is the same given by the collate() function.\nfunction toIndexableString(key) {\n var zero = '\\u0000';\n key = normalizeKey(key);\n return collationIndex(key) + SEP + indexify(key) + zero;\n}\n\nfunction parseNumber(str, i) {\n var originalIdx = i;\n var num;\n var zero = str[i] === '1';\n if (zero) {\n num = 0;\n i++;\n } else {\n var neg = str[i] === '0';\n i++;\n var numAsString = '';\n var magAsString = str.substring(i, i + MAGNITUDE_DIGITS);\n var magnitude = parseInt(magAsString, 10) + MIN_MAGNITUDE;\n /* istanbul ignore next */\n if (neg) {\n magnitude = -magnitude;\n }\n i += MAGNITUDE_DIGITS;\n while (true) {\n var ch = str[i];\n if (ch === '\\u0000') {\n break;\n } else {\n numAsString += ch;\n }\n i++;\n }\n numAsString = numAsString.split('.');\n if (numAsString.length === 1) {\n num = parseInt(numAsString, 10);\n } else {\n /* istanbul ignore next */\n num = parseFloat(numAsString[0] + '.' + numAsString[1]);\n }\n /* istanbul ignore next */\n if (neg) {\n num = num - 10;\n }\n /* istanbul ignore next */\n if (magnitude !== 0) {\n // parseFloat is more reliable than pow due to rounding errors\n // e.g. Number.MAX_VALUE would return Infinity if we did\n // num * Math.pow(10, magnitude);\n num = parseFloat(num + 'e' + magnitude);\n }\n }\n return {num: num, length : i - originalIdx};\n}\n\n// move up the stack while parsing\n// this function moved outside of parseIndexableString for performance\nfunction pop(stack, metaStack) {\n var obj = stack.pop();\n\n if (metaStack.length) {\n var lastMetaElement = metaStack[metaStack.length - 1];\n if (obj === lastMetaElement.element) {\n // popping a meta-element, e.g. an object whose value is another object\n metaStack.pop();\n lastMetaElement = metaStack[metaStack.length - 1];\n }\n var element = lastMetaElement.element;\n var lastElementIndex = lastMetaElement.index;\n if (Array.isArray(element)) {\n element.push(obj);\n } else if (lastElementIndex === stack.length - 2) { // obj with key+value\n var key = stack.pop();\n element[key] = obj;\n } else {\n stack.push(obj); // obj with key only\n }\n }\n}\n\nfunction parseIndexableString(str) {\n var stack = [];\n var metaStack = []; // stack for arrays and objects\n var i = 0;\n\n /*eslint no-constant-condition: [\"error\", { \"checkLoops\": false }]*/\n while (true) {\n var collationIndex = str[i++];\n if (collationIndex === '\\u0000') {\n if (stack.length === 1) {\n return stack.pop();\n } else {\n pop(stack, metaStack);\n continue;\n }\n }\n switch (collationIndex) {\n case '1':\n stack.push(null);\n break;\n case '2':\n stack.push(str[i] === '1');\n i++;\n break;\n case '3':\n var parsedNum = parseNumber(str, i);\n stack.push(parsedNum.num);\n i += parsedNum.length;\n break;\n case '4':\n var parsedStr = '';\n /*eslint no-constant-condition: [\"error\", { \"checkLoops\": false }]*/\n while (true) {\n var ch = str[i];\n if (ch === '\\u0000') {\n break;\n }\n parsedStr += ch;\n i++;\n }\n // perform the reverse of the order-preserving replacement\n // algorithm (see above)\n /* eslint-disable no-control-regex */\n parsedStr = parsedStr.replace(/\\u0001\\u0001/g, '\\u0000')\n .replace(/\\u0001\\u0002/g, '\\u0001')\n .replace(/\\u0002\\u0002/g, '\\u0002');\n /* eslint-enable no-control-regex */\n stack.push(parsedStr);\n break;\n case '5':\n var arrayElement = { element: [], index: stack.length };\n stack.push(arrayElement.element);\n metaStack.push(arrayElement);\n break;\n case '6':\n var objElement = { element: {}, index: stack.length };\n stack.push(objElement.element);\n metaStack.push(objElement);\n break;\n /* istanbul ignore next */\n default:\n throw new Error(\n 'bad collationIndex or unexpectedly reached end of input: ' +\n collationIndex);\n }\n }\n}\n\nfunction arrayCollate(a, b) {\n var len = Math.min(a.length, b.length);\n for (var i = 0; i < len; i++) {\n var sort = collate(a[i], b[i]);\n if (sort !== 0) {\n return sort;\n }\n }\n return (a.length === b.length) ? 0 :\n (a.length > b.length) ? 1 : -1;\n}\nfunction stringCollate(a, b) {\n // See: https://github.com/daleharvey/pouchdb/issues/40\n // This is incompatible with the CouchDB implementation, but its the\n // best we can do for now\n return (a === b) ? 0 : ((a > b) ? 1 : -1);\n}\nfunction objectCollate(a, b) {\n var ak = Object.keys(a), bk = Object.keys(b);\n var len = Math.min(ak.length, bk.length);\n for (var i = 0; i < len; i++) {\n // First sort the keys\n var sort = collate(ak[i], bk[i]);\n if (sort !== 0) {\n return sort;\n }\n // if the keys are equal sort the values\n sort = collate(a[ak[i]], b[bk[i]]);\n if (sort !== 0) {\n return sort;\n }\n\n }\n return (ak.length === bk.length) ? 0 :\n (ak.length > bk.length) ? 1 : -1;\n}\n// The collation is defined by erlangs ordered terms\n// the atoms null, true, false come first, then numbers, strings,\n// arrays, then objects\n// null/undefined/NaN/Infinity/-Infinity are all considered null\nfunction collationIndex(x) {\n var id = ['boolean', 'number', 'string', 'object'];\n var idx = id.indexOf(typeof x);\n //false if -1 otherwise true, but fast!!!!1\n if (~idx) {\n if (x === null) {\n return 1;\n }\n if (Array.isArray(x)) {\n return 5;\n }\n return idx < 3 ? (idx + 2) : (idx + 3);\n }\n /* istanbul ignore next */\n if (Array.isArray(x)) {\n return 5;\n }\n}\n\n// conversion:\n// x yyy zz...zz\n// x = 0 for negative, 1 for 0, 2 for positive\n// y = exponent (for negative numbers negated) moved so that it's >= 0\n// z = mantisse\nfunction numToIndexableString(num) {\n\n if (num === 0) {\n return '1';\n }\n\n // convert number to exponential format for easier and\n // more succinct string sorting\n var expFormat = num.toExponential().split(/e\\+?/);\n var magnitude = parseInt(expFormat[1], 10);\n\n var neg = num < 0;\n\n var result = neg ? '0' : '2';\n\n // first sort by magnitude\n // it's easier if all magnitudes are positive\n var magForComparison = ((neg ? -magnitude : magnitude) - MIN_MAGNITUDE);\n var magString = padLeft((magForComparison).toString(), '0', MAGNITUDE_DIGITS);\n\n result += SEP + magString;\n\n // then sort by the factor\n var factor = Math.abs(parseFloat(expFormat[0])); // [1..10)\n /* istanbul ignore next */\n if (neg) { // for negative reverse ordering\n factor = 10 - factor;\n }\n\n var factorStr = factor.toFixed(20);\n\n // strip zeros from the end\n factorStr = factorStr.replace(/\\.?0+$/, '');\n\n result += SEP + factorStr;\n\n return result;\n}\n\n// create a comparator based on the sort object\nfunction createFieldSorter(sort) {\n\n function getFieldValuesAsArray(doc) {\n return sort.map(function (sorting) {\n var fieldName = getKey(sorting);\n var parsedField = parseField(fieldName);\n var docFieldValue = getFieldFromDoc(doc, parsedField);\n return docFieldValue;\n });\n }\n\n return function (aRow, bRow) {\n var aFieldValues = getFieldValuesAsArray(aRow.doc);\n var bFieldValues = getFieldValuesAsArray(bRow.doc);\n var collation = collate(aFieldValues, bFieldValues);\n if (collation !== 0) {\n return collation;\n }\n // this is what mango seems to do\n return compare$1(aRow.doc._id, bRow.doc._id);\n };\n}\n\nfunction filterInMemoryFields(rows, requestDef, inMemoryFields) {\n rows = rows.filter(function (row) {\n return rowFilter(row.doc, requestDef.selector, inMemoryFields);\n });\n\n if (requestDef.sort) {\n // in-memory sort\n var fieldSorter = createFieldSorter(requestDef.sort);\n rows = rows.sort(fieldSorter);\n if (typeof requestDef.sort[0] !== 'string' &&\n getValue(requestDef.sort[0]) === 'desc') {\n rows = rows.reverse();\n }\n }\n\n if ('limit' in requestDef || 'skip' in requestDef) {\n // have to do the limit in-memory\n var skip = requestDef.skip || 0;\n var limit = ('limit' in requestDef ? requestDef.limit : rows.length) + skip;\n rows = rows.slice(skip, limit);\n }\n return rows;\n}\n\nfunction rowFilter(doc, selector, inMemoryFields) {\n return inMemoryFields.every(function (field) {\n var matcher = selector[field];\n var parsedField = parseField(field);\n var docFieldValue = getFieldFromDoc(doc, parsedField);\n if (isCombinationalField(field)) {\n return matchCominationalSelector(field, matcher, doc);\n }\n\n return matchSelector(matcher, doc, parsedField, docFieldValue);\n });\n}\n\nfunction matchSelector(matcher, doc, parsedField, docFieldValue) {\n if (!matcher) {\n // no filtering necessary; this field is just needed for sorting\n return true;\n }\n\n return Object.keys(matcher).every(function (userOperator) {\n var userValue = matcher[userOperator];\n return match(userOperator, doc, userValue, parsedField, docFieldValue);\n });\n}\n\nfunction matchCominationalSelector(field, matcher, doc) {\n\n if (field === '$or') {\n return matcher.some(function (orMatchers) {\n return rowFilter(doc, orMatchers, Object.keys(orMatchers));\n });\n }\n\n if (field === '$not') {\n return !rowFilter(doc, matcher, Object.keys(matcher));\n }\n\n //`$nor`\n return !matcher.find(function (orMatchers) {\n return rowFilter(doc, orMatchers, Object.keys(orMatchers));\n });\n\n}\n\nfunction match(userOperator, doc, userValue, parsedField, docFieldValue) {\n if (!matchers[userOperator]) {\n throw new Error('unknown operator \"' + userOperator +\n '\" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, ' +\n '$nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');\n }\n return matchers[userOperator](doc, userValue, parsedField, docFieldValue);\n}\n\nfunction fieldExists(docFieldValue) {\n return typeof docFieldValue !== 'undefined' && docFieldValue !== null;\n}\n\nfunction fieldIsNotUndefined(docFieldValue) {\n return typeof docFieldValue !== 'undefined';\n}\n\nfunction modField(docFieldValue, userValue) {\n var divisor = userValue[0];\n var mod = userValue[1];\n if (divisor === 0) {\n throw new Error('Bad divisor, cannot divide by zero');\n }\n\n if (parseInt(divisor, 10) !== divisor ) {\n throw new Error('Divisor is not an integer');\n }\n\n if (parseInt(mod, 10) !== mod ) {\n throw new Error('Modulus is not an integer');\n }\n\n if (parseInt(docFieldValue, 10) !== docFieldValue) {\n return false;\n }\n\n return docFieldValue % divisor === mod;\n}\n\nfunction arrayContainsValue(docFieldValue, userValue) {\n return userValue.some(function (val) {\n if (docFieldValue instanceof Array) {\n return docFieldValue.indexOf(val) > -1;\n }\n\n return docFieldValue === val;\n });\n}\n\nfunction arrayContainsAllValues(docFieldValue, userValue) {\n return userValue.every(function (val) {\n return docFieldValue.indexOf(val) > -1;\n });\n}\n\nfunction arraySize(docFieldValue, userValue) {\n return docFieldValue.length === userValue;\n}\n\nfunction regexMatch(docFieldValue, userValue) {\n var re = new RegExp(userValue);\n\n return re.test(docFieldValue);\n}\n\nfunction typeMatch(docFieldValue, userValue) {\n\n switch (userValue) {\n case 'null':\n return docFieldValue === null;\n case 'boolean':\n return typeof (docFieldValue) === 'boolean';\n case 'number':\n return typeof (docFieldValue) === 'number';\n case 'string':\n return typeof (docFieldValue) === 'string';\n case 'array':\n return docFieldValue instanceof Array;\n case 'object':\n return ({}).toString.call(docFieldValue) === '[object Object]';\n }\n\n throw new Error(userValue + ' not supported as a type.' +\n 'Please use one of object, string, array, number, boolean or null.');\n\n}\n\nvar matchers = {\n\n '$elemMatch': function (doc, userValue, parsedField, docFieldValue) {\n if (!Array.isArray(docFieldValue)) {\n return false;\n }\n\n if (docFieldValue.length === 0) {\n return false;\n }\n\n if (typeof docFieldValue[0] === 'object') {\n return docFieldValue.some(function (val) {\n return rowFilter(val, userValue, Object.keys(userValue));\n });\n }\n\n return docFieldValue.some(function (val) {\n return matchSelector(userValue, doc, parsedField, val);\n });\n },\n\n '$allMatch': function (doc, userValue, parsedField, docFieldValue) {\n if (!Array.isArray(docFieldValue)) {\n return false;\n }\n\n /* istanbul ignore next */\n if (docFieldValue.length === 0) {\n return false;\n }\n\n if (typeof docFieldValue[0] === 'object') {\n return docFieldValue.every(function (val) {\n return rowFilter(val, userValue, Object.keys(userValue));\n });\n }\n\n return docFieldValue.every(function (val) {\n return matchSelector(userValue, doc, parsedField, val);\n });\n },\n\n '$eq': function (doc, userValue, parsedField, docFieldValue) {\n return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) === 0;\n },\n\n '$gte': function (doc, userValue, parsedField, docFieldValue) {\n return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) >= 0;\n },\n\n '$gt': function (doc, userValue, parsedField, docFieldValue) {\n return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) > 0;\n },\n\n '$lte': function (doc, userValue, parsedField, docFieldValue) {\n return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) <= 0;\n },\n\n '$lt': function (doc, userValue, parsedField, docFieldValue) {\n return fieldIsNotUndefined(docFieldValue) && collate(docFieldValue, userValue) < 0;\n },\n\n '$exists': function (doc, userValue, parsedField, docFieldValue) {\n //a field that is null is still considered to exist\n if (userValue) {\n return fieldIsNotUndefined(docFieldValue);\n }\n\n return !fieldIsNotUndefined(docFieldValue);\n },\n\n '$mod': function (doc, userValue, parsedField, docFieldValue) {\n return fieldExists(docFieldValue) && modField(docFieldValue, userValue);\n },\n\n '$ne': function (doc, userValue, parsedField, docFieldValue) {\n return userValue.every(function (neValue) {\n return collate(docFieldValue, neValue) !== 0;\n });\n },\n '$in': function (doc, userValue, parsedField, docFieldValue) {\n return fieldExists(docFieldValue) && arrayContainsValue(docFieldValue, userValue);\n },\n\n '$nin': function (doc, userValue, parsedField, docFieldValue) {\n return fieldExists(docFieldValue) && !arrayContainsValue(docFieldValue, userValue);\n },\n\n '$size': function (doc, userValue, parsedField, docFieldValue) {\n return fieldExists(docFieldValue) && arraySize(docFieldValue, userValue);\n },\n\n '$all': function (doc, userValue, parsedField, docFieldValue) {\n return Array.isArray(docFieldValue) && arrayContainsAllValues(docFieldValue, userValue);\n },\n\n '$regex': function (doc, userValue, parsedField, docFieldValue) {\n return fieldExists(docFieldValue) && regexMatch(docFieldValue, userValue);\n },\n\n '$type': function (doc, userValue, parsedField, docFieldValue) {\n return typeMatch(docFieldValue, userValue);\n }\n};\n\n// return true if the given doc matches the supplied selector\nfunction matchesSelector(doc, selector) {\n /* istanbul ignore if */\n if (typeof selector !== 'object') {\n // match the CouchDB error message\n throw new Error('Selector error: expected a JSON object');\n }\n\n selector = massageSelector(selector);\n var row = {\n 'doc': doc\n };\n\n var rowsMatched = filterInMemoryFields([row], { 'selector': selector }, Object.keys(selector));\n return rowsMatched && rowsMatched.length === 1;\n}\n\nfunction evalFilter(input) {\n return scopeEval('\"use strict\";\\nreturn ' + input + ';', {});\n}\n\nfunction evalView(input) {\n var code = [\n 'return function(doc) {',\n ' \"use strict\";',\n ' var emitted = false;',\n ' var emit = function (a, b) {',\n ' emitted = true;',\n ' };',\n ' var view = ' + input + ';',\n ' view(doc);',\n ' if (emitted) {',\n ' return true;',\n ' }',\n '};'\n ].join('\\n');\n\n return scopeEval(code, {});\n}\n\nfunction validate(opts, callback) {\n if (opts.selector) {\n if (opts.filter && opts.filter !== '_selector') {\n var filterName = typeof opts.filter === 'string' ?\n opts.filter : 'function';\n return callback(new Error('selector invalid for filter \"' + filterName + '\"'));\n }\n }\n callback();\n}\n\nfunction normalize(opts) {\n if (opts.view && !opts.filter) {\n opts.filter = '_view';\n }\n\n if (opts.selector && !opts.filter) {\n opts.filter = '_selector';\n }\n\n if (opts.filter && typeof opts.filter === 'string') {\n if (opts.filter === '_view') {\n opts.view = normalizeDesignDocFunctionName(opts.view);\n } else {\n opts.filter = normalizeDesignDocFunctionName(opts.filter);\n }\n }\n}\n\nfunction shouldFilter(changesHandler, opts) {\n return opts.filter && typeof opts.filter === 'string' &&\n !opts.doc_ids && !isRemote(changesHandler.db);\n}\n\nfunction filter(changesHandler, opts) {\n var callback = opts.complete;\n if (opts.filter === '_view') {\n if (!opts.view || typeof opts.view !== 'string') {\n var err = createError(BAD_REQUEST,\n '`view` filter parameter not found or invalid.');\n return callback(err);\n }\n // fetch a view from a design doc, make it behave like a filter\n var viewName = parseDesignDocFunctionName(opts.view);\n changesHandler.db.get('_design/' + viewName[0], function (err, ddoc) {\n /* istanbul ignore if */\n if (changesHandler.isCancelled) {\n return callback(null, {status: 'cancelled'});\n }\n /* istanbul ignore next */\n if (err) {\n return callback(generateErrorFromResponse(err));\n }\n var mapFun = ddoc && ddoc.views && ddoc.views[viewName[1]] &&\n ddoc.views[viewName[1]].map;\n if (!mapFun) {\n return callback(createError(MISSING_DOC,\n (ddoc.views ? 'missing json key: ' + viewName[1] :\n 'missing json key: views')));\n }\n opts.filter = evalView(mapFun);\n changesHandler.doChanges(opts);\n });\n } else if (opts.selector) {\n opts.filter = function (doc) {\n return matchesSelector(doc, opts.selector);\n };\n changesHandler.doChanges(opts);\n } else {\n // fetch a filter from a design doc\n var filterName = parseDesignDocFunctionName(opts.filter);\n changesHandler.db.get('_design/' + filterName[0], function (err, ddoc) {\n /* istanbul ignore if */\n if (changesHandler.isCancelled) {\n return callback(null, {status: 'cancelled'});\n }\n /* istanbul ignore next */\n if (err) {\n return callback(generateErrorFromResponse(err));\n }\n var filterFun = ddoc && ddoc.filters && ddoc.filters[filterName[1]];\n if (!filterFun) {\n return callback(createError(MISSING_DOC,\n ((ddoc && ddoc.filters) ? 'missing json key: ' + filterName[1]\n : 'missing json key: filters')));\n }\n opts.filter = evalFilter(filterFun);\n changesHandler.doChanges(opts);\n });\n }\n}\n\nfunction applyChangesFilterPlugin(PouchDB) {\n PouchDB._changesFilterPlugin = {\n validate: validate,\n normalize: normalize,\n shouldFilter: shouldFilter,\n filter: filter\n };\n}\n\n// TODO: remove from pouchdb-core (breaking)\nPouchDB.plugin(applyChangesFilterPlugin);\n\nPouchDB.version = version;\n\nfunction toObject(array) {\n return array.reduce(function (obj, item) {\n obj[item] = true;\n return obj;\n }, {});\n}\n// List of top level reserved words for doc\nvar reservedWords = toObject([\n '_id',\n '_rev',\n '_attachments',\n '_deleted',\n '_revisions',\n '_revs_info',\n '_conflicts',\n '_deleted_conflicts',\n '_local_seq',\n '_rev_tree',\n //replication documents\n '_replication_id',\n '_replication_state',\n '_replication_state_time',\n '_replication_state_reason',\n '_replication_stats',\n // Specific to Couchbase Sync Gateway\n '_removed'\n]);\n\n// List of reserved words that should end up the document\nvar dataWords = toObject([\n '_attachments',\n //replication documents\n '_replication_id',\n '_replication_state',\n '_replication_state_time',\n '_replication_state_reason',\n '_replication_stats'\n]);\n\nfunction parseRevisionInfo(rev) {\n if (!/^\\d+-./.test(rev)) {\n return createError(INVALID_REV);\n }\n var idx = rev.indexOf('-');\n var left = rev.substring(0, idx);\n var right = rev.substring(idx + 1);\n return {\n prefix: parseInt(left, 10),\n id: right\n };\n}\n\nfunction makeRevTreeFromRevisions(revisions, opts) {\n var pos = revisions.start - revisions.ids.length + 1;\n\n var revisionIds = revisions.ids;\n var ids = [revisionIds[0], opts, []];\n\n for (var i = 1, len = revisionIds.length; i < len; i++) {\n ids = [revisionIds[i], {status: 'missing'}, [ids]];\n }\n\n return [{\n pos: pos,\n ids: ids\n }];\n}\n\n// Preprocess documents, parse their revisions, assign an id and a\n// revision for new writes that are missing them, etc\nfunction parseDoc(doc, newEdits, dbOpts) {\n if (!dbOpts) {\n dbOpts = {\n deterministic_revs: true\n };\n }\n\n var nRevNum;\n var newRevId;\n var revInfo;\n var opts = {status: 'available'};\n if (doc._deleted) {\n opts.deleted = true;\n }\n\n if (newEdits) {\n if (!doc._id) {\n doc._id = uuid();\n }\n newRevId = rev$$1(doc, dbOpts.deterministic_revs);\n if (doc._rev) {\n revInfo = parseRevisionInfo(doc._rev);\n if (revInfo.error) {\n return revInfo;\n }\n doc._rev_tree = [{\n pos: revInfo.prefix,\n ids: [revInfo.id, {status: 'missing'}, [[newRevId, opts, []]]]\n }];\n nRevNum = revInfo.prefix + 1;\n } else {\n doc._rev_tree = [{\n pos: 1,\n ids : [newRevId, opts, []]\n }];\n nRevNum = 1;\n }\n } else {\n if (doc._revisions) {\n doc._rev_tree = makeRevTreeFromRevisions(doc._revisions, opts);\n nRevNum = doc._revisions.start;\n newRevId = doc._revisions.ids[0];\n }\n if (!doc._rev_tree) {\n revInfo = parseRevisionInfo(doc._rev);\n if (revInfo.error) {\n return revInfo;\n }\n nRevNum = revInfo.prefix;\n newRevId = revInfo.id;\n doc._rev_tree = [{\n pos: nRevNum,\n ids: [newRevId, opts, []]\n }];\n }\n }\n\n invalidIdError(doc._id);\n\n doc._rev = nRevNum + '-' + newRevId;\n\n var result = {metadata : {}, data : {}};\n for (var key in doc) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(doc, key)) {\n var specialKey = key[0] === '_';\n if (specialKey && !reservedWords[key]) {\n var error = createError(DOC_VALIDATION, key);\n error.message = DOC_VALIDATION.message + ': ' + key;\n throw error;\n } else if (specialKey && !dataWords[key]) {\n result.metadata[key.slice(1)] = doc[key];\n } else {\n result.data[key] = doc[key];\n }\n }\n }\n return result;\n}\n\nfunction parseBase64(data) {\n try {\n return thisAtob(data);\n } catch (e) {\n var err = createError(BAD_ARG,\n 'Attachment is not a valid base64 string');\n return {error: err};\n }\n}\n\nfunction preprocessString(att, blobType, callback) {\n var asBinary = parseBase64(att.data);\n if (asBinary.error) {\n return callback(asBinary.error);\n }\n\n att.length = asBinary.length;\n if (blobType === 'blob') {\n att.data = binStringToBluffer(asBinary, att.content_type);\n } else if (blobType === 'base64') {\n att.data = thisBtoa(asBinary);\n } else { // binary\n att.data = asBinary;\n }\n binaryMd5(asBinary, function (result) {\n att.digest = 'md5-' + result;\n callback();\n });\n}\n\nfunction preprocessBlob(att, blobType, callback) {\n binaryMd5(att.data, function (md5) {\n att.digest = 'md5-' + md5;\n // size is for blobs (browser), length is for buffers (node)\n att.length = att.data.size || att.data.length || 0;\n if (blobType === 'binary') {\n blobToBinaryString(att.data, function (binString) {\n att.data = binString;\n callback();\n });\n } else if (blobType === 'base64') {\n blobToBase64(att.data, function (b64) {\n att.data = b64;\n callback();\n });\n } else {\n callback();\n }\n });\n}\n\nfunction preprocessAttachment(att, blobType, callback) {\n if (att.stub) {\n return callback();\n }\n if (typeof att.data === 'string') { // input is a base64 string\n preprocessString(att, blobType, callback);\n } else { // input is a blob\n preprocessBlob(att, blobType, callback);\n }\n}\n\nfunction preprocessAttachments(docInfos, blobType, callback) {\n\n if (!docInfos.length) {\n return callback();\n }\n\n var docv = 0;\n var overallErr;\n\n docInfos.forEach(function (docInfo) {\n var attachments = docInfo.data && docInfo.data._attachments ?\n Object.keys(docInfo.data._attachments) : [];\n var recv = 0;\n\n if (!attachments.length) {\n return done();\n }\n\n function processedAttachment(err) {\n overallErr = err;\n recv++;\n if (recv === attachments.length) {\n done();\n }\n }\n\n for (var key in docInfo.data._attachments) {\n if (docInfo.data._attachments.hasOwnProperty(key)) {\n preprocessAttachment(docInfo.data._attachments[key],\n blobType, processedAttachment);\n }\n }\n });\n\n function done() {\n docv++;\n if (docInfos.length === docv) {\n if (overallErr) {\n callback(overallErr);\n } else {\n callback();\n }\n }\n }\n}\n\nfunction updateDoc(revLimit, prev, docInfo, results,\n i, cb, writeDoc, newEdits) {\n\n if (revExists(prev.rev_tree, docInfo.metadata.rev) && !newEdits) {\n results[i] = docInfo;\n return cb();\n }\n\n // sometimes this is pre-calculated. historically not always\n var previousWinningRev = prev.winningRev || winningRev(prev);\n var previouslyDeleted = 'deleted' in prev ? prev.deleted :\n isDeleted(prev, previousWinningRev);\n var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :\n isDeleted(docInfo.metadata);\n var isRoot = /^1-/.test(docInfo.metadata.rev);\n\n if (previouslyDeleted && !deleted && newEdits && isRoot) {\n var newDoc = docInfo.data;\n newDoc._rev = previousWinningRev;\n newDoc._id = docInfo.metadata.id;\n docInfo = parseDoc(newDoc, newEdits);\n }\n\n var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);\n\n var inConflict = newEdits && ((\n (previouslyDeleted && deleted && merged.conflicts !== 'new_leaf') ||\n (!previouslyDeleted && merged.conflicts !== 'new_leaf') ||\n (previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));\n\n if (inConflict) {\n var err = createError(REV_CONFLICT);\n results[i] = err;\n return cb();\n }\n\n var newRev = docInfo.metadata.rev;\n docInfo.metadata.rev_tree = merged.tree;\n docInfo.stemmedRevs = merged.stemmedRevs || [];\n /* istanbul ignore else */\n if (prev.rev_map) {\n docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb\n }\n\n // recalculate\n var winningRev$$1 = winningRev(docInfo.metadata);\n var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev$$1);\n\n // calculate the total number of documents that were added/removed,\n // from the perspective of total_rows/doc_count\n var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :\n previouslyDeleted < winningRevIsDeleted ? -1 : 1;\n\n var newRevIsDeleted;\n if (newRev === winningRev$$1) {\n // if the new rev is the same as the winning rev, we can reuse that value\n newRevIsDeleted = winningRevIsDeleted;\n } else {\n // if they're not the same, then we need to recalculate\n newRevIsDeleted = isDeleted(docInfo.metadata, newRev);\n }\n\n writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,\n true, delta, i, cb);\n}\n\nfunction rootIsMissing(docInfo) {\n return docInfo.metadata.rev_tree[0].ids[1].status === 'missing';\n}\n\nfunction processDocs(revLimit, docInfos, api, fetchedDocs, tx, results,\n writeDoc, opts, overallCallback) {\n\n // Default to 1000 locally\n revLimit = revLimit || 1000;\n\n function insertDoc(docInfo, resultsIdx, callback) {\n // Cant insert new deleted documents\n var winningRev$$1 = winningRev(docInfo.metadata);\n var deleted = isDeleted(docInfo.metadata, winningRev$$1);\n if ('was_delete' in opts && deleted) {\n results[resultsIdx] = createError(MISSING_DOC, 'deleted');\n return callback();\n }\n\n // 4712 - detect whether a new document was inserted with a _rev\n var inConflict = newEdits && rootIsMissing(docInfo);\n\n if (inConflict) {\n var err = createError(REV_CONFLICT);\n results[resultsIdx] = err;\n return callback();\n }\n\n var delta = deleted ? 0 : 1;\n\n writeDoc(docInfo, winningRev$$1, deleted, deleted, false,\n delta, resultsIdx, callback);\n }\n\n var newEdits = opts.new_edits;\n var idsToDocs = new ExportedMap();\n\n var docsDone = 0;\n var docsToDo = docInfos.length;\n\n function checkAllDocsDone() {\n if (++docsDone === docsToDo && overallCallback) {\n overallCallback();\n }\n }\n\n docInfos.forEach(function (currentDoc, resultsIdx) {\n\n if (currentDoc._id && isLocalId(currentDoc._id)) {\n var fun = currentDoc._deleted ? '_removeLocal' : '_putLocal';\n api[fun](currentDoc, {ctx: tx}, function (err, res) {\n results[resultsIdx] = err || res;\n checkAllDocsDone();\n });\n return;\n }\n\n var id = currentDoc.metadata.id;\n if (idsToDocs.has(id)) {\n docsToDo--; // duplicate\n idsToDocs.get(id).push([currentDoc, resultsIdx]);\n } else {\n idsToDocs.set(id, [[currentDoc, resultsIdx]]);\n }\n });\n\n // in the case of new_edits, the user can provide multiple docs\n // with the same id. these need to be processed sequentially\n idsToDocs.forEach(function (docs, id) {\n var numDone = 0;\n\n function docWritten() {\n if (++numDone < docs.length) {\n nextDoc();\n } else {\n checkAllDocsDone();\n }\n }\n function nextDoc() {\n var value = docs[numDone];\n var currentDoc = value[0];\n var resultsIdx = value[1];\n\n if (fetchedDocs.has(id)) {\n updateDoc(revLimit, fetchedDocs.get(id), currentDoc, results,\n resultsIdx, docWritten, writeDoc, newEdits);\n } else {\n // Ensure stemming applies to new writes as well\n var merged = merge([], currentDoc.metadata.rev_tree[0], revLimit);\n currentDoc.metadata.rev_tree = merged.tree;\n currentDoc.stemmedRevs = merged.stemmedRevs || [];\n insertDoc(currentDoc, resultsIdx, docWritten);\n }\n }\n nextDoc();\n });\n}\n\n// IndexedDB requires a versioned database structure, so we use the\n// version here to manage migrations.\nvar ADAPTER_VERSION = 5;\n\n// The object stores created for each database\n// DOC_STORE stores the document meta data, its revision history and state\n// Keyed by document id\nvar DOC_STORE = 'document-store';\n// BY_SEQ_STORE stores a particular version of a document, keyed by its\n// sequence id\nvar BY_SEQ_STORE = 'by-sequence';\n// Where we store attachments\nvar ATTACH_STORE = 'attach-store';\n// Where we store many-to-many relations\n// between attachment digests and seqs\nvar ATTACH_AND_SEQ_STORE = 'attach-seq-store';\n\n// Where we store database-wide meta data in a single record\n// keyed by id: META_STORE\nvar META_STORE = 'meta-store';\n// Where we store local documents\nvar LOCAL_STORE = 'local-store';\n// Where we detect blob support\nvar DETECT_BLOB_SUPPORT_STORE = 'detect-blob-support';\n\nfunction safeJsonParse(str) {\n // This try/catch guards against stack overflow errors.\n // JSON.parse() is faster than vuvuzela.parse() but vuvuzela\n // cannot overflow.\n try {\n return JSON.parse(str);\n } catch (e) {\n /* istanbul ignore next */\n return vuvuzela.parse(str);\n }\n}\n\nfunction safeJsonStringify(json) {\n try {\n return JSON.stringify(json);\n } catch (e) {\n /* istanbul ignore next */\n return vuvuzela.stringify(json);\n }\n}\n\nfunction idbError(callback) {\n return function (evt) {\n var message = 'unknown_error';\n if (evt.target && evt.target.error) {\n message = evt.target.error.name || evt.target.error.message;\n }\n callback(createError(IDB_ERROR, message, evt.type));\n };\n}\n\n// Unfortunately, the metadata has to be stringified\n// when it is put into the database, because otherwise\n// IndexedDB can throw errors for deeply-nested objects.\n// Originally we just used JSON.parse/JSON.stringify; now\n// we use this custom vuvuzela library that avoids recursion.\n// If we could do it all over again, we'd probably use a\n// format for the revision trees other than JSON.\nfunction encodeMetadata(metadata, winningRev, deleted) {\n return {\n data: safeJsonStringify(metadata),\n winningRev: winningRev,\n deletedOrLocal: deleted ? '1' : '0',\n seq: metadata.seq, // highest seq for this doc\n id: metadata.id\n };\n}\n\nfunction decodeMetadata(storedObject) {\n if (!storedObject) {\n return null;\n }\n var metadata = safeJsonParse(storedObject.data);\n metadata.winningRev = storedObject.winningRev;\n metadata.deleted = storedObject.deletedOrLocal === '1';\n metadata.seq = storedObject.seq;\n return metadata;\n}\n\n// read the doc back out from the database. we don't store the\n// _id or _rev because we already have _doc_id_rev.\nfunction decodeDoc(doc) {\n if (!doc) {\n return doc;\n }\n var idx = doc._doc_id_rev.lastIndexOf(':');\n doc._id = doc._doc_id_rev.substring(0, idx - 1);\n doc._rev = doc._doc_id_rev.substring(idx + 1);\n delete doc._doc_id_rev;\n return doc;\n}\n\n// Read a blob from the database, encoding as necessary\n// and translating from base64 if the IDB doesn't support\n// native Blobs\nfunction readBlobData(body, type, asBlob, callback) {\n if (asBlob) {\n if (!body) {\n callback(createBlob([''], {type: type}));\n } else if (typeof body !== 'string') { // we have blob support\n callback(body);\n } else { // no blob support\n callback(b64ToBluffer(body, type));\n }\n } else { // as base64 string\n if (!body) {\n callback('');\n } else if (typeof body !== 'string') { // we have blob support\n readAsBinaryString(body, function (binary) {\n callback(thisBtoa(binary));\n });\n } else { // no blob support\n callback(body);\n }\n }\n}\n\nfunction fetchAttachmentsIfNecessary(doc, opts, txn, cb) {\n var attachments = Object.keys(doc._attachments || {});\n if (!attachments.length) {\n return cb && cb();\n }\n var numDone = 0;\n\n function checkDone() {\n if (++numDone === attachments.length && cb) {\n cb();\n }\n }\n\n function fetchAttachment(doc, att) {\n var attObj = doc._attachments[att];\n var digest = attObj.digest;\n var req = txn.objectStore(ATTACH_STORE).get(digest);\n req.onsuccess = function (e) {\n attObj.body = e.target.result.body;\n checkDone();\n };\n }\n\n attachments.forEach(function (att) {\n if (opts.attachments && opts.include_docs) {\n fetchAttachment(doc, att);\n } else {\n doc._attachments[att].stub = true;\n checkDone();\n }\n });\n}\n\n// IDB-specific postprocessing necessary because\n// we don't know whether we stored a true Blob or\n// a base64-encoded string, and if it's a Blob it\n// needs to be read outside of the transaction context\nfunction postProcessAttachments(results, asBlob) {\n return Promise.all(results.map(function (row) {\n if (row.doc && row.doc._attachments) {\n var attNames = Object.keys(row.doc._attachments);\n return Promise.all(attNames.map(function (att) {\n var attObj = row.doc._attachments[att];\n if (!('body' in attObj)) { // already processed\n return;\n }\n var body = attObj.body;\n var type = attObj.content_type;\n return new Promise(function (resolve) {\n readBlobData(body, type, asBlob, function (data) {\n row.doc._attachments[att] = $inject_Object_assign(\n pick(attObj, ['digest', 'content_type']),\n {data: data}\n );\n resolve();\n });\n });\n }));\n }\n }));\n}\n\nfunction compactRevs(revs, docId, txn) {\n\n var possiblyOrphanedDigests = [];\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n var attStore = txn.objectStore(ATTACH_STORE);\n var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);\n var count = revs.length;\n\n function checkDone() {\n count--;\n if (!count) { // done processing all revs\n deleteOrphanedAttachments();\n }\n }\n\n function deleteOrphanedAttachments() {\n if (!possiblyOrphanedDigests.length) {\n return;\n }\n possiblyOrphanedDigests.forEach(function (digest) {\n var countReq = attAndSeqStore.index('digestSeq').count(\n IDBKeyRange.bound(\n digest + '::', digest + '::\\uffff', false, false));\n countReq.onsuccess = function (e) {\n var count = e.target.result;\n if (!count) {\n // orphaned\n attStore.delete(digest);\n }\n };\n });\n }\n\n revs.forEach(function (rev) {\n var index = seqStore.index('_doc_id_rev');\n var key = docId + \"::\" + rev;\n index.getKey(key).onsuccess = function (e) {\n var seq = e.target.result;\n if (typeof seq !== 'number') {\n return checkDone();\n }\n seqStore.delete(seq);\n\n var cursor = attAndSeqStore.index('seq')\n .openCursor(IDBKeyRange.only(seq));\n\n cursor.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n var digest = cursor.value.digestSeq.split('::')[0];\n possiblyOrphanedDigests.push(digest);\n attAndSeqStore.delete(cursor.primaryKey);\n cursor.continue();\n } else { // done\n checkDone();\n }\n };\n };\n });\n}\n\nfunction openTransactionSafely(idb, stores, mode) {\n try {\n return {\n txn: idb.transaction(stores, mode)\n };\n } catch (err) {\n return {\n error: err\n };\n }\n}\n\nvar changesHandler = new Changes();\n\nfunction idbBulkDocs(dbOpts, req, opts, api, idb, callback) {\n var docInfos = req.docs;\n var txn;\n var docStore;\n var bySeqStore;\n var attachStore;\n var attachAndSeqStore;\n var metaStore;\n var docInfoError;\n var metaDoc;\n\n for (var i = 0, len = docInfos.length; i < len; i++) {\n var doc = docInfos[i];\n if (doc._id && isLocalId(doc._id)) {\n continue;\n }\n doc = docInfos[i] = parseDoc(doc, opts.new_edits, dbOpts);\n if (doc.error && !docInfoError) {\n docInfoError = doc;\n }\n }\n\n if (docInfoError) {\n return callback(docInfoError);\n }\n\n var allDocsProcessed = false;\n var docCountDelta = 0;\n var results = new Array(docInfos.length);\n var fetchedDocs = new ExportedMap();\n var preconditionErrored = false;\n var blobType = api._meta.blobSupport ? 'blob' : 'base64';\n\n preprocessAttachments(docInfos, blobType, function (err) {\n if (err) {\n return callback(err);\n }\n startTransaction();\n });\n\n function startTransaction() {\n\n var stores = [\n DOC_STORE, BY_SEQ_STORE,\n ATTACH_STORE,\n LOCAL_STORE, ATTACH_AND_SEQ_STORE,\n META_STORE\n ];\n var txnResult = openTransactionSafely(idb, stores, 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n txn = txnResult.txn;\n txn.onabort = idbError(callback);\n txn.ontimeout = idbError(callback);\n txn.oncomplete = complete;\n docStore = txn.objectStore(DOC_STORE);\n bySeqStore = txn.objectStore(BY_SEQ_STORE);\n attachStore = txn.objectStore(ATTACH_STORE);\n attachAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);\n metaStore = txn.objectStore(META_STORE);\n\n metaStore.get(META_STORE).onsuccess = function (e) {\n metaDoc = e.target.result;\n updateDocCountIfReady();\n };\n\n verifyAttachments(function (err) {\n if (err) {\n preconditionErrored = true;\n return callback(err);\n }\n fetchExistingDocs();\n });\n }\n\n function onAllDocsProcessed() {\n allDocsProcessed = true;\n updateDocCountIfReady();\n }\n\n function idbProcessDocs() {\n processDocs(dbOpts.revs_limit, docInfos, api, fetchedDocs,\n txn, results, writeDoc, opts, onAllDocsProcessed);\n }\n\n function updateDocCountIfReady() {\n if (!metaDoc || !allDocsProcessed) {\n return;\n }\n // caching the docCount saves a lot of time in allDocs() and\n // info(), which is why we go to all the trouble of doing this\n metaDoc.docCount += docCountDelta;\n metaStore.put(metaDoc);\n }\n\n function fetchExistingDocs() {\n\n if (!docInfos.length) {\n return;\n }\n\n var numFetched = 0;\n\n function checkDone() {\n if (++numFetched === docInfos.length) {\n idbProcessDocs();\n }\n }\n\n function readMetadata(event) {\n var metadata = decodeMetadata(event.target.result);\n\n if (metadata) {\n fetchedDocs.set(metadata.id, metadata);\n }\n checkDone();\n }\n\n for (var i = 0, len = docInfos.length; i < len; i++) {\n var docInfo = docInfos[i];\n if (docInfo._id && isLocalId(docInfo._id)) {\n checkDone(); // skip local docs\n continue;\n }\n var req = docStore.get(docInfo.metadata.id);\n req.onsuccess = readMetadata;\n }\n }\n\n function complete() {\n if (preconditionErrored) {\n return;\n }\n\n changesHandler.notify(api._meta.name);\n callback(null, results);\n }\n\n function verifyAttachment(digest, callback) {\n\n var req = attachStore.get(digest);\n req.onsuccess = function (e) {\n if (!e.target.result) {\n var err = createError(MISSING_STUB,\n 'unknown stub attachment with digest ' +\n digest);\n err.status = 412;\n callback(err);\n } else {\n callback();\n }\n };\n }\n\n function verifyAttachments(finish) {\n\n\n var digests = [];\n docInfos.forEach(function (docInfo) {\n if (docInfo.data && docInfo.data._attachments) {\n Object.keys(docInfo.data._attachments).forEach(function (filename) {\n var att = docInfo.data._attachments[filename];\n if (att.stub) {\n digests.push(att.digest);\n }\n });\n }\n });\n if (!digests.length) {\n return finish();\n }\n var numDone = 0;\n var err;\n\n function checkDone() {\n if (++numDone === digests.length) {\n finish(err);\n }\n }\n digests.forEach(function (digest) {\n verifyAttachment(digest, function (attErr) {\n if (attErr && !err) {\n err = attErr;\n }\n checkDone();\n });\n });\n }\n\n function writeDoc(docInfo, winningRev$$1, winningRevIsDeleted, newRevIsDeleted,\n isUpdate, delta, resultsIdx, callback) {\n\n docInfo.metadata.winningRev = winningRev$$1;\n docInfo.metadata.deleted = winningRevIsDeleted;\n\n var doc = docInfo.data;\n doc._id = docInfo.metadata.id;\n doc._rev = docInfo.metadata.rev;\n\n if (newRevIsDeleted) {\n doc._deleted = true;\n }\n\n var hasAttachments = doc._attachments &&\n Object.keys(doc._attachments).length;\n if (hasAttachments) {\n return writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback);\n }\n\n docCountDelta += delta;\n updateDocCountIfReady();\n\n finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback);\n }\n\n function finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback) {\n\n var doc = docInfo.data;\n var metadata = docInfo.metadata;\n\n doc._doc_id_rev = metadata.id + '::' + metadata.rev;\n delete doc._id;\n delete doc._rev;\n\n function afterPutDoc(e) {\n var revsToDelete = docInfo.stemmedRevs || [];\n\n if (isUpdate && api.auto_compaction) {\n revsToDelete = revsToDelete.concat(compactTree(docInfo.metadata));\n }\n\n if (revsToDelete && revsToDelete.length) {\n compactRevs(revsToDelete, docInfo.metadata.id, txn);\n }\n\n metadata.seq = e.target.result;\n // Current _rev is calculated from _rev_tree on read\n // delete metadata.rev;\n var metadataToStore = encodeMetadata(metadata, winningRev$$1,\n winningRevIsDeleted);\n var metaDataReq = docStore.put(metadataToStore);\n metaDataReq.onsuccess = afterPutMetadata;\n }\n\n function afterPutDocError(e) {\n // ConstraintError, need to update, not put (see #1638 for details)\n e.preventDefault(); // avoid transaction abort\n e.stopPropagation(); // avoid transaction onerror\n var index = bySeqStore.index('_doc_id_rev');\n var getKeyReq = index.getKey(doc._doc_id_rev);\n getKeyReq.onsuccess = function (e) {\n var putReq = bySeqStore.put(doc, e.target.result);\n putReq.onsuccess = afterPutDoc;\n };\n }\n\n function afterPutMetadata() {\n results[resultsIdx] = {\n ok: true,\n id: metadata.id,\n rev: metadata.rev\n };\n fetchedDocs.set(docInfo.metadata.id, docInfo.metadata);\n insertAttachmentMappings(docInfo, metadata.seq, callback);\n }\n\n var putReq = bySeqStore.put(doc);\n\n putReq.onsuccess = afterPutDoc;\n putReq.onerror = afterPutDocError;\n }\n\n function writeAttachments(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback) {\n\n\n var doc = docInfo.data;\n\n var numDone = 0;\n var attachments = Object.keys(doc._attachments);\n\n function collectResults() {\n if (numDone === attachments.length) {\n finishDoc(docInfo, winningRev$$1, winningRevIsDeleted,\n isUpdate, resultsIdx, callback);\n }\n }\n\n function attachmentSaved() {\n numDone++;\n collectResults();\n }\n\n attachments.forEach(function (key) {\n var att = docInfo.data._attachments[key];\n if (!att.stub) {\n var data = att.data;\n delete att.data;\n att.revpos = parseInt(winningRev$$1, 10);\n var digest = att.digest;\n saveAttachment(digest, data, attachmentSaved);\n } else {\n numDone++;\n collectResults();\n }\n });\n }\n\n // map seqs to attachment digests, which\n // we will need later during compaction\n function insertAttachmentMappings(docInfo, seq, callback) {\n\n var attsAdded = 0;\n var attsToAdd = Object.keys(docInfo.data._attachments || {});\n\n if (!attsToAdd.length) {\n return callback();\n }\n\n function checkDone() {\n if (++attsAdded === attsToAdd.length) {\n callback();\n }\n }\n\n function add(att) {\n var digest = docInfo.data._attachments[att].digest;\n var req = attachAndSeqStore.put({\n seq: seq,\n digestSeq: digest + '::' + seq\n });\n\n req.onsuccess = checkDone;\n req.onerror = function (e) {\n // this callback is for a constaint error, which we ignore\n // because this docid/rev has already been associated with\n // the digest (e.g. when new_edits == false)\n e.preventDefault(); // avoid transaction abort\n e.stopPropagation(); // avoid transaction onerror\n checkDone();\n };\n }\n for (var i = 0; i < attsToAdd.length; i++) {\n add(attsToAdd[i]); // do in parallel\n }\n }\n\n function saveAttachment(digest, data, callback) {\n\n\n var getKeyReq = attachStore.count(digest);\n getKeyReq.onsuccess = function (e) {\n var count = e.target.result;\n if (count) {\n return callback(); // already exists\n }\n var newAtt = {\n digest: digest,\n body: data\n };\n var putReq = attachStore.put(newAtt);\n putReq.onsuccess = callback;\n };\n }\n}\n\n// Abstraction over IDBCursor and getAll()/getAllKeys() that allows us to batch our operations\n// while falling back to a normal IDBCursor operation on browsers that don't support getAll() or\n// getAllKeys(). This allows for a much faster implementation than just straight-up cursors, because\n// we're not processing each document one-at-a-time.\nfunction runBatchedCursor(objectStore, keyRange, descending, batchSize, onBatch) {\n\n if (batchSize === -1) {\n batchSize = 1000;\n }\n\n // Bail out of getAll()/getAllKeys() in the following cases:\n // 1) either method is unsupported - we need both\n // 2) batchSize is 1 (might as well use IDBCursor)\n // 3) descending – no real way to do this via getAll()/getAllKeys()\n\n var useGetAll = typeof objectStore.getAll === 'function' &&\n typeof objectStore.getAllKeys === 'function' &&\n batchSize > 1 && !descending;\n\n var keysBatch;\n var valuesBatch;\n var pseudoCursor;\n\n function onGetAll(e) {\n valuesBatch = e.target.result;\n if (keysBatch) {\n onBatch(keysBatch, valuesBatch, pseudoCursor);\n }\n }\n\n function onGetAllKeys(e) {\n keysBatch = e.target.result;\n if (valuesBatch) {\n onBatch(keysBatch, valuesBatch, pseudoCursor);\n }\n }\n\n function continuePseudoCursor() {\n if (!keysBatch.length) { // no more results\n return onBatch();\n }\n // fetch next batch, exclusive start\n var lastKey = keysBatch[keysBatch.length - 1];\n var newKeyRange;\n if (keyRange && keyRange.upper) {\n try {\n newKeyRange = IDBKeyRange.bound(lastKey, keyRange.upper,\n true, keyRange.upperOpen);\n } catch (e) {\n if (e.name === \"DataError\" && e.code === 0) {\n return onBatch(); // we're done, startkey and endkey are equal\n }\n }\n } else {\n newKeyRange = IDBKeyRange.lowerBound(lastKey, true);\n }\n keyRange = newKeyRange;\n keysBatch = null;\n valuesBatch = null;\n objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;\n objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;\n }\n\n function onCursor(e) {\n var cursor = e.target.result;\n if (!cursor) { // done\n return onBatch();\n }\n // regular IDBCursor acts like a batch where batch size is always 1\n onBatch([cursor.key], [cursor.value], cursor);\n }\n\n if (useGetAll) {\n pseudoCursor = {\"continue\": continuePseudoCursor};\n objectStore.getAll(keyRange, batchSize).onsuccess = onGetAll;\n objectStore.getAllKeys(keyRange, batchSize).onsuccess = onGetAllKeys;\n } else if (descending) {\n objectStore.openCursor(keyRange, 'prev').onsuccess = onCursor;\n } else {\n objectStore.openCursor(keyRange).onsuccess = onCursor;\n }\n}\n\n// simple shim for objectStore.getAll(), falling back to IDBCursor\nfunction getAll(objectStore, keyRange, onSuccess) {\n if (typeof objectStore.getAll === 'function') {\n // use native getAll\n objectStore.getAll(keyRange).onsuccess = onSuccess;\n return;\n }\n // fall back to cursors\n var values = [];\n\n function onCursor(e) {\n var cursor = e.target.result;\n if (cursor) {\n values.push(cursor.value);\n cursor.continue();\n } else {\n onSuccess({\n target: {\n result: values\n }\n });\n }\n }\n\n objectStore.openCursor(keyRange).onsuccess = onCursor;\n}\n\nfunction allDocsKeys(keys, docStore, onBatch) {\n // It's not guaranted to be returned in right order \n var valuesBatch = new Array(keys.length);\n var count = 0;\n keys.forEach(function (key, index) {\n docStore.get(key).onsuccess = function (event) {\n if (event.target.result) {\n valuesBatch[index] = event.target.result;\n } else {\n valuesBatch[index] = {key: key, error: 'not_found'};\n }\n count++;\n if (count === keys.length) {\n onBatch(keys, valuesBatch, {});\n }\n };\n });\n}\n\nfunction createKeyRange(start, end, inclusiveEnd, key, descending) {\n try {\n if (start && end) {\n if (descending) {\n return IDBKeyRange.bound(end, start, !inclusiveEnd, false);\n } else {\n return IDBKeyRange.bound(start, end, false, !inclusiveEnd);\n }\n } else if (start) {\n if (descending) {\n return IDBKeyRange.upperBound(start);\n } else {\n return IDBKeyRange.lowerBound(start);\n }\n } else if (end) {\n if (descending) {\n return IDBKeyRange.lowerBound(end, !inclusiveEnd);\n } else {\n return IDBKeyRange.upperBound(end, !inclusiveEnd);\n }\n } else if (key) {\n return IDBKeyRange.only(key);\n }\n } catch (e) {\n return {error: e};\n }\n return null;\n}\n\nfunction idbAllDocs(opts, idb, callback) {\n var start = 'startkey' in opts ? opts.startkey : false;\n var end = 'endkey' in opts ? opts.endkey : false;\n var key = 'key' in opts ? opts.key : false;\n var keys = 'keys' in opts ? opts.keys : false; \n var skip = opts.skip || 0;\n var limit = typeof opts.limit === 'number' ? opts.limit : -1;\n var inclusiveEnd = opts.inclusive_end !== false;\n\n var keyRange ; \n var keyRangeError;\n if (!keys) {\n keyRange = createKeyRange(start, end, inclusiveEnd, key, opts.descending);\n keyRangeError = keyRange && keyRange.error;\n if (keyRangeError && \n !(keyRangeError.name === \"DataError\" && keyRangeError.code === 0)) {\n // DataError with error code 0 indicates start is less than end, so\n // can just do an empty query. Else need to throw\n return callback(createError(IDB_ERROR,\n keyRangeError.name, keyRangeError.message));\n }\n }\n\n var stores = [DOC_STORE, BY_SEQ_STORE, META_STORE];\n\n if (opts.attachments) {\n stores.push(ATTACH_STORE);\n }\n var txnResult = openTransactionSafely(idb, stores, 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n txn.oncomplete = onTxnComplete;\n txn.onabort = idbError(callback);\n var docStore = txn.objectStore(DOC_STORE);\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n var metaStore = txn.objectStore(META_STORE);\n var docIdRevIndex = seqStore.index('_doc_id_rev');\n var results = [];\n var docCount;\n var updateSeq;\n\n metaStore.get(META_STORE).onsuccess = function (e) {\n docCount = e.target.result.docCount;\n };\n\n /* istanbul ignore if */\n if (opts.update_seq) {\n getMaxUpdateSeq(seqStore, function (e) { \n if (e.target.result && e.target.result.length > 0) {\n updateSeq = e.target.result[0];\n }\n });\n }\n\n function getMaxUpdateSeq(objectStore, onSuccess) {\n function onCursor(e) {\n var cursor = e.target.result;\n var maxKey = undefined;\n if (cursor && cursor.key) {\n maxKey = cursor.key;\n } \n return onSuccess({\n target: {\n result: [maxKey]\n }\n });\n }\n objectStore.openCursor(null, 'prev').onsuccess = onCursor;\n }\n\n // if the user specifies include_docs=true, then we don't\n // want to block the main cursor while we're fetching the doc\n function fetchDocAsynchronously(metadata, row, winningRev$$1) {\n var key = metadata.id + \"::\" + winningRev$$1;\n docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {\n row.doc = decodeDoc(e.target.result) || {};\n if (opts.conflicts) {\n var conflicts = collectConflicts(metadata);\n if (conflicts.length) {\n row.doc._conflicts = conflicts;\n }\n }\n fetchAttachmentsIfNecessary(row.doc, opts, txn);\n };\n }\n\n function allDocsInner(winningRev$$1, metadata) {\n var row = {\n id: metadata.id,\n key: metadata.id,\n value: {\n rev: winningRev$$1\n }\n };\n var deleted = metadata.deleted;\n if (deleted) {\n if (keys) {\n results.push(row);\n // deleted docs are okay with \"keys\" requests\n row.value.deleted = true;\n row.doc = null;\n }\n } else if (skip-- <= 0) {\n results.push(row);\n if (opts.include_docs) {\n fetchDocAsynchronously(metadata, row, winningRev$$1);\n }\n }\n }\n\n function processBatch(batchValues) {\n for (var i = 0, len = batchValues.length; i < len; i++) {\n if (results.length === limit) {\n break;\n }\n var batchValue = batchValues[i];\n if (batchValue.error && keys) {\n // key was not found with \"keys\" requests\n results.push(batchValue);\n continue;\n }\n var metadata = decodeMetadata(batchValue);\n var winningRev$$1 = metadata.winningRev;\n allDocsInner(winningRev$$1, metadata);\n }\n }\n\n function onBatch(batchKeys, batchValues, cursor) {\n if (!cursor) {\n return;\n }\n processBatch(batchValues);\n if (results.length < limit) {\n cursor.continue();\n }\n }\n\n function onGetAll(e) {\n var values = e.target.result;\n if (opts.descending) {\n values = values.reverse();\n }\n processBatch(values);\n }\n\n function onResultsReady() {\n var returnVal = {\n total_rows: docCount,\n offset: opts.skip,\n rows: results\n };\n \n /* istanbul ignore if */\n if (opts.update_seq && updateSeq !== undefined) {\n returnVal.update_seq = updateSeq;\n }\n callback(null, returnVal);\n }\n\n function onTxnComplete() {\n if (opts.attachments) {\n postProcessAttachments(results, opts.binary).then(onResultsReady);\n } else {\n onResultsReady();\n }\n }\n\n // don't bother doing any requests if start > end or limit === 0\n if (keyRangeError || limit === 0) {\n return;\n }\n if (keys) {\n return allDocsKeys(opts.keys, docStore, onBatch);\n }\n if (limit === -1) { // just fetch everything\n return getAll(docStore, keyRange, onGetAll);\n }\n // else do a cursor\n // choose a batch size based on the skip, since we'll need to skip that many\n runBatchedCursor(docStore, keyRange, opts.descending, limit + skip, onBatch);\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\nfunction checkBlobSupport(txn) {\n return new Promise(function (resolve) {\n var blob$$1 = createBlob(['']);\n var req = txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob$$1, 'key');\n\n req.onsuccess = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome ||\n parseInt(matchedChrome[1], 10) >= 43);\n };\n\n req.onerror = txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n }).catch(function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction countDocs(txn, cb) {\n var index = txn.objectStore(DOC_STORE).index('deletedOrLocal');\n index.count(IDBKeyRange.only('0')).onsuccess = function (e) {\n cb(e.target.result);\n };\n}\n\n// This task queue ensures that IDB open calls are done in their own tick\n\nvar running = false;\nvar queue = [];\n\nfunction tryCode(fun, err, res, PouchDB) {\n try {\n fun(err, res);\n } catch (err) {\n // Shouldn't happen, but in some odd cases\n // IndexedDB implementations might throw a sync\n // error, in which case this will at least log it.\n PouchDB.emit('error', err);\n }\n}\n\nfunction applyNext() {\n if (running || !queue.length) {\n return;\n }\n running = true;\n queue.shift()();\n}\n\nfunction enqueueTask(action, callback, PouchDB) {\n queue.push(function runAction() {\n action(function runCallback(err, res) {\n tryCode(callback, err, res, PouchDB);\n running = false;\n nextTick(function runNext() {\n applyNext(PouchDB);\n });\n });\n });\n applyNext();\n}\n\nfunction changes(opts, api, dbName, idb) {\n opts = clone(opts);\n\n if (opts.continuous) {\n var id = dbName + ':' + uuid();\n changesHandler.addListener(dbName, id, api, opts);\n changesHandler.notify(dbName);\n return {\n cancel: function () {\n changesHandler.removeListener(dbName, id);\n }\n };\n }\n\n var docIds = opts.doc_ids && new ExportedSet(opts.doc_ids);\n\n opts.since = opts.since || 0;\n var lastSeq = opts.since;\n\n var limit = 'limit' in opts ? opts.limit : -1;\n if (limit === 0) {\n limit = 1; // per CouchDB _changes spec\n }\n\n var results = [];\n var numResults = 0;\n var filter = filterChange(opts);\n var docIdsToMetadata = new ExportedMap();\n\n var txn;\n var bySeqStore;\n var docStore;\n var docIdRevIndex;\n\n function onBatch(batchKeys, batchValues, cursor) {\n if (!cursor || !batchKeys.length) { // done\n return;\n }\n\n var winningDocs = new Array(batchKeys.length);\n var metadatas = new Array(batchKeys.length);\n\n function processMetadataAndWinningDoc(metadata, winningDoc) {\n var change = opts.processChange(winningDoc, metadata, opts);\n lastSeq = change.seq = metadata.seq;\n\n var filtered = filter(change);\n if (typeof filtered === 'object') { // anything but true/false indicates error\n return Promise.reject(filtered);\n }\n\n if (!filtered) {\n return Promise.resolve();\n }\n numResults++;\n if (opts.return_docs) {\n results.push(change);\n }\n // process the attachment immediately\n // for the benefit of live listeners\n if (opts.attachments && opts.include_docs) {\n return new Promise(function (resolve) {\n fetchAttachmentsIfNecessary(winningDoc, opts, txn, function () {\n postProcessAttachments([change], opts.binary).then(function () {\n resolve(change);\n });\n });\n });\n } else {\n return Promise.resolve(change);\n }\n }\n\n function onBatchDone() {\n var promises = [];\n for (var i = 0, len = winningDocs.length; i < len; i++) {\n if (numResults === limit) {\n break;\n }\n var winningDoc = winningDocs[i];\n if (!winningDoc) {\n continue;\n }\n var metadata = metadatas[i];\n promises.push(processMetadataAndWinningDoc(metadata, winningDoc));\n }\n\n Promise.all(promises).then(function (changes) {\n for (var i = 0, len = changes.length; i < len; i++) {\n if (changes[i]) {\n opts.onChange(changes[i]);\n }\n }\n }).catch(opts.complete);\n\n if (numResults !== limit) {\n cursor.continue();\n }\n }\n\n // Fetch all metadatas/winningdocs from this batch in parallel, then process\n // them all only once all data has been collected. This is done in parallel\n // because it's faster than doing it one-at-a-time.\n var numDone = 0;\n batchValues.forEach(function (value, i) {\n var doc = decodeDoc(value);\n var seq = batchKeys[i];\n fetchWinningDocAndMetadata(doc, seq, function (metadata, winningDoc) {\n metadatas[i] = metadata;\n winningDocs[i] = winningDoc;\n if (++numDone === batchKeys.length) {\n onBatchDone();\n }\n });\n });\n }\n\n function onGetMetadata(doc, seq, metadata, cb) {\n if (metadata.seq !== seq) {\n // some other seq is later\n return cb();\n }\n\n if (metadata.winningRev === doc._rev) {\n // this is the winning doc\n return cb(metadata, doc);\n }\n\n // fetch winning doc in separate request\n var docIdRev = doc._id + '::' + metadata.winningRev;\n var req = docIdRevIndex.get(docIdRev);\n req.onsuccess = function (e) {\n cb(metadata, decodeDoc(e.target.result));\n };\n }\n\n function fetchWinningDocAndMetadata(doc, seq, cb) {\n if (docIds && !docIds.has(doc._id)) {\n return cb();\n }\n\n var metadata = docIdsToMetadata.get(doc._id);\n if (metadata) { // cached\n return onGetMetadata(doc, seq, metadata, cb);\n }\n // metadata not cached, have to go fetch it\n docStore.get(doc._id).onsuccess = function (e) {\n metadata = decodeMetadata(e.target.result);\n docIdsToMetadata.set(doc._id, metadata);\n onGetMetadata(doc, seq, metadata, cb);\n };\n }\n\n function finish() {\n opts.complete(null, {\n results: results,\n last_seq: lastSeq\n });\n }\n\n function onTxnComplete() {\n if (!opts.continuous && opts.attachments) {\n // cannot guarantee that postProcessing was already done,\n // so do it again\n postProcessAttachments(results).then(finish);\n } else {\n finish();\n }\n }\n\n var objectStores = [DOC_STORE, BY_SEQ_STORE];\n if (opts.attachments) {\n objectStores.push(ATTACH_STORE);\n }\n var txnResult = openTransactionSafely(idb, objectStores, 'readonly');\n if (txnResult.error) {\n return opts.complete(txnResult.error);\n }\n txn = txnResult.txn;\n txn.onabort = idbError(opts.complete);\n txn.oncomplete = onTxnComplete;\n\n bySeqStore = txn.objectStore(BY_SEQ_STORE);\n docStore = txn.objectStore(DOC_STORE);\n docIdRevIndex = bySeqStore.index('_doc_id_rev');\n\n var keyRange = (opts.since && !opts.descending) ?\n IDBKeyRange.lowerBound(opts.since, true) : null;\n\n runBatchedCursor(bySeqStore, keyRange, opts.descending, limit, onBatch);\n}\n\nvar cachedDBs = new ExportedMap();\nvar blobSupportPromise;\nvar openReqList = new ExportedMap();\n\nfunction IdbPouch(opts, callback) {\n var api = this;\n\n enqueueTask(function (thisCallback) {\n init(api, opts, thisCallback);\n }, callback, api.constructor);\n}\n\nfunction init(api, opts, callback) {\n\n var dbName = opts.name;\n\n var idb = null;\n api._meta = null;\n\n // called when creating a fresh new database\n function createSchema(db) {\n var docStore = db.createObjectStore(DOC_STORE, {keyPath : 'id'});\n db.createObjectStore(BY_SEQ_STORE, {autoIncrement: true})\n .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});\n db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'});\n db.createObjectStore(META_STORE, {keyPath: 'id', autoIncrement: false});\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n\n // added in v2\n docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});\n\n // added in v3\n db.createObjectStore(LOCAL_STORE, {keyPath: '_id'});\n\n // added in v4\n var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,\n {autoIncrement: true});\n attAndSeqStore.createIndex('seq', 'seq');\n attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});\n }\n\n // migration to version 2\n // unfortunately \"deletedOrLocal\" is a misnomer now that we no longer\n // store local docs in the main doc-store, but whaddyagonnado\n function addDeletedOrLocalIndex(txn, callback) {\n var docStore = txn.objectStore(DOC_STORE);\n docStore.createIndex('deletedOrLocal', 'deletedOrLocal', {unique : false});\n\n docStore.openCursor().onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n var metadata = cursor.value;\n var deleted = isDeleted(metadata);\n metadata.deletedOrLocal = deleted ? \"1\" : \"0\";\n docStore.put(metadata);\n cursor.continue();\n } else {\n callback();\n }\n };\n }\n\n // migration to version 3 (part 1)\n function createLocalStoreSchema(db) {\n db.createObjectStore(LOCAL_STORE, {keyPath: '_id'})\n .createIndex('_doc_id_rev', '_doc_id_rev', {unique: true});\n }\n\n // migration to version 3 (part 2)\n function migrateLocalStore(txn, cb) {\n var localStore = txn.objectStore(LOCAL_STORE);\n var docStore = txn.objectStore(DOC_STORE);\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n\n var cursor = docStore.openCursor();\n cursor.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n var metadata = cursor.value;\n var docId = metadata.id;\n var local = isLocalId(docId);\n var rev = winningRev(metadata);\n if (local) {\n var docIdRev = docId + \"::\" + rev;\n // remove all seq entries\n // associated with this docId\n var start = docId + \"::\";\n var end = docId + \"::~\";\n var index = seqStore.index('_doc_id_rev');\n var range = IDBKeyRange.bound(start, end, false, false);\n var seqCursor = index.openCursor(range);\n seqCursor.onsuccess = function (e) {\n seqCursor = e.target.result;\n if (!seqCursor) {\n // done\n docStore.delete(cursor.primaryKey);\n cursor.continue();\n } else {\n var data = seqCursor.value;\n if (data._doc_id_rev === docIdRev) {\n localStore.put(data);\n }\n seqStore.delete(seqCursor.primaryKey);\n seqCursor.continue();\n }\n };\n } else {\n cursor.continue();\n }\n } else if (cb) {\n cb();\n }\n };\n }\n\n // migration to version 4 (part 1)\n function addAttachAndSeqStore(db) {\n var attAndSeqStore = db.createObjectStore(ATTACH_AND_SEQ_STORE,\n {autoIncrement: true});\n attAndSeqStore.createIndex('seq', 'seq');\n attAndSeqStore.createIndex('digestSeq', 'digestSeq', {unique: true});\n }\n\n // migration to version 4 (part 2)\n function migrateAttsAndSeqs(txn, callback) {\n var seqStore = txn.objectStore(BY_SEQ_STORE);\n var attStore = txn.objectStore(ATTACH_STORE);\n var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);\n\n // need to actually populate the table. this is the expensive part,\n // so as an optimization, check first that this database even\n // contains attachments\n var req = attStore.count();\n req.onsuccess = function (e) {\n var count = e.target.result;\n if (!count) {\n return callback(); // done\n }\n\n seqStore.openCursor().onsuccess = function (e) {\n var cursor = e.target.result;\n if (!cursor) {\n return callback(); // done\n }\n var doc = cursor.value;\n var seq = cursor.primaryKey;\n var atts = Object.keys(doc._attachments || {});\n var digestMap = {};\n for (var j = 0; j < atts.length; j++) {\n var att = doc._attachments[atts[j]];\n digestMap[att.digest] = true; // uniq digests, just in case\n }\n var digests = Object.keys(digestMap);\n for (j = 0; j < digests.length; j++) {\n var digest = digests[j];\n attAndSeqStore.put({\n seq: seq,\n digestSeq: digest + '::' + seq\n });\n }\n cursor.continue();\n };\n };\n }\n\n // migration to version 5\n // Instead of relying on on-the-fly migration of metadata,\n // this brings the doc-store to its modern form:\n // - metadata.winningrev\n // - metadata.seq\n // - stringify the metadata when storing it\n function migrateMetadata(txn) {\n\n function decodeMetadataCompat(storedObject) {\n if (!storedObject.data) {\n // old format, when we didn't store it stringified\n storedObject.deleted = storedObject.deletedOrLocal === '1';\n return storedObject;\n }\n return decodeMetadata(storedObject);\n }\n\n // ensure that every metadata has a winningRev and seq,\n // which was previously created on-the-fly but better to migrate\n var bySeqStore = txn.objectStore(BY_SEQ_STORE);\n var docStore = txn.objectStore(DOC_STORE);\n var cursor = docStore.openCursor();\n cursor.onsuccess = function (e) {\n var cursor = e.target.result;\n if (!cursor) {\n return; // done\n }\n var metadata = decodeMetadataCompat(cursor.value);\n\n metadata.winningRev = metadata.winningRev ||\n winningRev(metadata);\n\n function fetchMetadataSeq() {\n // metadata.seq was added post-3.2.0, so if it's missing,\n // we need to fetch it manually\n var start = metadata.id + '::';\n var end = metadata.id + '::\\uffff';\n var req = bySeqStore.index('_doc_id_rev').openCursor(\n IDBKeyRange.bound(start, end));\n\n var metadataSeq = 0;\n req.onsuccess = function (e) {\n var cursor = e.target.result;\n if (!cursor) {\n metadata.seq = metadataSeq;\n return onGetMetadataSeq();\n }\n var seq = cursor.primaryKey;\n if (seq > metadataSeq) {\n metadataSeq = seq;\n }\n cursor.continue();\n };\n }\n\n function onGetMetadataSeq() {\n var metadataToStore = encodeMetadata(metadata,\n metadata.winningRev, metadata.deleted);\n\n var req = docStore.put(metadataToStore);\n req.onsuccess = function () {\n cursor.continue();\n };\n }\n\n if (metadata.seq) {\n return onGetMetadataSeq();\n }\n\n fetchMetadataSeq();\n };\n\n }\n\n api._remote = false;\n api.type = function () {\n return 'idb';\n };\n\n api._id = toPromise(function (callback) {\n callback(null, api._meta.instanceId);\n });\n\n api._bulkDocs = function idb_bulkDocs(req, reqOpts, callback) {\n idbBulkDocs(opts, req, reqOpts, api, idb, callback);\n };\n\n // First we look up the metadata in the ids database, then we fetch the\n // current revision(s) from the by sequence store\n api._get = function idb_get(id, opts, callback) {\n var doc;\n var metadata;\n var err;\n var txn = opts.ctx;\n if (!txn) {\n var txnResult = openTransactionSafely(idb,\n [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n txn = txnResult.txn;\n }\n\n function finish() {\n callback(err, {doc: doc, metadata: metadata, ctx: txn});\n }\n\n txn.objectStore(DOC_STORE).get(id).onsuccess = function (e) {\n metadata = decodeMetadata(e.target.result);\n // we can determine the result here if:\n // 1. there is no such document\n // 2. the document is deleted and we don't ask about specific rev\n // When we ask with opts.rev we expect the answer to be either\n // doc (possibly with _deleted=true) or missing error\n if (!metadata) {\n err = createError(MISSING_DOC, 'missing');\n return finish();\n }\n\n var rev;\n if (!opts.rev) {\n rev = metadata.winningRev;\n var deleted = isDeleted(metadata);\n if (deleted) {\n err = createError(MISSING_DOC, \"deleted\");\n return finish();\n }\n } else {\n rev = opts.latest ? latest(opts.rev, metadata) : opts.rev;\n }\n\n var objectStore = txn.objectStore(BY_SEQ_STORE);\n var key = metadata.id + '::' + rev;\n\n objectStore.index('_doc_id_rev').get(key).onsuccess = function (e) {\n doc = e.target.result;\n if (doc) {\n doc = decodeDoc(doc);\n }\n if (!doc) {\n err = createError(MISSING_DOC, 'missing');\n return finish();\n }\n finish();\n };\n };\n };\n\n api._getAttachment = function (docId, attachId, attachment, opts, callback) {\n var txn;\n if (opts.ctx) {\n txn = opts.ctx;\n } else {\n var txnResult = openTransactionSafely(idb,\n [DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n txn = txnResult.txn;\n }\n var digest = attachment.digest;\n var type = attachment.content_type;\n\n txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function (e) {\n var body = e.target.result.body;\n readBlobData(body, type, opts.binary, function (blobData) {\n callback(null, blobData);\n });\n };\n };\n\n api._info = function idb_info(callback) {\n var updateSeq;\n var docCount;\n\n var txnResult = openTransactionSafely(idb, [META_STORE, BY_SEQ_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {\n docCount = e.target.result.docCount;\n };\n txn.objectStore(BY_SEQ_STORE).openCursor(null, 'prev').onsuccess = function (e) {\n var cursor = e.target.result;\n updateSeq = cursor ? cursor.key : 0;\n };\n\n txn.oncomplete = function () {\n callback(null, {\n doc_count: docCount,\n update_seq: updateSeq,\n // for debugging\n idb_attachment_format: (api._meta.blobSupport ? 'binary' : 'base64')\n });\n };\n };\n\n api._allDocs = function idb_allDocs(opts, callback) {\n idbAllDocs(opts, idb, callback);\n };\n\n api._changes = function idbChanges(opts) {\n return changes(opts, api, dbName, idb);\n };\n\n api._close = function (callback) {\n // https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase#close\n // \"Returns immediately and closes the connection in a separate thread...\"\n idb.close();\n cachedDBs.delete(dbName);\n callback();\n };\n\n api._getRevisionTree = function (docId, callback) {\n var txnResult = openTransactionSafely(idb, [DOC_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n var req = txn.objectStore(DOC_STORE).get(docId);\n req.onsuccess = function (event) {\n var doc = decodeMetadata(event.target.result);\n if (!doc) {\n callback(createError(MISSING_DOC));\n } else {\n callback(null, doc.rev_tree);\n }\n };\n };\n\n // This function removes revisions of document docId\n // which are listed in revs and sets this document\n // revision to to rev_tree\n api._doCompaction = function (docId, revs, callback) {\n var stores = [\n DOC_STORE,\n BY_SEQ_STORE,\n ATTACH_STORE,\n ATTACH_AND_SEQ_STORE\n ];\n var txnResult = openTransactionSafely(idb, stores, 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var txn = txnResult.txn;\n\n var docStore = txn.objectStore(DOC_STORE);\n\n docStore.get(docId).onsuccess = function (event) {\n var metadata = decodeMetadata(event.target.result);\n traverseRevTree(metadata.rev_tree, function (isLeaf, pos,\n revHash, ctx, opts) {\n var rev = pos + '-' + revHash;\n if (revs.indexOf(rev) !== -1) {\n opts.status = 'missing';\n }\n });\n compactRevs(revs, docId, txn);\n var winningRev$$1 = metadata.winningRev;\n var deleted = metadata.deleted;\n txn.objectStore(DOC_STORE).put(\n encodeMetadata(metadata, winningRev$$1, deleted));\n };\n txn.onabort = idbError(callback);\n txn.oncomplete = function () {\n callback();\n };\n };\n\n\n api._getLocal = function (id, callback) {\n var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readonly');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n var tx = txnResult.txn;\n var req = tx.objectStore(LOCAL_STORE).get(id);\n\n req.onerror = idbError(callback);\n req.onsuccess = function (e) {\n var doc = e.target.result;\n if (!doc) {\n callback(createError(MISSING_DOC));\n } else {\n delete doc['_doc_id_rev']; // for backwards compat\n callback(null, doc);\n }\n };\n };\n\n api._putLocal = function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n delete doc._revisions; // ignore this, trust the rev\n var oldRev = doc._rev;\n var id = doc._id;\n if (!oldRev) {\n doc._rev = '0-1';\n } else {\n doc._rev = '0-' + (parseInt(oldRev.split('-')[1], 10) + 1);\n }\n\n var tx = opts.ctx;\n var ret;\n if (!tx) {\n var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n tx = txnResult.txn;\n tx.onerror = idbError(callback);\n tx.oncomplete = function () {\n if (ret) {\n callback(null, ret);\n }\n };\n }\n\n var oStore = tx.objectStore(LOCAL_STORE);\n var req;\n if (oldRev) {\n req = oStore.get(id);\n req.onsuccess = function (e) {\n var oldDoc = e.target.result;\n if (!oldDoc || oldDoc._rev !== oldRev) {\n callback(createError(REV_CONFLICT));\n } else { // update\n var req = oStore.put(doc);\n req.onsuccess = function () {\n ret = {ok: true, id: doc._id, rev: doc._rev};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n };\n }\n };\n } else { // new doc\n req = oStore.add(doc);\n req.onerror = function (e) {\n // constraint error, already exists\n callback(createError(REV_CONFLICT));\n e.preventDefault(); // avoid transaction abort\n e.stopPropagation(); // avoid transaction onerror\n };\n req.onsuccess = function () {\n ret = {ok: true, id: doc._id, rev: doc._rev};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n };\n }\n };\n\n api._removeLocal = function (doc, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var tx = opts.ctx;\n if (!tx) {\n var txnResult = openTransactionSafely(idb, [LOCAL_STORE], 'readwrite');\n if (txnResult.error) {\n return callback(txnResult.error);\n }\n tx = txnResult.txn;\n tx.oncomplete = function () {\n if (ret) {\n callback(null, ret);\n }\n };\n }\n var ret;\n var id = doc._id;\n var oStore = tx.objectStore(LOCAL_STORE);\n var req = oStore.get(id);\n\n req.onerror = idbError(callback);\n req.onsuccess = function (e) {\n var oldDoc = e.target.result;\n if (!oldDoc || oldDoc._rev !== doc._rev) {\n callback(createError(MISSING_DOC));\n } else {\n oStore.delete(id);\n ret = {ok: true, id: id, rev: '0-0'};\n if (opts.ctx) { // return immediately\n callback(null, ret);\n }\n }\n };\n };\n\n api._destroy = function (opts, callback) {\n changesHandler.removeAllListeners(dbName);\n\n //Close open request for \"dbName\" database to fix ie delay.\n var openReq = openReqList.get(dbName);\n if (openReq && openReq.result) {\n openReq.result.close();\n cachedDBs.delete(dbName);\n }\n var req = indexedDB.deleteDatabase(dbName);\n\n req.onsuccess = function () {\n //Remove open request from the list.\n openReqList.delete(dbName);\n if (hasLocalStorage() && (dbName in localStorage)) {\n delete localStorage[dbName];\n }\n callback(null, { 'ok': true });\n };\n\n req.onerror = idbError(callback);\n };\n\n var cached = cachedDBs.get(dbName);\n\n if (cached) {\n idb = cached.idb;\n api._meta = cached.global;\n return nextTick(function () {\n callback(null, api);\n });\n }\n\n var req = indexedDB.open(dbName, ADAPTER_VERSION);\n openReqList.set(dbName, req);\n\n req.onupgradeneeded = function (e) {\n var db = e.target.result;\n if (e.oldVersion < 1) {\n return createSchema(db); // new db, initial schema\n }\n // do migrations\n\n var txn = e.currentTarget.transaction;\n // these migrations have to be done in this function, before\n // control is returned to the event loop, because IndexedDB\n\n if (e.oldVersion < 3) {\n createLocalStoreSchema(db); // v2 -> v3\n }\n if (e.oldVersion < 4) {\n addAttachAndSeqStore(db); // v3 -> v4\n }\n\n var migrations = [\n addDeletedOrLocalIndex, // v1 -> v2\n migrateLocalStore, // v2 -> v3\n migrateAttsAndSeqs, // v3 -> v4\n migrateMetadata // v4 -> v5\n ];\n\n var i = e.oldVersion;\n\n function next() {\n var migration = migrations[i - 1];\n i++;\n if (migration) {\n migration(txn, next);\n }\n }\n\n next();\n };\n\n req.onsuccess = function (e) {\n\n idb = e.target.result;\n\n idb.onversionchange = function () {\n idb.close();\n cachedDBs.delete(dbName);\n };\n\n idb.onabort = function (e) {\n guardedConsole('error', 'Database has a global failure', e.target.error);\n idb.close();\n cachedDBs.delete(dbName);\n };\n\n // Do a few setup operations (in parallel as much as possible):\n // 1. Fetch meta doc\n // 2. Check blob support\n // 3. Calculate docCount\n // 4. Generate an instanceId if necessary\n // 5. Store docCount and instanceId on meta doc\n\n var txn = idb.transaction([\n META_STORE,\n DETECT_BLOB_SUPPORT_STORE,\n DOC_STORE\n ], 'readwrite');\n\n var storedMetaDoc = false;\n var metaDoc;\n var docCount;\n var blobSupport;\n var instanceId;\n\n function completeSetup() {\n if (typeof blobSupport === 'undefined' || !storedMetaDoc) {\n return;\n }\n api._meta = {\n name: dbName,\n instanceId: instanceId,\n blobSupport: blobSupport\n };\n\n cachedDBs.set(dbName, {\n idb: idb,\n global: api._meta\n });\n callback(null, api);\n }\n\n function storeMetaDocIfReady() {\n if (typeof docCount === 'undefined' || typeof metaDoc === 'undefined') {\n return;\n }\n var instanceKey = dbName + '_id';\n if (instanceKey in metaDoc) {\n instanceId = metaDoc[instanceKey];\n } else {\n metaDoc[instanceKey] = instanceId = uuid();\n }\n metaDoc.docCount = docCount;\n txn.objectStore(META_STORE).put(metaDoc);\n }\n\n //\n // fetch or generate the instanceId\n //\n txn.objectStore(META_STORE).get(META_STORE).onsuccess = function (e) {\n metaDoc = e.target.result || { id: META_STORE };\n storeMetaDocIfReady();\n };\n\n //\n // countDocs\n //\n countDocs(txn, function (count) {\n docCount = count;\n storeMetaDocIfReady();\n });\n\n //\n // check blob support\n //\n if (!blobSupportPromise) {\n // make sure blob support is only checked once\n blobSupportPromise = checkBlobSupport(txn);\n }\n\n blobSupportPromise.then(function (val) {\n blobSupport = val;\n completeSetup();\n });\n\n // only when the metadata put transaction has completed,\n // consider the setup done\n txn.oncomplete = function () {\n storedMetaDoc = true;\n completeSetup();\n };\n txn.onabort = idbError(callback);\n };\n\n req.onerror = function () {\n var msg = 'Failed to open indexedDB, are you in private browsing mode?';\n guardedConsole('error', msg);\n callback(createError(IDB_ERROR, msg));\n };\n}\n\nIdbPouch.valid = function () {\n // Following #7085 buggy idb versions (typically Safari < 10.1) are\n // considered valid.\n\n // On Firefox SecurityError is thrown while referencing indexedDB if cookies\n // are not allowed. `typeof indexedDB` also triggers the error.\n try {\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n return typeof indexedDB !== 'undefined' && typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n};\n\nfunction IDBPouch (PouchDB) {\n PouchDB.adapter('idb', IdbPouch, true);\n}\n\n// dead simple promise pool, inspired by https://github.com/timdp/es6-promise-pool\n// but much smaller in code size. limits the number of concurrent promises that are executed\n\n\nfunction pool(promiseFactories, limit) {\n return new Promise(function (resolve, reject) {\n var running = 0;\n var current = 0;\n var done = 0;\n var len = promiseFactories.length;\n var err;\n\n function runNext() {\n running++;\n promiseFactories[current++]().then(onSuccess, onError);\n }\n\n function doNext() {\n if (++done === len) {\n /* istanbul ignore if */\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n } else {\n runNextBatch();\n }\n }\n\n function onSuccess() {\n running--;\n doNext();\n }\n\n /* istanbul ignore next */\n function onError(thisErr) {\n running--;\n err = err || thisErr;\n doNext();\n }\n\n function runNextBatch() {\n while (running < limit && current < len) {\n runNext();\n }\n }\n\n runNextBatch();\n });\n}\n\nvar CHANGES_BATCH_SIZE = 25;\nvar MAX_SIMULTANEOUS_REVS = 50;\nvar CHANGES_TIMEOUT_BUFFER = 5000;\nvar DEFAULT_HEARTBEAT = 10000;\n\nvar supportsBulkGetMap = {};\n\nfunction readAttachmentsAsBlobOrBuffer(row) {\n var doc = row.doc || row.ok;\n var atts = doc._attachments;\n if (!atts) {\n return;\n }\n Object.keys(atts).forEach(function (filename) {\n var att = atts[filename];\n att.data = b64ToBluffer(att.data, att.content_type);\n });\n}\n\nfunction encodeDocId(id) {\n if (/^_design/.test(id)) {\n return '_design/' + encodeURIComponent(id.slice(8));\n }\n if (/^_local/.test(id)) {\n return '_local/' + encodeURIComponent(id.slice(7));\n }\n return encodeURIComponent(id);\n}\n\nfunction preprocessAttachments$1(doc) {\n if (!doc._attachments || !Object.keys(doc._attachments)) {\n return Promise.resolve();\n }\n\n return Promise.all(Object.keys(doc._attachments).map(function (key) {\n var attachment = doc._attachments[key];\n if (attachment.data && typeof attachment.data !== 'string') {\n return new Promise(function (resolve) {\n blobToBase64(attachment.data, resolve);\n }).then(function (b64) {\n attachment.data = b64;\n });\n }\n }));\n}\n\nfunction hasUrlPrefix(opts) {\n if (!opts.prefix) {\n return false;\n }\n var protocol = parseUri(opts.prefix).protocol;\n return protocol === 'http' || protocol === 'https';\n}\n\n// Get all the information you possibly can about the URI given by name and\n// return it as a suitable object.\nfunction getHost(name, opts) {\n // encode db name if opts.prefix is a url (#5574)\n if (hasUrlPrefix(opts)) {\n var dbName = opts.name.substr(opts.prefix.length);\n // Ensure prefix has a trailing slash\n var prefix = opts.prefix.replace(/\\/?$/, '/');\n name = prefix + encodeURIComponent(dbName);\n }\n\n var uri = parseUri(name);\n if (uri.user || uri.password) {\n uri.auth = {username: uri.user, password: uri.password};\n }\n\n // Split the path part of the URI into parts using '/' as the delimiter\n // after removing any leading '/' and any trailing '/'\n var parts = uri.path.replace(/(^\\/|\\/$)/g, '').split('/');\n\n uri.db = parts.pop();\n // Prevent double encoding of URI component\n if (uri.db.indexOf('%') === -1) {\n uri.db = encodeURIComponent(uri.db);\n }\n\n uri.path = parts.join('/');\n\n return uri;\n}\n\n// Generate a URL with the host data given by opts and the given path\nfunction genDBUrl(opts, path) {\n return genUrl(opts, opts.db + '/' + path);\n}\n\n// Generate a URL with the host data given by opts and the given path\nfunction genUrl(opts, path) {\n // If the host already has a path, then we need to have a path delimiter\n // Otherwise, the path delimiter is the empty string\n var pathDel = !opts.path ? '' : '/';\n\n // If the host already has a path, then we need to have a path delimiter\n // Otherwise, the path delimiter is the empty string\n return opts.protocol + '://' + opts.host +\n (opts.port ? (':' + opts.port) : '') +\n '/' + opts.path + pathDel + path;\n}\n\nfunction paramsToStr(params) {\n return '?' + Object.keys(params).map(function (k) {\n return k + '=' + encodeURIComponent(params[k]);\n }).join('&');\n}\n\nfunction shouldCacheBust(opts) {\n var ua = (typeof navigator !== 'undefined' && navigator.userAgent) ?\n navigator.userAgent.toLowerCase() : '';\n var isIE = ua.indexOf('msie') !== -1;\n var isTrident = ua.indexOf('trident') !== -1;\n var isEdge = ua.indexOf('edge') !== -1;\n var isGET = !('method' in opts) || opts.method === 'GET';\n return (isIE || isTrident || isEdge) && isGET;\n}\n\n// Implements the PouchDB API for dealing with CouchDB instances over HTTP\nfunction HttpPouch(opts, callback) {\n\n // The functions that will be publicly available for HttpPouch\n var api = this;\n\n var host = getHost(opts.name, opts);\n var dbUrl = genDBUrl(host, '');\n\n opts = clone(opts);\n\n var ourFetch = function (url, options) {\n\n options = options || {};\n options.headers = options.headers || new h();\n\n if (opts.auth || host.auth) {\n var nAuth = opts.auth || host.auth;\n var str = nAuth.username + ':' + nAuth.password;\n var token = thisBtoa(unescape(encodeURIComponent(str)));\n options.headers.set('Authorization', 'Basic ' + token);\n }\n\n var headers = opts.headers || {};\n Object.keys(headers).forEach(function (key) {\n options.headers.append(key, headers[key]);\n });\n\n /* istanbul ignore if */\n if (shouldCacheBust(options)) {\n url += (url.indexOf('?') === -1 ? '?' : '&') + '_nonce=' + Date.now();\n }\n\n var fetchFun = opts.fetch || f$1;\n return fetchFun(url, options);\n };\n\n function adapterFun$$1(name, fun) {\n return adapterFun(name, getArguments(function (args) {\n setup().then(function () {\n return fun.apply(this, args);\n }).catch(function (e) {\n var callback = args.pop();\n callback(e);\n });\n })).bind(api);\n }\n\n function fetchJSON(url, options, callback) {\n\n var result = {};\n\n options = options || {};\n options.headers = options.headers || new h();\n\n if (!options.headers.get('Content-Type')) {\n options.headers.set('Content-Type', 'application/json');\n }\n if (!options.headers.get('Accept')) {\n options.headers.set('Accept', 'application/json');\n }\n\n return ourFetch(url, options).then(function (response) {\n result.ok = response.ok;\n result.status = response.status;\n return response.json();\n }).then(function (json) {\n result.data = json;\n if (!result.ok) {\n result.data.status = result.status;\n var err = generateErrorFromResponse(result.data);\n if (callback) {\n return callback(err);\n } else {\n throw err;\n }\n }\n\n if (Array.isArray(result.data)) {\n result.data = result.data.map(function (v) {\n if (v.error || v.missing) {\n return generateErrorFromResponse(v);\n } else {\n return v;\n }\n });\n }\n\n if (callback) {\n callback(null, result.data);\n } else {\n return result;\n }\n });\n }\n\n var setupPromise;\n\n function setup() {\n if (opts.skip_setup) {\n return Promise.resolve();\n }\n\n // If there is a setup in process or previous successful setup\n // done then we will use that\n // If previous setups have been rejected we will try again\n if (setupPromise) {\n return setupPromise;\n }\n\n setupPromise = fetchJSON(dbUrl).catch(function (err) {\n if (err && err.status && err.status === 404) {\n // Doesnt exist, create it\n explainError(404, 'PouchDB is just detecting if the remote exists.');\n return fetchJSON(dbUrl, {method: 'PUT'});\n } else {\n return Promise.reject(err);\n }\n }).catch(function (err) {\n // If we try to create a database that already exists, skipped in\n // istanbul since its catching a race condition.\n /* istanbul ignore if */\n if (err && err.status && err.status === 412) {\n return true;\n }\n return Promise.reject(err);\n });\n\n setupPromise.catch(function () {\n setupPromise = null;\n });\n\n return setupPromise;\n }\n\n nextTick(function () {\n callback(null, api);\n });\n\n api._remote = true;\n\n /* istanbul ignore next */\n api.type = function () {\n return 'http';\n };\n\n api.id = adapterFun$$1('id', function (callback) {\n ourFetch(genUrl(host, '')).then(function (response) {\n return response.json();\n }).then(function (result) {\n var uuid$$1 = (result && result.uuid) ?\n (result.uuid + host.db) : genDBUrl(host, '');\n callback(null, uuid$$1);\n }).catch(function (err) {\n callback(err);\n });\n });\n\n // Sends a POST request to the host calling the couchdb _compact function\n // version: The version of CouchDB it is running\n api.compact = adapterFun$$1('compact', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = clone(opts);\n\n fetchJSON(genDBUrl(host, '_compact'), {method: 'POST'}).then(function () {\n function ping() {\n api.info(function (err, res) {\n // CouchDB may send a \"compact_running:true\" if it's\n // already compacting. PouchDB Server doesn't.\n /* istanbul ignore else */\n if (res && !res.compact_running) {\n callback(null, {ok: true});\n } else {\n setTimeout(ping, opts.interval || 200);\n }\n });\n }\n // Ping the http if it's finished compaction\n ping();\n });\n });\n\n api.bulkGet = adapterFun('bulkGet', function (opts, callback) {\n var self = this;\n\n function doBulkGet(cb) {\n var params = {};\n if (opts.revs) {\n params.revs = true;\n }\n if (opts.attachments) {\n /* istanbul ignore next */\n params.attachments = true;\n }\n if (opts.latest) {\n params.latest = true;\n }\n fetchJSON(genDBUrl(host, '_bulk_get' + paramsToStr(params)), {\n method: 'POST',\n body: JSON.stringify({ docs: opts.docs})\n }).then(function (result) {\n if (opts.attachments && opts.binary) {\n result.data.results.forEach(function (res) {\n res.docs.forEach(readAttachmentsAsBlobOrBuffer);\n });\n }\n cb(null, result.data);\n }).catch(cb);\n }\n\n /* istanbul ignore next */\n function doBulkGetShim() {\n // avoid \"url too long error\" by splitting up into multiple requests\n var batchSize = MAX_SIMULTANEOUS_REVS;\n var numBatches = Math.ceil(opts.docs.length / batchSize);\n var numDone = 0;\n var results = new Array(numBatches);\n\n function onResult(batchNum) {\n return function (err, res) {\n // err is impossible because shim returns a list of errs in that case\n results[batchNum] = res.results;\n if (++numDone === numBatches) {\n callback(null, {results: flatten(results)});\n }\n };\n }\n\n for (var i = 0; i < numBatches; i++) {\n var subOpts = pick(opts, ['revs', 'attachments', 'binary', 'latest']);\n subOpts.docs = opts.docs.slice(i * batchSize,\n Math.min(opts.docs.length, (i + 1) * batchSize));\n bulkGet(self, subOpts, onResult(i));\n }\n }\n\n // mark the whole database as either supporting or not supporting _bulk_get\n var dbUrl = genUrl(host, '');\n var supportsBulkGet = supportsBulkGetMap[dbUrl];\n\n /* istanbul ignore next */\n if (typeof supportsBulkGet !== 'boolean') {\n // check if this database supports _bulk_get\n doBulkGet(function (err, res) {\n if (err) {\n supportsBulkGetMap[dbUrl] = false;\n explainError(\n err.status,\n 'PouchDB is just detecting if the remote ' +\n 'supports the _bulk_get API.'\n );\n doBulkGetShim();\n } else {\n supportsBulkGetMap[dbUrl] = true;\n callback(null, res);\n }\n });\n } else if (supportsBulkGet) {\n doBulkGet(callback);\n } else {\n doBulkGetShim();\n }\n });\n\n // Calls GET on the host, which gets back a JSON string containing\n // couchdb: A welcome string\n // version: The version of CouchDB it is running\n api._info = function (callback) {\n setup().then(function () {\n return ourFetch(genDBUrl(host, ''));\n }).then(function (response) {\n return response.json();\n }).then(function (info) {\n info.host = genDBUrl(host, '');\n callback(null, info);\n }).catch(callback);\n };\n\n api.fetch = function (path, options) {\n return setup().then(function () {\n return ourFetch(genDBUrl(host, path), options);\n });\n };\n\n // Get the document with the given id from the database given by host.\n // The id could be solely the _id in the database, or it may be a\n // _design/ID or _local/ID path\n api.get = adapterFun$$1('get', function (id, opts, callback) {\n // If no options were given, set the callback to the second parameter\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = clone(opts);\n\n // List of parameters to add to the GET request\n var params = {};\n\n if (opts.revs) {\n params.revs = true;\n }\n\n if (opts.revs_info) {\n params.revs_info = true;\n }\n\n if (opts.latest) {\n params.latest = true;\n }\n\n if (opts.open_revs) {\n if (opts.open_revs !== \"all\") {\n opts.open_revs = JSON.stringify(opts.open_revs);\n }\n params.open_revs = opts.open_revs;\n }\n\n if (opts.rev) {\n params.rev = opts.rev;\n }\n\n if (opts.conflicts) {\n params.conflicts = opts.conflicts;\n }\n\n /* istanbul ignore if */\n if (opts.update_seq) {\n params.update_seq = opts.update_seq;\n }\n\n id = encodeDocId(id);\n\n function fetchAttachments(doc) {\n var atts = doc._attachments;\n var filenames = atts && Object.keys(atts);\n if (!atts || !filenames.length) {\n return;\n }\n // we fetch these manually in separate XHRs, because\n // Sync Gateway would normally send it back as multipart/mixed,\n // which we cannot parse. Also, this is more efficient than\n // receiving attachments as base64-encoded strings.\n function fetchData(filename) {\n var att = atts[filename];\n var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +\n '?rev=' + doc._rev;\n return ourFetch(genDBUrl(host, path)).then(function (response) {\n if (typeof process !== 'undefined' && !process.browser) {\n return response.buffer();\n } else {\n /* istanbul ignore next */\n return response.blob();\n }\n }).then(function (blob) {\n if (opts.binary) {\n // TODO: Can we remove this?\n if (typeof process !== 'undefined' && !process.browser) {\n blob.type = att.content_type;\n }\n return blob;\n }\n return new Promise(function (resolve) {\n blobToBase64(blob, resolve);\n });\n }).then(function (data) {\n delete att.stub;\n delete att.length;\n att.data = data;\n });\n }\n\n var promiseFactories = filenames.map(function (filename) {\n return function () {\n return fetchData(filename);\n };\n });\n\n // This limits the number of parallel xhr requests to 5 any time\n // to avoid issues with maximum browser request limits\n return pool(promiseFactories, 5);\n }\n\n function fetchAllAttachments(docOrDocs) {\n if (Array.isArray(docOrDocs)) {\n return Promise.all(docOrDocs.map(function (doc) {\n if (doc.ok) {\n return fetchAttachments(doc.ok);\n }\n }));\n }\n return fetchAttachments(docOrDocs);\n }\n\n var url = genDBUrl(host, id + paramsToStr(params));\n fetchJSON(url).then(function (res) {\n return Promise.resolve().then(function () {\n if (opts.attachments) {\n return fetchAllAttachments(res.data);\n }\n }).then(function () {\n callback(null, res.data);\n });\n }).catch(function (e) {\n e.docId = id;\n callback(e);\n });\n });\n\n\n // Delete the document given by doc from the database given by host.\n api.remove = adapterFun$$1('remove', function (docOrId, optsOrRev, opts, cb) {\n var doc;\n if (typeof optsOrRev === 'string') {\n // id, rev, opts, callback style\n doc = {\n _id: docOrId,\n _rev: optsOrRev\n };\n if (typeof opts === 'function') {\n cb = opts;\n opts = {};\n }\n } else {\n // doc, opts, callback style\n doc = docOrId;\n if (typeof optsOrRev === 'function') {\n cb = optsOrRev;\n opts = {};\n } else {\n cb = opts;\n opts = optsOrRev;\n }\n }\n\n var rev = (doc._rev || opts.rev);\n var url = genDBUrl(host, encodeDocId(doc._id)) + '?rev=' + rev;\n\n fetchJSON(url, {method: 'DELETE'}, cb).catch(cb);\n });\n\n function encodeAttachmentId(attachmentId) {\n return attachmentId.split(\"/\").map(encodeURIComponent).join(\"/\");\n }\n\n // Get the attachment\n api.getAttachment = adapterFun$$1('getAttachment', function (docId, attachmentId,\n opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n var params = opts.rev ? ('?rev=' + opts.rev) : '';\n var url = genDBUrl(host, encodeDocId(docId)) + '/' +\n encodeAttachmentId(attachmentId) + params;\n var contentType;\n ourFetch(url, {method: 'GET'}).then(function (response) {\n contentType = response.headers.get('content-type');\n if (!response.ok) {\n throw response;\n } else {\n if (typeof process !== 'undefined' && !process.browser) {\n return response.buffer();\n } else {\n /* istanbul ignore next */\n return response.blob();\n }\n }\n }).then(function (blob) {\n // TODO: also remove\n if (typeof process !== 'undefined' && !process.browser) {\n blob.type = contentType;\n }\n callback(null, blob);\n }).catch(function (err) {\n callback(err);\n });\n });\n\n // Remove the attachment given by the id and rev\n api.removeAttachment = adapterFun$$1('removeAttachment', function (docId,\n attachmentId,\n rev,\n callback) {\n var url = genDBUrl(host, encodeDocId(docId) + '/' +\n encodeAttachmentId(attachmentId)) + '?rev=' + rev;\n fetchJSON(url, {method: 'DELETE'}, callback).catch(callback);\n });\n\n // Add the attachment given by blob and its contentType property\n // to the document with the given id, the revision given by rev, and\n // add it to the database given by host.\n api.putAttachment = adapterFun$$1('putAttachment', function (docId, attachmentId,\n rev, blob,\n type, callback) {\n if (typeof type === 'function') {\n callback = type;\n type = blob;\n blob = rev;\n rev = null;\n }\n var id = encodeDocId(docId) + '/' + encodeAttachmentId(attachmentId);\n var url = genDBUrl(host, id);\n if (rev) {\n url += '?rev=' + rev;\n }\n\n if (typeof blob === 'string') {\n // input is assumed to be a base64 string\n var binary;\n try {\n binary = thisAtob(blob);\n } catch (err) {\n return callback(createError(BAD_ARG,\n 'Attachment is not a valid base64 string'));\n }\n blob = binary ? binStringToBluffer(binary, type) : '';\n }\n\n // Add the attachment\n fetchJSON(url, {\n headers: new h({'Content-Type': type}),\n method: 'PUT',\n body: blob\n }, callback).catch(callback);\n });\n\n // Update/create multiple documents given by req in the database\n // given by host.\n api._bulkDocs = function (req, opts, callback) {\n // If new_edits=false then it prevents the database from creating\n // new revision numbers for the documents. Instead it just uses\n // the old ones. This is used in database replication.\n req.new_edits = opts.new_edits;\n\n setup().then(function () {\n return Promise.all(req.docs.map(preprocessAttachments$1));\n }).then(function () {\n // Update/create the documents\n return fetchJSON(genDBUrl(host, '_bulk_docs'), {\n method: 'POST',\n body: JSON.stringify(req)\n }, callback);\n }).catch(callback);\n };\n\n\n // Update/create document\n api._put = function (doc, opts, callback) {\n setup().then(function () {\n return preprocessAttachments$1(doc);\n }).then(function () {\n return fetchJSON(genDBUrl(host, encodeDocId(doc._id)), {\n method: 'PUT',\n body: JSON.stringify(doc)\n });\n }).then(function (result) {\n callback(null, result.data);\n }).catch(function (err) {\n err.docId = doc && doc._id;\n callback(err);\n });\n };\n\n\n // Get a listing of the documents in the database given\n // by host and ordered by increasing id.\n api.allDocs = adapterFun$$1('allDocs', function (opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = clone(opts);\n\n // List of parameters to add to the GET request\n var params = {};\n var body;\n var method = 'GET';\n\n if (opts.conflicts) {\n params.conflicts = true;\n }\n\n /* istanbul ignore if */\n if (opts.update_seq) {\n params.update_seq = true;\n }\n\n if (opts.descending) {\n params.descending = true;\n }\n\n if (opts.include_docs) {\n params.include_docs = true;\n }\n\n // added in CouchDB 1.6.0\n if (opts.attachments) {\n params.attachments = true;\n }\n\n if (opts.key) {\n params.key = JSON.stringify(opts.key);\n }\n\n if (opts.start_key) {\n opts.startkey = opts.start_key;\n }\n\n if (opts.startkey) {\n params.startkey = JSON.stringify(opts.startkey);\n }\n\n if (opts.end_key) {\n opts.endkey = opts.end_key;\n }\n\n if (opts.endkey) {\n params.endkey = JSON.stringify(opts.endkey);\n }\n\n if (typeof opts.inclusive_end !== 'undefined') {\n params.inclusive_end = !!opts.inclusive_end;\n }\n\n if (typeof opts.limit !== 'undefined') {\n params.limit = opts.limit;\n }\n\n if (typeof opts.skip !== 'undefined') {\n params.skip = opts.skip;\n }\n\n var paramStr = paramsToStr(params);\n\n if (typeof opts.keys !== 'undefined') {\n method = 'POST';\n body = {keys: opts.keys};\n }\n\n fetchJSON(genDBUrl(host, '_all_docs' + paramStr), {\n method: method,\n body: JSON.stringify(body)\n }).then(function (result) {\n if (opts.include_docs && opts.attachments && opts.binary) {\n result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);\n }\n callback(null, result.data);\n }).catch(callback);\n });\n\n // Get a list of changes made to documents in the database given by host.\n // TODO According to the README, there should be two other methods here,\n // api.changes.addListener and api.changes.removeListener.\n api._changes = function (opts) {\n\n // We internally page the results of a changes request, this means\n // if there is a large set of changes to be returned we can start\n // processing them quicker instead of waiting on the entire\n // set of changes to return and attempting to process them at once\n var batchSize = 'batch_size' in opts ? opts.batch_size : CHANGES_BATCH_SIZE;\n\n opts = clone(opts);\n\n if (opts.continuous && !('heartbeat' in opts)) {\n opts.heartbeat = DEFAULT_HEARTBEAT;\n }\n\n var requestTimeout = ('timeout' in opts) ? opts.timeout : 30 * 1000;\n\n // ensure CHANGES_TIMEOUT_BUFFER applies\n if ('timeout' in opts && opts.timeout &&\n (requestTimeout - opts.timeout) < CHANGES_TIMEOUT_BUFFER) {\n requestTimeout = opts.timeout + CHANGES_TIMEOUT_BUFFER;\n }\n\n /* istanbul ignore if */\n if ('heartbeat' in opts && opts.heartbeat &&\n (requestTimeout - opts.heartbeat) < CHANGES_TIMEOUT_BUFFER) {\n requestTimeout = opts.heartbeat + CHANGES_TIMEOUT_BUFFER;\n }\n\n var params = {};\n if ('timeout' in opts && opts.timeout) {\n params.timeout = opts.timeout;\n }\n\n var limit = (typeof opts.limit !== 'undefined') ? opts.limit : false;\n var leftToFetch = limit;\n\n if (opts.style) {\n params.style = opts.style;\n }\n\n if (opts.include_docs || opts.filter && typeof opts.filter === 'function') {\n params.include_docs = true;\n }\n\n if (opts.attachments) {\n params.attachments = true;\n }\n\n if (opts.continuous) {\n params.feed = 'longpoll';\n }\n\n if (opts.seq_interval) {\n params.seq_interval = opts.seq_interval;\n }\n\n if (opts.conflicts) {\n params.conflicts = true;\n }\n\n if (opts.descending) {\n params.descending = true;\n }\n \n /* istanbul ignore if */\n if (opts.update_seq) {\n params.update_seq = true;\n }\n\n if ('heartbeat' in opts) {\n // If the heartbeat value is false, it disables the default heartbeat\n if (opts.heartbeat) {\n params.heartbeat = opts.heartbeat;\n }\n }\n\n if (opts.filter && typeof opts.filter === 'string') {\n params.filter = opts.filter;\n }\n\n if (opts.view && typeof opts.view === 'string') {\n params.filter = '_view';\n params.view = opts.view;\n }\n\n // If opts.query_params exists, pass it through to the changes request.\n // These parameters may be used by the filter on the source database.\n if (opts.query_params && typeof opts.query_params === 'object') {\n for (var param_name in opts.query_params) {\n /* istanbul ignore else */\n if (opts.query_params.hasOwnProperty(param_name)) {\n params[param_name] = opts.query_params[param_name];\n }\n }\n }\n\n var method = 'GET';\n var body;\n\n if (opts.doc_ids) {\n // set this automagically for the user; it's annoying that couchdb\n // requires both a \"filter\" and a \"doc_ids\" param.\n params.filter = '_doc_ids';\n method = 'POST';\n body = {doc_ids: opts.doc_ids };\n }\n /* istanbul ignore next */\n else if (opts.selector) {\n // set this automagically for the user, similar to above\n params.filter = '_selector';\n method = 'POST';\n body = {selector: opts.selector };\n }\n\n var controller = new a();\n var lastFetchedSeq;\n\n // Get all the changes starting wtih the one immediately after the\n // sequence number given by since.\n var fetchData = function (since, callback) {\n if (opts.aborted) {\n return;\n }\n params.since = since;\n // \"since\" can be any kind of json object in Cloudant/CouchDB 2.x\n /* istanbul ignore next */\n if (typeof params.since === \"object\") {\n params.since = JSON.stringify(params.since);\n }\n\n if (opts.descending) {\n if (limit) {\n params.limit = leftToFetch;\n }\n } else {\n params.limit = (!limit || leftToFetch > batchSize) ?\n batchSize : leftToFetch;\n }\n\n // Set the options for the ajax call\n var url = genDBUrl(host, '_changes' + paramsToStr(params));\n var fetchOpts = {\n signal: controller.signal,\n method: method,\n body: JSON.stringify(body)\n };\n lastFetchedSeq = since;\n\n /* istanbul ignore if */\n if (opts.aborted) {\n return;\n }\n\n // Get the changes\n setup().then(function () {\n return fetchJSON(url, fetchOpts, callback);\n }).catch(callback);\n };\n\n // If opts.since exists, get all the changes from the sequence\n // number given by opts.since. Otherwise, get all the changes\n // from the sequence number 0.\n var results = {results: []};\n\n var fetched = function (err, res) {\n if (opts.aborted) {\n return;\n }\n var raw_results_length = 0;\n // If the result of the ajax call (res) contains changes (res.results)\n if (res && res.results) {\n raw_results_length = res.results.length;\n results.last_seq = res.last_seq;\n var pending = null;\n var lastSeq = null;\n // Attach 'pending' property if server supports it (CouchDB 2.0+)\n /* istanbul ignore if */\n if (typeof res.pending === 'number') {\n pending = res.pending;\n }\n if (typeof results.last_seq === 'string' || typeof results.last_seq === 'number') {\n lastSeq = results.last_seq;\n }\n // For each change\n var req = {};\n req.query = opts.query_params;\n res.results = res.results.filter(function (c) {\n leftToFetch--;\n var ret = filterChange(opts)(c);\n if (ret) {\n if (opts.include_docs && opts.attachments && opts.binary) {\n readAttachmentsAsBlobOrBuffer(c);\n }\n if (opts.return_docs) {\n results.results.push(c);\n }\n opts.onChange(c, pending, lastSeq);\n }\n return ret;\n });\n } else if (err) {\n // In case of an error, stop listening for changes and call\n // opts.complete\n opts.aborted = true;\n opts.complete(err);\n return;\n }\n\n // The changes feed may have timed out with no results\n // if so reuse last update sequence\n if (res && res.last_seq) {\n lastFetchedSeq = res.last_seq;\n }\n\n var finished = (limit && leftToFetch <= 0) ||\n (res && raw_results_length < batchSize) ||\n (opts.descending);\n\n if ((opts.continuous && !(limit && leftToFetch <= 0)) || !finished) {\n // Queue a call to fetch again with the newest sequence number\n nextTick(function () { fetchData(lastFetchedSeq, fetched); });\n } else {\n // We're done, call the callback\n opts.complete(null, results);\n }\n };\n\n fetchData(opts.since || 0, fetched);\n\n // Return a method to cancel this method from processing any more\n return {\n cancel: function () {\n opts.aborted = true;\n controller.abort();\n }\n };\n };\n\n // Given a set of document/revision IDs (given by req), tets the subset of\n // those that do NOT correspond to revisions stored in the database.\n // See http://wiki.apache.org/couchdb/HttpPostRevsDiff\n api.revsDiff = adapterFun$$1('revsDiff', function (req, opts, callback) {\n // If no options were given, set the callback to be the second parameter\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n\n // Get the missing document/revision IDs\n fetchJSON(genDBUrl(host, '_revs_diff'), {\n method: 'POST',\n body: JSON.stringify(req)\n }, callback).catch(callback);\n });\n\n api._close = function (callback) {\n callback();\n };\n\n api._destroy = function (options, callback) {\n fetchJSON(genDBUrl(host, ''), {method: 'DELETE'}).then(function (json) {\n callback(null, json);\n }).catch(function (err) {\n /* istanbul ignore if */\n if (err.status === 404) {\n callback(null, {ok: true});\n } else {\n callback(err);\n }\n });\n };\n}\n\n// HttpPouch is a valid adapter.\nHttpPouch.valid = function () {\n return true;\n};\n\nfunction HttpPouch$1 (PouchDB) {\n PouchDB.adapter('http', HttpPouch, false);\n PouchDB.adapter('https', HttpPouch, false);\n}\n\nfunction QueryParseError(message) {\n this.status = 400;\n this.name = 'query_parse_error';\n this.message = message;\n this.error = true;\n try {\n Error.captureStackTrace(this, QueryParseError);\n } catch (e) {}\n}\n\ninherits(QueryParseError, Error);\n\nfunction NotFoundError(message) {\n this.status = 404;\n this.name = 'not_found';\n this.message = message;\n this.error = true;\n try {\n Error.captureStackTrace(this, NotFoundError);\n } catch (e) {}\n}\n\ninherits(NotFoundError, Error);\n\nfunction BuiltInError(message) {\n this.status = 500;\n this.name = 'invalid_value';\n this.message = message;\n this.error = true;\n try {\n Error.captureStackTrace(this, BuiltInError);\n } catch (e) {}\n}\n\ninherits(BuiltInError, Error);\n\nfunction promisedCallback(promise, callback) {\n if (callback) {\n promise.then(function (res) {\n nextTick(function () {\n callback(null, res);\n });\n }, function (reason) {\n nextTick(function () {\n callback(reason);\n });\n });\n }\n return promise;\n}\n\nfunction callbackify(fun) {\n return getArguments(function (args) {\n var cb = args.pop();\n var promise = fun.apply(this, args);\n if (typeof cb === 'function') {\n promisedCallback(promise, cb);\n }\n return promise;\n });\n}\n\n// Promise finally util similar to Q.finally\nfunction fin(promise, finalPromiseFactory) {\n return promise.then(function (res) {\n return finalPromiseFactory().then(function () {\n return res;\n });\n }, function (reason) {\n return finalPromiseFactory().then(function () {\n throw reason;\n });\n });\n}\n\nfunction sequentialize(queue, promiseFactory) {\n return function () {\n var args = arguments;\n var that = this;\n return queue.add(function () {\n return promiseFactory.apply(that, args);\n });\n };\n}\n\n// uniq an array of strings, order not guaranteed\n// similar to underscore/lodash _.uniq\nfunction uniq(arr) {\n var theSet = new ExportedSet(arr);\n var result = new Array(theSet.size);\n var index = -1;\n theSet.forEach(function (value) {\n result[++index] = value;\n });\n return result;\n}\n\nfunction mapToKeysArray(map) {\n var result = new Array(map.size);\n var index = -1;\n map.forEach(function (value, key) {\n result[++index] = key;\n });\n return result;\n}\n\nfunction createBuiltInError(name) {\n var message = 'builtin ' + name +\n ' function requires map values to be numbers' +\n ' or number arrays';\n return new BuiltInError(message);\n}\n\nfunction sum(values) {\n var result = 0;\n for (var i = 0, len = values.length; i < len; i++) {\n var num = values[i];\n if (typeof num !== 'number') {\n if (Array.isArray(num)) {\n // lists of numbers are also allowed, sum them separately\n result = typeof result === 'number' ? [result] : result;\n for (var j = 0, jLen = num.length; j < jLen; j++) {\n var jNum = num[j];\n if (typeof jNum !== 'number') {\n throw createBuiltInError('_sum');\n } else if (typeof result[j] === 'undefined') {\n result.push(jNum);\n } else {\n result[j] += jNum;\n }\n }\n } else { // not array/number\n throw createBuiltInError('_sum');\n }\n } else if (typeof result === 'number') {\n result += num;\n } else { // add number to array\n result[0] += num;\n }\n }\n return result;\n}\n\nvar log = guardedConsole.bind(null, 'log');\nvar isArray = Array.isArray;\nvar toJSON = JSON.parse;\n\nfunction evalFunctionWithEval(func, emit) {\n return scopeEval(\n \"return (\" + func.replace(/;\\s*$/, \"\") + \");\",\n {\n emit: emit,\n sum: sum,\n log: log,\n isArray: isArray,\n toJSON: toJSON\n }\n );\n}\n\n/*\n * Simple task queue to sequentialize actions. Assumes\n * callbacks will eventually fire (once).\n */\n\n\nfunction TaskQueue$1() {\n this.promise = new Promise(function (fulfill) {fulfill(); });\n}\nTaskQueue$1.prototype.add = function (promiseFactory) {\n this.promise = this.promise.catch(function () {\n // just recover\n }).then(function () {\n return promiseFactory();\n });\n return this.promise;\n};\nTaskQueue$1.prototype.finish = function () {\n return this.promise;\n};\n\nfunction stringify(input) {\n if (!input) {\n return 'undefined'; // backwards compat for empty reduce\n }\n // for backwards compat with mapreduce, functions/strings are stringified\n // as-is. everything else is JSON-stringified.\n switch (typeof input) {\n case 'function':\n // e.g. a mapreduce map\n return input.toString();\n case 'string':\n // e.g. a mapreduce built-in _reduce function\n return input.toString();\n default:\n // e.g. a JSON object in the case of mango queries\n return JSON.stringify(input);\n }\n}\n\n/* create a string signature for a view so we can cache it and uniq it */\nfunction createViewSignature(mapFun, reduceFun) {\n // the \"undefined\" part is for backwards compatibility\n return stringify(mapFun) + stringify(reduceFun) + 'undefined';\n}\n\nfunction createView(sourceDB, viewName, mapFun, reduceFun, temporary, localDocName) {\n var viewSignature = createViewSignature(mapFun, reduceFun);\n\n var cachedViews;\n if (!temporary) {\n // cache this to ensure we don't try to update the same view twice\n cachedViews = sourceDB._cachedViews = sourceDB._cachedViews || {};\n if (cachedViews[viewSignature]) {\n return cachedViews[viewSignature];\n }\n }\n\n var promiseForView = sourceDB.info().then(function (info) {\n\n var depDbName = info.db_name + '-mrview-' +\n (temporary ? 'temp' : stringMd5(viewSignature));\n\n // save the view name in the source db so it can be cleaned up if necessary\n // (e.g. when the _design doc is deleted, remove all associated view data)\n function diffFunction(doc) {\n doc.views = doc.views || {};\n var fullViewName = viewName;\n if (fullViewName.indexOf('/') === -1) {\n fullViewName = viewName + '/' + viewName;\n }\n var depDbs = doc.views[fullViewName] = doc.views[fullViewName] || {};\n /* istanbul ignore if */\n if (depDbs[depDbName]) {\n return; // no update necessary\n }\n depDbs[depDbName] = true;\n return doc;\n }\n return upsert(sourceDB, '_local/' + localDocName, diffFunction).then(function () {\n return sourceDB.registerDependentDatabase(depDbName).then(function (res) {\n var db = res.db;\n db.auto_compaction = true;\n var view = {\n name: depDbName,\n db: db,\n sourceDB: sourceDB,\n adapter: sourceDB.adapter,\n mapFun: mapFun,\n reduceFun: reduceFun\n };\n return view.db.get('_local/lastSeq').catch(function (err) {\n /* istanbul ignore if */\n if (err.status !== 404) {\n throw err;\n }\n }).then(function (lastSeqDoc) {\n view.seq = lastSeqDoc ? lastSeqDoc.seq : 0;\n if (cachedViews) {\n view.db.once('destroyed', function () {\n delete cachedViews[viewSignature];\n });\n }\n return view;\n });\n });\n });\n });\n\n if (cachedViews) {\n cachedViews[viewSignature] = promiseForView;\n }\n return promiseForView;\n}\n\nvar persistentQueues = {};\nvar tempViewQueue = new TaskQueue$1();\nvar CHANGES_BATCH_SIZE$1 = 50;\n\nfunction parseViewName(name) {\n // can be either 'ddocname/viewname' or just 'viewname'\n // (where the ddoc name is the same)\n return name.indexOf('/') === -1 ? [name, name] : name.split('/');\n}\n\nfunction isGenOne(changes) {\n // only return true if the current change is 1-\n // and there are no other leafs\n return changes.length === 1 && /^1-/.test(changes[0].rev);\n}\n\nfunction emitError(db, e) {\n try {\n db.emit('error', e);\n } catch (err) {\n guardedConsole('error',\n 'The user\\'s map/reduce function threw an uncaught error.\\n' +\n 'You can debug this error by doing:\\n' +\n 'myDatabase.on(\\'error\\', function (err) { debugger; });\\n' +\n 'Please double-check your map/reduce function.');\n guardedConsole('error', e);\n }\n}\n\n/**\n * Returns an \"abstract\" mapreduce object of the form:\n *\n * {\n * query: queryFun,\n * viewCleanup: viewCleanupFun\n * }\n *\n * Arguments are:\n *\n * localDoc: string\n * This is for the local doc that gets saved in order to track the\n * \"dependent\" DBs and clean them up for viewCleanup. It should be\n * unique, so that indexer plugins don't collide with each other.\n * mapper: function (mapFunDef, emit)\n * Returns a map function based on the mapFunDef, which in the case of\n * normal map/reduce is just the de-stringified function, but may be\n * something else, such as an object in the case of pouchdb-find.\n * reducer: function (reduceFunDef)\n * Ditto, but for reducing. Modules don't have to support reducing\n * (e.g. pouchdb-find).\n * ddocValidator: function (ddoc, viewName)\n * Throws an error if the ddoc or viewName is not valid.\n * This could be a way to communicate to the user that the configuration for the\n * indexer is invalid.\n */\nfunction createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator) {\n\n function tryMap(db, fun, doc) {\n // emit an event if there was an error thrown by a map function.\n // putting try/catches in a single function also avoids deoptimizations.\n try {\n fun(doc);\n } catch (e) {\n emitError(db, e);\n }\n }\n\n function tryReduce(db, fun, keys, values, rereduce) {\n // same as above, but returning the result or an error. there are two separate\n // functions to avoid extra memory allocations since the tryCode() case is used\n // for custom map functions (common) vs this function, which is only used for\n // custom reduce functions (rare)\n try {\n return {output : fun(keys, values, rereduce)};\n } catch (e) {\n emitError(db, e);\n return {error: e};\n }\n }\n\n function sortByKeyThenValue(x, y) {\n var keyCompare = collate(x.key, y.key);\n return keyCompare !== 0 ? keyCompare : collate(x.value, y.value);\n }\n\n function sliceResults(results, limit, skip) {\n skip = skip || 0;\n if (typeof limit === 'number') {\n return results.slice(skip, limit + skip);\n } else if (skip > 0) {\n return results.slice(skip);\n }\n return results;\n }\n\n function rowToDocId(row) {\n var val = row.value;\n // Users can explicitly specify a joined doc _id, or it\n // defaults to the doc _id that emitted the key/value.\n var docId = (val && typeof val === 'object' && val._id) || row.id;\n return docId;\n }\n\n function readAttachmentsAsBlobOrBuffer(res) {\n res.rows.forEach(function (row) {\n var atts = row.doc && row.doc._attachments;\n if (!atts) {\n return;\n }\n Object.keys(atts).forEach(function (filename) {\n var att = atts[filename];\n atts[filename].data = b64ToBluffer(att.data, att.content_type);\n });\n });\n }\n\n function postprocessAttachments(opts) {\n return function (res) {\n if (opts.include_docs && opts.attachments && opts.binary) {\n readAttachmentsAsBlobOrBuffer(res);\n }\n return res;\n };\n }\n\n function addHttpParam(paramName, opts, params, asJson) {\n // add an http param from opts to params, optionally json-encoded\n var val = opts[paramName];\n if (typeof val !== 'undefined') {\n if (asJson) {\n val = encodeURIComponent(JSON.stringify(val));\n }\n params.push(paramName + '=' + val);\n }\n }\n\n function coerceInteger(integerCandidate) {\n if (typeof integerCandidate !== 'undefined') {\n var asNumber = Number(integerCandidate);\n // prevents e.g. '1foo' or '1.1' being coerced to 1\n if (!isNaN(asNumber) && asNumber === parseInt(integerCandidate, 10)) {\n return asNumber;\n } else {\n return integerCandidate;\n }\n }\n }\n\n function coerceOptions(opts) {\n opts.group_level = coerceInteger(opts.group_level);\n opts.limit = coerceInteger(opts.limit);\n opts.skip = coerceInteger(opts.skip);\n return opts;\n }\n\n function checkPositiveInteger(number) {\n if (number) {\n if (typeof number !== 'number') {\n return new QueryParseError('Invalid value for integer: \"' +\n number + '\"');\n }\n if (number < 0) {\n return new QueryParseError('Invalid value for positive integer: ' +\n '\"' + number + '\"');\n }\n }\n }\n\n function checkQueryParseError(options, fun) {\n var startkeyName = options.descending ? 'endkey' : 'startkey';\n var endkeyName = options.descending ? 'startkey' : 'endkey';\n\n if (typeof options[startkeyName] !== 'undefined' &&\n typeof options[endkeyName] !== 'undefined' &&\n collate(options[startkeyName], options[endkeyName]) > 0) {\n throw new QueryParseError('No rows can match your key range, ' +\n 'reverse your start_key and end_key or set {descending : true}');\n } else if (fun.reduce && options.reduce !== false) {\n if (options.include_docs) {\n throw new QueryParseError('{include_docs:true} is invalid for reduce');\n } else if (options.keys && options.keys.length > 1 &&\n !options.group && !options.group_level) {\n throw new QueryParseError('Multi-key fetches for reduce views must use ' +\n '{group: true}');\n }\n }\n ['group_level', 'limit', 'skip'].forEach(function (optionName) {\n var error = checkPositiveInteger(options[optionName]);\n if (error) {\n throw error;\n }\n });\n }\n\n function httpQuery(db, fun, opts) {\n // List of parameters to add to the PUT request\n var params = [];\n var body;\n var method = 'GET';\n var ok, status;\n\n // If opts.reduce exists and is defined, then add it to the list\n // of parameters.\n // If reduce=false then the results are that of only the map function\n // not the final result of map and reduce.\n addHttpParam('reduce', opts, params);\n addHttpParam('include_docs', opts, params);\n addHttpParam('attachments', opts, params);\n addHttpParam('limit', opts, params);\n addHttpParam('descending', opts, params);\n addHttpParam('group', opts, params);\n addHttpParam('group_level', opts, params);\n addHttpParam('skip', opts, params);\n addHttpParam('stale', opts, params);\n addHttpParam('conflicts', opts, params);\n addHttpParam('startkey', opts, params, true);\n addHttpParam('start_key', opts, params, true);\n addHttpParam('endkey', opts, params, true);\n addHttpParam('end_key', opts, params, true);\n addHttpParam('inclusive_end', opts, params);\n addHttpParam('key', opts, params, true);\n addHttpParam('update_seq', opts, params);\n\n // Format the list of parameters into a valid URI query string\n params = params.join('&');\n params = params === '' ? '' : '?' + params;\n\n // If keys are supplied, issue a POST to circumvent GET query string limits\n // see http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options\n if (typeof opts.keys !== 'undefined') {\n var MAX_URL_LENGTH = 2000;\n // according to http://stackoverflow.com/a/417184/680742,\n // the de facto URL length limit is 2000 characters\n\n var keysAsString =\n 'keys=' + encodeURIComponent(JSON.stringify(opts.keys));\n if (keysAsString.length + params.length + 1 <= MAX_URL_LENGTH) {\n // If the keys are short enough, do a GET. we do this to work around\n // Safari not understanding 304s on POSTs (see pouchdb/pouchdb#1239)\n params += (params[0] === '?' ? '&' : '?') + keysAsString;\n } else {\n method = 'POST';\n if (typeof fun === 'string') {\n body = {keys: opts.keys};\n } else { // fun is {map : mapfun}, so append to this\n fun.keys = opts.keys;\n }\n }\n }\n\n // We are referencing a query defined in the design doc\n if (typeof fun === 'string') {\n var parts = parseViewName(fun);\n return db.fetch('_design/' + parts[0] + '/_view/' + parts[1] + params, {\n headers: new h({'Content-Type': 'application/json'}),\n method: method,\n body: JSON.stringify(body)\n }).then(function (response) {\n ok = response.ok;\n status = response.status;\n return response.json();\n }).then(function (result) {\n if (!ok) {\n result.status = status;\n throw generateErrorFromResponse(result);\n }\n // fail the entire request if the result contains an error\n result.rows.forEach(function (row) {\n /* istanbul ignore if */\n if (row.value && row.value.error && row.value.error === \"builtin_reduce_error\") {\n throw new Error(row.reason);\n }\n });\n return result;\n }).then(postprocessAttachments(opts));\n }\n\n // We are using a temporary view, terrible for performance, good for testing\n body = body || {};\n Object.keys(fun).forEach(function (key) {\n if (Array.isArray(fun[key])) {\n body[key] = fun[key];\n } else {\n body[key] = fun[key].toString();\n }\n });\n\n return db.fetch('_temp_view' + params, {\n headers: new h({'Content-Type': 'application/json'}),\n method: 'POST',\n body: JSON.stringify(body)\n }).then(function (response) {\n ok = response.ok;\n status = response.status;\n return response.json();\n }).then(function (result) {\n if (!ok) {\n result.status = status;\n throw generateErrorFromResponse(result);\n }\n return result;\n }).then(postprocessAttachments(opts));\n }\n\n // custom adapters can define their own api._query\n // and override the default behavior\n /* istanbul ignore next */\n function customQuery(db, fun, opts) {\n return new Promise(function (resolve, reject) {\n db._query(fun, opts, function (err, res) {\n if (err) {\n return reject(err);\n }\n resolve(res);\n });\n });\n }\n\n // custom adapters can define their own api._viewCleanup\n // and override the default behavior\n /* istanbul ignore next */\n function customViewCleanup(db) {\n return new Promise(function (resolve, reject) {\n db._viewCleanup(function (err, res) {\n if (err) {\n return reject(err);\n }\n resolve(res);\n });\n });\n }\n\n function defaultsTo(value) {\n return function (reason) {\n /* istanbul ignore else */\n if (reason.status === 404) {\n return value;\n } else {\n throw reason;\n }\n };\n }\n\n // returns a promise for a list of docs to update, based on the input docId.\n // the order doesn't matter, because post-3.2.0, bulkDocs\n // is an atomic operation in all three adapters.\n function getDocsToPersist(docId, view, docIdsToChangesAndEmits) {\n var metaDocId = '_local/doc_' + docId;\n var defaultMetaDoc = {_id: metaDocId, keys: []};\n var docData = docIdsToChangesAndEmits.get(docId);\n var indexableKeysToKeyValues = docData[0];\n var changes = docData[1];\n\n function getMetaDoc() {\n if (isGenOne(changes)) {\n // generation 1, so we can safely assume initial state\n // for performance reasons (avoids unnecessary GETs)\n return Promise.resolve(defaultMetaDoc);\n }\n return view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc));\n }\n\n function getKeyValueDocs(metaDoc) {\n if (!metaDoc.keys.length) {\n // no keys, no need for a lookup\n return Promise.resolve({rows: []});\n }\n return view.db.allDocs({\n keys: metaDoc.keys,\n include_docs: true\n });\n }\n\n function processKeyValueDocs(metaDoc, kvDocsRes) {\n var kvDocs = [];\n var oldKeys = new ExportedSet();\n\n for (var i = 0, len = kvDocsRes.rows.length; i < len; i++) {\n var row = kvDocsRes.rows[i];\n var doc = row.doc;\n if (!doc) { // deleted\n continue;\n }\n kvDocs.push(doc);\n oldKeys.add(doc._id);\n doc._deleted = !indexableKeysToKeyValues.has(doc._id);\n if (!doc._deleted) {\n var keyValue = indexableKeysToKeyValues.get(doc._id);\n if ('value' in keyValue) {\n doc.value = keyValue.value;\n }\n }\n }\n var newKeys = mapToKeysArray(indexableKeysToKeyValues);\n newKeys.forEach(function (key) {\n if (!oldKeys.has(key)) {\n // new doc\n var kvDoc = {\n _id: key\n };\n var keyValue = indexableKeysToKeyValues.get(key);\n if ('value' in keyValue) {\n kvDoc.value = keyValue.value;\n }\n kvDocs.push(kvDoc);\n }\n });\n metaDoc.keys = uniq(newKeys.concat(metaDoc.keys));\n kvDocs.push(metaDoc);\n\n return kvDocs;\n }\n\n return getMetaDoc().then(function (metaDoc) {\n return getKeyValueDocs(metaDoc).then(function (kvDocsRes) {\n return processKeyValueDocs(metaDoc, kvDocsRes);\n });\n });\n }\n\n // updates all emitted key/value docs and metaDocs in the mrview database\n // for the given batch of documents from the source database\n function saveKeyValues(view, docIdsToChangesAndEmits, seq) {\n var seqDocId = '_local/lastSeq';\n return view.db.get(seqDocId)\n .catch(defaultsTo({_id: seqDocId, seq: 0}))\n .then(function (lastSeqDoc) {\n var docIds = mapToKeysArray(docIdsToChangesAndEmits);\n return Promise.all(docIds.map(function (docId) {\n return getDocsToPersist(docId, view, docIdsToChangesAndEmits);\n })).then(function (listOfDocsToPersist) {\n var docsToPersist = flatten(listOfDocsToPersist);\n lastSeqDoc.seq = seq;\n docsToPersist.push(lastSeqDoc);\n // write all docs in a single operation, update the seq once\n return view.db.bulkDocs({docs : docsToPersist});\n });\n });\n }\n\n function getQueue(view) {\n var viewName = typeof view === 'string' ? view : view.name;\n var queue = persistentQueues[viewName];\n if (!queue) {\n queue = persistentQueues[viewName] = new TaskQueue$1();\n }\n return queue;\n }\n\n function updateView(view) {\n return sequentialize(getQueue(view), function () {\n return updateViewInQueue(view);\n })();\n }\n\n function updateViewInQueue(view) {\n // bind the emit function once\n var mapResults;\n var doc;\n\n function emit(key, value) {\n var output = {id: doc._id, key: normalizeKey(key)};\n // Don't explicitly store the value unless it's defined and non-null.\n // This saves on storage space, because often people don't use it.\n if (typeof value !== 'undefined' && value !== null) {\n output.value = normalizeKey(value);\n }\n mapResults.push(output);\n }\n\n var mapFun = mapper(view.mapFun, emit);\n\n var currentSeq = view.seq || 0;\n\n function processChange(docIdsToChangesAndEmits, seq) {\n return function () {\n return saveKeyValues(view, docIdsToChangesAndEmits, seq);\n };\n }\n\n var queue = new TaskQueue$1();\n\n function processNextBatch() {\n return view.sourceDB.changes({\n return_docs: true,\n conflicts: true,\n include_docs: true,\n style: 'all_docs',\n since: currentSeq,\n limit: CHANGES_BATCH_SIZE$1\n }).then(processBatch);\n }\n\n function processBatch(response) {\n var results = response.results;\n if (!results.length) {\n return;\n }\n var docIdsToChangesAndEmits = createDocIdsToChangesAndEmits(results);\n queue.add(processChange(docIdsToChangesAndEmits, currentSeq));\n if (results.length < CHANGES_BATCH_SIZE$1) {\n return;\n }\n return processNextBatch();\n }\n\n function createDocIdsToChangesAndEmits(results) {\n var docIdsToChangesAndEmits = new ExportedMap();\n for (var i = 0, len = results.length; i < len; i++) {\n var change = results[i];\n if (change.doc._id[0] !== '_') {\n mapResults = [];\n doc = change.doc;\n\n if (!doc._deleted) {\n tryMap(view.sourceDB, mapFun, doc);\n }\n mapResults.sort(sortByKeyThenValue);\n\n var indexableKeysToKeyValues = createIndexableKeysToKeyValues(mapResults);\n docIdsToChangesAndEmits.set(change.doc._id, [\n indexableKeysToKeyValues,\n change.changes\n ]);\n }\n currentSeq = change.seq;\n }\n return docIdsToChangesAndEmits;\n }\n\n function createIndexableKeysToKeyValues(mapResults) {\n var indexableKeysToKeyValues = new ExportedMap();\n var lastKey;\n for (var i = 0, len = mapResults.length; i < len; i++) {\n var emittedKeyValue = mapResults[i];\n var complexKey = [emittedKeyValue.key, emittedKeyValue.id];\n if (i > 0 && collate(emittedKeyValue.key, lastKey) === 0) {\n complexKey.push(i); // dup key+id, so make it unique\n }\n indexableKeysToKeyValues.set(toIndexableString(complexKey), emittedKeyValue);\n lastKey = emittedKeyValue.key;\n }\n return indexableKeysToKeyValues;\n }\n\n return processNextBatch().then(function () {\n return queue.finish();\n }).then(function () {\n view.seq = currentSeq;\n });\n }\n\n function reduceView(view, results, options) {\n if (options.group_level === 0) {\n delete options.group_level;\n }\n\n var shouldGroup = options.group || options.group_level;\n\n var reduceFun = reducer(view.reduceFun);\n\n var groups = [];\n var lvl = isNaN(options.group_level) ? Number.POSITIVE_INFINITY :\n options.group_level;\n results.forEach(function (e) {\n var last = groups[groups.length - 1];\n var groupKey = shouldGroup ? e.key : null;\n\n // only set group_level for array keys\n if (shouldGroup && Array.isArray(groupKey)) {\n groupKey = groupKey.slice(0, lvl);\n }\n\n if (last && collate(last.groupKey, groupKey) === 0) {\n last.keys.push([e.key, e.id]);\n last.values.push(e.value);\n return;\n }\n groups.push({\n keys: [[e.key, e.id]],\n values: [e.value],\n groupKey: groupKey\n });\n });\n results = [];\n for (var i = 0, len = groups.length; i < len; i++) {\n var e = groups[i];\n var reduceTry = tryReduce(view.sourceDB, reduceFun, e.keys, e.values, false);\n if (reduceTry.error && reduceTry.error instanceof BuiltInError) {\n // CouchDB returns an error if a built-in errors out\n throw reduceTry.error;\n }\n results.push({\n // CouchDB just sets the value to null if a non-built-in errors out\n value: reduceTry.error ? null : reduceTry.output,\n key: e.groupKey\n });\n }\n // no total_rows/offset when reducing\n return {rows: sliceResults(results, options.limit, options.skip)};\n }\n\n function queryView(view, opts) {\n return sequentialize(getQueue(view), function () {\n return queryViewInQueue(view, opts);\n })();\n }\n\n function queryViewInQueue(view, opts) {\n var totalRows;\n var shouldReduce = view.reduceFun && opts.reduce !== false;\n var skip = opts.skip || 0;\n if (typeof opts.keys !== 'undefined' && !opts.keys.length) {\n // equivalent query\n opts.limit = 0;\n delete opts.keys;\n }\n\n function fetchFromView(viewOpts) {\n viewOpts.include_docs = true;\n return view.db.allDocs(viewOpts).then(function (res) {\n totalRows = res.total_rows;\n return res.rows.map(function (result) {\n\n // implicit migration - in older versions of PouchDB,\n // we explicitly stored the doc as {id: ..., key: ..., value: ...}\n // this is tested in a migration test\n /* istanbul ignore next */\n if ('value' in result.doc && typeof result.doc.value === 'object' &&\n result.doc.value !== null) {\n var keys = Object.keys(result.doc.value).sort();\n // this detection method is not perfect, but it's unlikely the user\n // emitted a value which was an object with these 3 exact keys\n var expectedKeys = ['id', 'key', 'value'];\n if (!(keys < expectedKeys || keys > expectedKeys)) {\n return result.doc.value;\n }\n }\n\n var parsedKeyAndDocId = parseIndexableString(result.doc._id);\n return {\n key: parsedKeyAndDocId[0],\n id: parsedKeyAndDocId[1],\n value: ('value' in result.doc ? result.doc.value : null)\n };\n });\n });\n }\n\n function onMapResultsReady(rows) {\n var finalResults;\n if (shouldReduce) {\n finalResults = reduceView(view, rows, opts);\n } else {\n finalResults = {\n total_rows: totalRows,\n offset: skip,\n rows: rows\n };\n }\n /* istanbul ignore if */\n if (opts.update_seq) {\n finalResults.update_seq = view.seq;\n }\n if (opts.include_docs) {\n var docIds = uniq(rows.map(rowToDocId));\n\n return view.sourceDB.allDocs({\n keys: docIds,\n include_docs: true,\n conflicts: opts.conflicts,\n attachments: opts.attachments,\n binary: opts.binary\n }).then(function (allDocsRes) {\n var docIdsToDocs = new ExportedMap();\n allDocsRes.rows.forEach(function (row) {\n docIdsToDocs.set(row.id, row.doc);\n });\n rows.forEach(function (row) {\n var docId = rowToDocId(row);\n var doc = docIdsToDocs.get(docId);\n if (doc) {\n row.doc = doc;\n }\n });\n return finalResults;\n });\n } else {\n return finalResults;\n }\n }\n\n if (typeof opts.keys !== 'undefined') {\n var keys = opts.keys;\n var fetchPromises = keys.map(function (key) {\n var viewOpts = {\n startkey : toIndexableString([key]),\n endkey : toIndexableString([key, {}])\n };\n /* istanbul ignore if */\n if (opts.update_seq) {\n viewOpts.update_seq = true;\n }\n return fetchFromView(viewOpts);\n });\n return Promise.all(fetchPromises).then(flatten).then(onMapResultsReady);\n } else { // normal query, no 'keys'\n var viewOpts = {\n descending : opts.descending\n };\n /* istanbul ignore if */\n if (opts.update_seq) {\n viewOpts.update_seq = true;\n }\n var startkey;\n var endkey;\n if ('start_key' in opts) {\n startkey = opts.start_key;\n }\n if ('startkey' in opts) {\n startkey = opts.startkey;\n }\n if ('end_key' in opts) {\n endkey = opts.end_key;\n }\n if ('endkey' in opts) {\n endkey = opts.endkey;\n }\n if (typeof startkey !== 'undefined') {\n viewOpts.startkey = opts.descending ?\n toIndexableString([startkey, {}]) :\n toIndexableString([startkey]);\n }\n if (typeof endkey !== 'undefined') {\n var inclusiveEnd = opts.inclusive_end !== false;\n if (opts.descending) {\n inclusiveEnd = !inclusiveEnd;\n }\n\n viewOpts.endkey = toIndexableString(\n inclusiveEnd ? [endkey, {}] : [endkey]);\n }\n if (typeof opts.key !== 'undefined') {\n var keyStart = toIndexableString([opts.key]);\n var keyEnd = toIndexableString([opts.key, {}]);\n if (viewOpts.descending) {\n viewOpts.endkey = keyStart;\n viewOpts.startkey = keyEnd;\n } else {\n viewOpts.startkey = keyStart;\n viewOpts.endkey = keyEnd;\n }\n }\n if (!shouldReduce) {\n if (typeof opts.limit === 'number') {\n viewOpts.limit = opts.limit;\n }\n viewOpts.skip = skip;\n }\n return fetchFromView(viewOpts).then(onMapResultsReady);\n }\n }\n\n function httpViewCleanup(db) {\n return db.fetch('_view_cleanup', {\n headers: new h({'Content-Type': 'application/json'}),\n method: 'POST'\n }).then(function (response) {\n return response.json();\n });\n }\n\n function localViewCleanup(db) {\n return db.get('_local/' + localDocName).then(function (metaDoc) {\n var docsToViews = new ExportedMap();\n Object.keys(metaDoc.views).forEach(function (fullViewName) {\n var parts = parseViewName(fullViewName);\n var designDocName = '_design/' + parts[0];\n var viewName = parts[1];\n var views = docsToViews.get(designDocName);\n if (!views) {\n views = new ExportedSet();\n docsToViews.set(designDocName, views);\n }\n views.add(viewName);\n });\n var opts = {\n keys : mapToKeysArray(docsToViews),\n include_docs : true\n };\n return db.allDocs(opts).then(function (res) {\n var viewsToStatus = {};\n res.rows.forEach(function (row) {\n var ddocName = row.key.substring(8); // cuts off '_design/'\n docsToViews.get(row.key).forEach(function (viewName) {\n var fullViewName = ddocName + '/' + viewName;\n /* istanbul ignore if */\n if (!metaDoc.views[fullViewName]) {\n // new format, without slashes, to support PouchDB 2.2.0\n // migration test in pouchdb's browser.migration.js verifies this\n fullViewName = viewName;\n }\n var viewDBNames = Object.keys(metaDoc.views[fullViewName]);\n // design doc deleted, or view function nonexistent\n var statusIsGood = row.doc && row.doc.views &&\n row.doc.views[viewName];\n viewDBNames.forEach(function (viewDBName) {\n viewsToStatus[viewDBName] =\n viewsToStatus[viewDBName] || statusIsGood;\n });\n });\n });\n var dbsToDelete = Object.keys(viewsToStatus).filter(\n function (viewDBName) { return !viewsToStatus[viewDBName]; });\n var destroyPromises = dbsToDelete.map(function (viewDBName) {\n return sequentialize(getQueue(viewDBName), function () {\n return new db.constructor(viewDBName, db.__opts).destroy();\n })();\n });\n return Promise.all(destroyPromises).then(function () {\n return {ok: true};\n });\n });\n }, defaultsTo({ok: true}));\n }\n\n function queryPromised(db, fun, opts) {\n /* istanbul ignore next */\n if (typeof db._query === 'function') {\n return customQuery(db, fun, opts);\n }\n if (isRemote(db)) {\n return httpQuery(db, fun, opts);\n }\n\n if (typeof fun !== 'string') {\n // temp_view\n checkQueryParseError(opts, fun);\n\n tempViewQueue.add(function () {\n var createViewPromise = createView(\n /* sourceDB */ db,\n /* viewName */ 'temp_view/temp_view',\n /* mapFun */ fun.map,\n /* reduceFun */ fun.reduce,\n /* temporary */ true,\n /* localDocName */ localDocName);\n return createViewPromise.then(function (view) {\n return fin(updateView(view).then(function () {\n return queryView(view, opts);\n }), function () {\n return view.db.destroy();\n });\n });\n });\n return tempViewQueue.finish();\n } else {\n // persistent view\n var fullViewName = fun;\n var parts = parseViewName(fullViewName);\n var designDocName = parts[0];\n var viewName = parts[1];\n return db.get('_design/' + designDocName).then(function (doc) {\n var fun = doc.views && doc.views[viewName];\n\n if (!fun) {\n // basic validator; it's assumed that every subclass would want this\n throw new NotFoundError('ddoc ' + doc._id + ' has no view named ' +\n viewName);\n }\n\n ddocValidator(doc, viewName);\n checkQueryParseError(opts, fun);\n\n var createViewPromise = createView(\n /* sourceDB */ db,\n /* viewName */ fullViewName,\n /* mapFun */ fun.map,\n /* reduceFun */ fun.reduce,\n /* temporary */ false,\n /* localDocName */ localDocName);\n return createViewPromise.then(function (view) {\n if (opts.stale === 'ok' || opts.stale === 'update_after') {\n if (opts.stale === 'update_after') {\n nextTick(function () {\n updateView(view);\n });\n }\n return queryView(view, opts);\n } else { // stale not ok\n return updateView(view).then(function () {\n return queryView(view, opts);\n });\n }\n });\n });\n }\n }\n\n function abstractQuery(fun, opts, callback) {\n var db = this;\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n opts = opts ? coerceOptions(opts) : {};\n\n if (typeof fun === 'function') {\n fun = {map : fun};\n }\n\n var promise = Promise.resolve().then(function () {\n return queryPromised(db, fun, opts);\n });\n promisedCallback(promise, callback);\n return promise;\n }\n\n var abstractViewCleanup = callbackify(function () {\n var db = this;\n /* istanbul ignore next */\n if (typeof db._viewCleanup === 'function') {\n return customViewCleanup(db);\n }\n if (isRemote(db)) {\n return httpViewCleanup(db);\n }\n return localViewCleanup(db);\n });\n\n return {\n query: abstractQuery,\n viewCleanup: abstractViewCleanup\n };\n}\n\nvar builtInReduce = {\n _sum: function (keys, values) {\n return sum(values);\n },\n\n _count: function (keys, values) {\n return values.length;\n },\n\n _stats: function (keys, values) {\n // no need to implement rereduce=true, because Pouch\n // will never call it\n function sumsqr(values) {\n var _sumsqr = 0;\n for (var i = 0, len = values.length; i < len; i++) {\n var num = values[i];\n _sumsqr += (num * num);\n }\n return _sumsqr;\n }\n return {\n sum : sum(values),\n min : Math.min.apply(null, values),\n max : Math.max.apply(null, values),\n count : values.length,\n sumsqr : sumsqr(values)\n };\n }\n};\n\nfunction getBuiltIn(reduceFunString) {\n if (/^_sum/.test(reduceFunString)) {\n return builtInReduce._sum;\n } else if (/^_count/.test(reduceFunString)) {\n return builtInReduce._count;\n } else if (/^_stats/.test(reduceFunString)) {\n return builtInReduce._stats;\n } else if (/^_/.test(reduceFunString)) {\n throw new Error(reduceFunString + ' is not a supported reduce function.');\n }\n}\n\nfunction mapper(mapFun, emit) {\n // for temp_views one can use emit(doc, emit), see #38\n if (typeof mapFun === \"function\" && mapFun.length === 2) {\n var origMap = mapFun;\n return function (doc) {\n return origMap(doc, emit);\n };\n } else {\n return evalFunctionWithEval(mapFun.toString(), emit);\n }\n}\n\nfunction reducer(reduceFun) {\n var reduceFunString = reduceFun.toString();\n var builtIn = getBuiltIn(reduceFunString);\n if (builtIn) {\n return builtIn;\n } else {\n return evalFunctionWithEval(reduceFunString);\n }\n}\n\nfunction ddocValidator(ddoc, viewName) {\n var fun = ddoc.views && ddoc.views[viewName];\n if (typeof fun.map !== 'string') {\n throw new NotFoundError('ddoc ' + ddoc._id + ' has no string view named ' +\n viewName + ', instead found object of type: ' + typeof fun.map);\n }\n}\n\nvar localDocName = 'mrviews';\nvar abstract = createAbstractMapReduce(localDocName, mapper, reducer, ddocValidator);\n\nfunction query(fun, opts, callback) {\n return abstract.query.call(this, fun, opts, callback);\n}\n\nfunction viewCleanup(callback) {\n return abstract.viewCleanup.call(this, callback);\n}\n\nvar mapreduce = {\n query: query,\n viewCleanup: viewCleanup\n};\n\nfunction isGenOne$1(rev) {\n return /^1-/.test(rev);\n}\n\nfunction fileHasChanged(localDoc, remoteDoc, filename) {\n return !localDoc._attachments ||\n !localDoc._attachments[filename] ||\n localDoc._attachments[filename].digest !== remoteDoc._attachments[filename].digest;\n}\n\nfunction getDocAttachments(db, doc) {\n var filenames = Object.keys(doc._attachments);\n return Promise.all(filenames.map(function (filename) {\n return db.getAttachment(doc._id, filename, {rev: doc._rev});\n }));\n}\n\nfunction getDocAttachmentsFromTargetOrSource(target, src, doc) {\n var doCheckForLocalAttachments = isRemote(src) && !isRemote(target);\n var filenames = Object.keys(doc._attachments);\n\n if (!doCheckForLocalAttachments) {\n return getDocAttachments(src, doc);\n }\n\n return target.get(doc._id).then(function (localDoc) {\n return Promise.all(filenames.map(function (filename) {\n if (fileHasChanged(localDoc, doc, filename)) {\n return src.getAttachment(doc._id, filename);\n }\n\n return target.getAttachment(localDoc._id, filename);\n }));\n }).catch(function (error) {\n /* istanbul ignore if */\n if (error.status !== 404) {\n throw error;\n }\n\n return getDocAttachments(src, doc);\n });\n}\n\nfunction createBulkGetOpts(diffs) {\n var requests = [];\n Object.keys(diffs).forEach(function (id) {\n var missingRevs = diffs[id].missing;\n missingRevs.forEach(function (missingRev) {\n requests.push({\n id: id,\n rev: missingRev\n });\n });\n });\n\n return {\n docs: requests,\n revs: true,\n latest: true\n };\n}\n\n//\n// Fetch all the documents from the src as described in the \"diffs\",\n// which is a mapping of docs IDs to revisions. If the state ever\n// changes to \"cancelled\", then the returned promise will be rejected.\n// Else it will be resolved with a list of fetched documents.\n//\nfunction getDocs(src, target, diffs, state) {\n diffs = clone(diffs); // we do not need to modify this\n\n var resultDocs = [],\n ok = true;\n\n function getAllDocs() {\n\n var bulkGetOpts = createBulkGetOpts(diffs);\n\n if (!bulkGetOpts.docs.length) { // optimization: skip empty requests\n return;\n }\n\n return src.bulkGet(bulkGetOpts).then(function (bulkGetResponse) {\n /* istanbul ignore if */\n if (state.cancelled) {\n throw new Error('cancelled');\n }\n return Promise.all(bulkGetResponse.results.map(function (bulkGetInfo) {\n return Promise.all(bulkGetInfo.docs.map(function (doc) {\n var remoteDoc = doc.ok;\n\n if (doc.error) {\n // when AUTO_COMPACTION is set, docs can be returned which look\n // like this: {\"missing\":\"1-7c3ac256b693c462af8442f992b83696\"}\n ok = false;\n }\n\n if (!remoteDoc || !remoteDoc._attachments) {\n return remoteDoc;\n }\n\n return getDocAttachmentsFromTargetOrSource(target, src, remoteDoc)\n .then(function (attachments) {\n var filenames = Object.keys(remoteDoc._attachments);\n attachments\n .forEach(function (attachment, i) {\n var att = remoteDoc._attachments[filenames[i]];\n delete att.stub;\n delete att.length;\n att.data = attachment;\n });\n\n return remoteDoc;\n });\n }));\n }))\n\n .then(function (results) {\n resultDocs = resultDocs.concat(flatten(results).filter(Boolean));\n });\n });\n }\n\n function hasAttachments(doc) {\n return doc._attachments && Object.keys(doc._attachments).length > 0;\n }\n\n function hasConflicts(doc) {\n return doc._conflicts && doc._conflicts.length > 0;\n }\n\n function fetchRevisionOneDocs(ids) {\n // Optimization: fetch gen-1 docs and attachments in\n // a single request using _all_docs\n return src.allDocs({\n keys: ids,\n include_docs: true,\n conflicts: true\n }).then(function (res) {\n if (state.cancelled) {\n throw new Error('cancelled');\n }\n res.rows.forEach(function (row) {\n if (row.deleted || !row.doc || !isGenOne$1(row.value.rev) ||\n hasAttachments(row.doc) || hasConflicts(row.doc)) {\n // if any of these conditions apply, we need to fetch using get()\n return;\n }\n\n // strip _conflicts array to appease CSG (#5793)\n /* istanbul ignore if */\n if (row.doc._conflicts) {\n delete row.doc._conflicts;\n }\n\n // the doc we got back from allDocs() is sufficient\n resultDocs.push(row.doc);\n delete diffs[row.id];\n });\n });\n }\n\n function getRevisionOneDocs() {\n // filter out the generation 1 docs and get them\n // leaving the non-generation one docs to be got otherwise\n var ids = Object.keys(diffs).filter(function (id) {\n var missing = diffs[id].missing;\n return missing.length === 1 && isGenOne$1(missing[0]);\n });\n if (ids.length > 0) {\n return fetchRevisionOneDocs(ids);\n }\n }\n\n function returnResult() {\n return { ok:ok, docs:resultDocs };\n }\n\n return Promise.resolve()\n .then(getRevisionOneDocs)\n .then(getAllDocs)\n .then(returnResult);\n}\n\nvar CHECKPOINT_VERSION = 1;\nvar REPLICATOR = \"pouchdb\";\n// This is an arbitrary number to limit the\n// amount of replication history we save in the checkpoint.\n// If we save too much, the checkpoing docs will become very big,\n// if we save fewer, we'll run a greater risk of having to\n// read all the changes from 0 when checkpoint PUTs fail\n// CouchDB 2.0 has a more involved history pruning,\n// but let's go for the simple version for now.\nvar CHECKPOINT_HISTORY_SIZE = 5;\nvar LOWEST_SEQ = 0;\n\nfunction updateCheckpoint(db, id, checkpoint, session, returnValue) {\n return db.get(id).catch(function (err) {\n if (err.status === 404) {\n if (db.adapter === 'http' || db.adapter === 'https') {\n explainError(\n 404, 'PouchDB is just checking if a remote checkpoint exists.'\n );\n }\n return {\n session_id: session,\n _id: id,\n history: [],\n replicator: REPLICATOR,\n version: CHECKPOINT_VERSION\n };\n }\n throw err;\n }).then(function (doc) {\n if (returnValue.cancelled) {\n return;\n }\n\n // if the checkpoint has not changed, do not update\n if (doc.last_seq === checkpoint) {\n return;\n }\n\n // Filter out current entry for this replication\n doc.history = (doc.history || []).filter(function (item) {\n return item.session_id !== session;\n });\n\n // Add the latest checkpoint to history\n doc.history.unshift({\n last_seq: checkpoint,\n session_id: session\n });\n\n // Just take the last pieces in history, to\n // avoid really big checkpoint docs.\n // see comment on history size above\n doc.history = doc.history.slice(0, CHECKPOINT_HISTORY_SIZE);\n\n doc.version = CHECKPOINT_VERSION;\n doc.replicator = REPLICATOR;\n\n doc.session_id = session;\n doc.last_seq = checkpoint;\n\n return db.put(doc).catch(function (err) {\n if (err.status === 409) {\n // retry; someone is trying to write a checkpoint simultaneously\n return updateCheckpoint(db, id, checkpoint, session, returnValue);\n }\n throw err;\n });\n });\n}\n\nfunction Checkpointer(src, target, id, returnValue, opts) {\n this.src = src;\n this.target = target;\n this.id = id;\n this.returnValue = returnValue;\n this.opts = opts || {};\n}\n\nCheckpointer.prototype.writeCheckpoint = function (checkpoint, session) {\n var self = this;\n return this.updateTarget(checkpoint, session).then(function () {\n return self.updateSource(checkpoint, session);\n });\n};\n\nCheckpointer.prototype.updateTarget = function (checkpoint, session) {\n if (this.opts.writeTargetCheckpoint) {\n return updateCheckpoint(this.target, this.id, checkpoint,\n session, this.returnValue);\n } else {\n return Promise.resolve(true);\n }\n};\n\nCheckpointer.prototype.updateSource = function (checkpoint, session) {\n if (this.opts.writeSourceCheckpoint) {\n var self = this;\n return updateCheckpoint(this.src, this.id, checkpoint,\n session, this.returnValue)\n .catch(function (err) {\n if (isForbiddenError(err)) {\n self.opts.writeSourceCheckpoint = false;\n return true;\n }\n throw err;\n });\n } else {\n return Promise.resolve(true);\n }\n};\n\nvar comparisons = {\n \"undefined\": function (targetDoc, sourceDoc) {\n // This is the previous comparison function\n if (collate(targetDoc.last_seq, sourceDoc.last_seq) === 0) {\n return sourceDoc.last_seq;\n }\n /* istanbul ignore next */\n return 0;\n },\n \"1\": function (targetDoc, sourceDoc) {\n // This is the comparison function ported from CouchDB\n return compareReplicationLogs(sourceDoc, targetDoc).last_seq;\n }\n};\n\nCheckpointer.prototype.getCheckpoint = function () {\n var self = this;\n\n if (self.opts && self.opts.writeSourceCheckpoint && !self.opts.writeTargetCheckpoint) {\n return self.src.get(self.id).then(function (sourceDoc) {\n return sourceDoc.last_seq || LOWEST_SEQ;\n }).catch(function (err) {\n /* istanbul ignore if */\n if (err.status !== 404) {\n throw err;\n }\n return LOWEST_SEQ;\n });\n }\n\n return self.target.get(self.id).then(function (targetDoc) {\n if (self.opts && self.opts.writeTargetCheckpoint && !self.opts.writeSourceCheckpoint) {\n return targetDoc.last_seq || LOWEST_SEQ;\n }\n\n return self.src.get(self.id).then(function (sourceDoc) {\n // Since we can't migrate an old version doc to a new one\n // (no session id), we just go with the lowest seq in this case\n /* istanbul ignore if */\n if (targetDoc.version !== sourceDoc.version) {\n return LOWEST_SEQ;\n }\n\n var version;\n if (targetDoc.version) {\n version = targetDoc.version.toString();\n } else {\n version = \"undefined\";\n }\n\n if (version in comparisons) {\n return comparisons[version](targetDoc, sourceDoc);\n }\n /* istanbul ignore next */\n return LOWEST_SEQ;\n }, function (err) {\n if (err.status === 404 && targetDoc.last_seq) {\n return self.src.put({\n _id: self.id,\n last_seq: LOWEST_SEQ\n }).then(function () {\n return LOWEST_SEQ;\n }, function (err) {\n if (isForbiddenError(err)) {\n self.opts.writeSourceCheckpoint = false;\n return targetDoc.last_seq;\n }\n /* istanbul ignore next */\n return LOWEST_SEQ;\n });\n }\n throw err;\n });\n }).catch(function (err) {\n if (err.status !== 404) {\n throw err;\n }\n return LOWEST_SEQ;\n });\n};\n// This checkpoint comparison is ported from CouchDBs source\n// they come from here:\n// https://github.com/apache/couchdb-couch-replicator/blob/master/src/couch_replicator.erl#L863-L906\n\nfunction compareReplicationLogs(srcDoc, tgtDoc) {\n if (srcDoc.session_id === tgtDoc.session_id) {\n return {\n last_seq: srcDoc.last_seq,\n history: srcDoc.history\n };\n }\n\n return compareReplicationHistory(srcDoc.history, tgtDoc.history);\n}\n\nfunction compareReplicationHistory(sourceHistory, targetHistory) {\n // the erlang loop via function arguments is not so easy to repeat in JS\n // therefore, doing this as recursion\n var S = sourceHistory[0];\n var sourceRest = sourceHistory.slice(1);\n var T = targetHistory[0];\n var targetRest = targetHistory.slice(1);\n\n if (!S || targetHistory.length === 0) {\n return {\n last_seq: LOWEST_SEQ,\n history: []\n };\n }\n\n var sourceId = S.session_id;\n /* istanbul ignore if */\n if (hasSessionId(sourceId, targetHistory)) {\n return {\n last_seq: S.last_seq,\n history: sourceHistory\n };\n }\n\n var targetId = T.session_id;\n if (hasSessionId(targetId, sourceRest)) {\n return {\n last_seq: T.last_seq,\n history: targetRest\n };\n }\n\n return compareReplicationHistory(sourceRest, targetRest);\n}\n\nfunction hasSessionId(sessionId, history) {\n var props = history[0];\n var rest = history.slice(1);\n\n if (!sessionId || history.length === 0) {\n return false;\n }\n\n if (sessionId === props.session_id) {\n return true;\n }\n\n return hasSessionId(sessionId, rest);\n}\n\nfunction isForbiddenError(err) {\n return typeof err.status === 'number' && Math.floor(err.status / 100) === 4;\n}\n\nvar STARTING_BACK_OFF = 0;\n\nfunction backOff(opts, returnValue, error, callback) {\n if (opts.retry === false) {\n returnValue.emit('error', error);\n returnValue.removeAllListeners();\n return;\n }\n /* istanbul ignore if */\n if (typeof opts.back_off_function !== 'function') {\n opts.back_off_function = defaultBackOff;\n }\n returnValue.emit('requestError', error);\n if (returnValue.state === 'active' || returnValue.state === 'pending') {\n returnValue.emit('paused', error);\n returnValue.state = 'stopped';\n var backOffSet = function backoffTimeSet() {\n opts.current_back_off = STARTING_BACK_OFF;\n };\n var removeBackOffSetter = function removeBackOffTimeSet() {\n returnValue.removeListener('active', backOffSet);\n };\n returnValue.once('paused', removeBackOffSetter);\n returnValue.once('active', backOffSet);\n }\n\n opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;\n opts.current_back_off = opts.back_off_function(opts.current_back_off);\n setTimeout(callback, opts.current_back_off);\n}\n\nfunction sortObjectPropertiesByKey(queryParams) {\n return Object.keys(queryParams).sort(collate).reduce(function (result, key) {\n result[key] = queryParams[key];\n return result;\n }, {});\n}\n\n// Generate a unique id particular to this replication.\n// Not guaranteed to align perfectly with CouchDB's rep ids.\nfunction generateReplicationId(src, target, opts) {\n var docIds = opts.doc_ids ? opts.doc_ids.sort(collate) : '';\n var filterFun = opts.filter ? opts.filter.toString() : '';\n var queryParams = '';\n var filterViewName = '';\n var selector = '';\n\n // possibility for checkpoints to be lost here as behaviour of\n // JSON.stringify is not stable (see #6226)\n /* istanbul ignore if */\n if (opts.selector) {\n selector = JSON.stringify(opts.selector);\n }\n\n if (opts.filter && opts.query_params) {\n queryParams = JSON.stringify(sortObjectPropertiesByKey(opts.query_params));\n }\n\n if (opts.filter && opts.filter === '_view') {\n filterViewName = opts.view.toString();\n }\n\n return Promise.all([src.id(), target.id()]).then(function (res) {\n var queryData = res[0] + res[1] + filterFun + filterViewName +\n queryParams + docIds + selector;\n return new Promise(function (resolve) {\n binaryMd5(queryData, resolve);\n });\n }).then(function (md5sum) {\n // can't use straight-up md5 alphabet, because\n // the char '/' is interpreted as being for attachments,\n // and + is also not url-safe\n md5sum = md5sum.replace(/\\//g, '.').replace(/\\+/g, '_');\n return '_local/' + md5sum;\n });\n}\n\nfunction replicate(src, target, opts, returnValue, result) {\n var batches = []; // list of batches to be processed\n var currentBatch; // the batch currently being processed\n var pendingBatch = {\n seq: 0,\n changes: [],\n docs: []\n }; // next batch, not yet ready to be processed\n var writingCheckpoint = false; // true while checkpoint is being written\n var changesCompleted = false; // true when all changes received\n var replicationCompleted = false; // true when replication has completed\n var last_seq = 0;\n var continuous = opts.continuous || opts.live || false;\n var batch_size = opts.batch_size || 100;\n var batches_limit = opts.batches_limit || 10;\n var changesPending = false; // true while src.changes is running\n var doc_ids = opts.doc_ids;\n var selector = opts.selector;\n var repId;\n var checkpointer;\n var changedDocs = [];\n // Like couchdb, every replication gets a unique session id\n var session = uuid();\n\n result = result || {\n ok: true,\n start_time: new Date().toISOString(),\n docs_read: 0,\n docs_written: 0,\n doc_write_failures: 0,\n errors: []\n };\n\n var changesOpts = {};\n returnValue.ready(src, target);\n\n function initCheckpointer() {\n if (checkpointer) {\n return Promise.resolve();\n }\n return generateReplicationId(src, target, opts).then(function (res) {\n repId = res;\n\n var checkpointOpts = {};\n if (opts.checkpoint === false) {\n checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: false };\n } else if (opts.checkpoint === 'source') {\n checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: false };\n } else if (opts.checkpoint === 'target') {\n checkpointOpts = { writeSourceCheckpoint: false, writeTargetCheckpoint: true };\n } else {\n checkpointOpts = { writeSourceCheckpoint: true, writeTargetCheckpoint: true };\n }\n\n checkpointer = new Checkpointer(src, target, repId, returnValue, checkpointOpts);\n });\n }\n\n function writeDocs() {\n changedDocs = [];\n\n if (currentBatch.docs.length === 0) {\n return;\n }\n var docs = currentBatch.docs;\n var bulkOpts = {timeout: opts.timeout};\n return target.bulkDocs({docs: docs, new_edits: false}, bulkOpts).then(function (res) {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n throw new Error('cancelled');\n }\n\n // `res` doesn't include full documents (which live in `docs`), so we create a map of \n // (id -> error), and check for errors while iterating over `docs`\n var errorsById = Object.create(null);\n res.forEach(function (res) {\n if (res.error) {\n errorsById[res.id] = res;\n }\n });\n\n var errorsNo = Object.keys(errorsById).length;\n result.doc_write_failures += errorsNo;\n result.docs_written += docs.length - errorsNo;\n\n docs.forEach(function (doc) {\n var error = errorsById[doc._id];\n if (error) {\n result.errors.push(error);\n // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)\n var errorName = (error.name || '').toLowerCase();\n if (errorName === 'unauthorized' || errorName === 'forbidden') {\n returnValue.emit('denied', clone(error));\n } else {\n throw error;\n }\n } else {\n changedDocs.push(doc);\n }\n });\n\n }, function (err) {\n result.doc_write_failures += docs.length;\n throw err;\n });\n }\n\n function finishBatch() {\n if (currentBatch.error) {\n throw new Error('There was a problem getting docs.');\n }\n result.last_seq = last_seq = currentBatch.seq;\n var outResult = clone(result);\n if (changedDocs.length) {\n outResult.docs = changedDocs;\n // Attach 'pending' property if server supports it (CouchDB 2.0+)\n /* istanbul ignore if */\n if (typeof currentBatch.pending === 'number') {\n outResult.pending = currentBatch.pending;\n delete currentBatch.pending;\n }\n returnValue.emit('change', outResult);\n }\n writingCheckpoint = true;\n return checkpointer.writeCheckpoint(currentBatch.seq,\n session).then(function () {\n writingCheckpoint = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n throw new Error('cancelled');\n }\n currentBatch = undefined;\n getChanges();\n }).catch(function (err) {\n onCheckpointError(err);\n throw err;\n });\n }\n\n function getDiffs() {\n var diff = {};\n currentBatch.changes.forEach(function (change) {\n // Couchbase Sync Gateway emits these, but we can ignore them\n /* istanbul ignore if */\n if (change.id === \"_user/\") {\n return;\n }\n diff[change.id] = change.changes.map(function (x) {\n return x.rev;\n });\n });\n return target.revsDiff(diff).then(function (diffs) {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n throw new Error('cancelled');\n }\n // currentBatch.diffs elements are deleted as the documents are written\n currentBatch.diffs = diffs;\n });\n }\n\n function getBatchDocs() {\n return getDocs(src, target, currentBatch.diffs, returnValue).then(function (got) {\n currentBatch.error = !got.ok;\n got.docs.forEach(function (doc) {\n delete currentBatch.diffs[doc._id];\n result.docs_read++;\n currentBatch.docs.push(doc);\n });\n });\n }\n\n function startNextBatch() {\n if (returnValue.cancelled || currentBatch) {\n return;\n }\n if (batches.length === 0) {\n processPendingBatch(true);\n return;\n }\n currentBatch = batches.shift();\n getDiffs()\n .then(getBatchDocs)\n .then(writeDocs)\n .then(finishBatch)\n .then(startNextBatch)\n .catch(function (err) {\n abortReplication('batch processing terminated with error', err);\n });\n }\n\n\n function processPendingBatch(immediate) {\n if (pendingBatch.changes.length === 0) {\n if (batches.length === 0 && !currentBatch) {\n if ((continuous && changesOpts.live) || changesCompleted) {\n returnValue.state = 'pending';\n returnValue.emit('paused');\n }\n if (changesCompleted) {\n completeReplication();\n }\n }\n return;\n }\n if (\n immediate ||\n changesCompleted ||\n pendingBatch.changes.length >= batch_size\n ) {\n batches.push(pendingBatch);\n pendingBatch = {\n seq: 0,\n changes: [],\n docs: []\n };\n if (returnValue.state === 'pending' || returnValue.state === 'stopped') {\n returnValue.state = 'active';\n returnValue.emit('active');\n }\n startNextBatch();\n }\n }\n\n\n function abortReplication(reason, err) {\n if (replicationCompleted) {\n return;\n }\n if (!err.message) {\n err.message = reason;\n }\n result.ok = false;\n result.status = 'aborting';\n batches = [];\n pendingBatch = {\n seq: 0,\n changes: [],\n docs: []\n };\n completeReplication(err);\n }\n\n\n function completeReplication(fatalError) {\n if (replicationCompleted) {\n return;\n }\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n result.status = 'cancelled';\n if (writingCheckpoint) {\n return;\n }\n }\n result.status = result.status || 'complete';\n result.end_time = new Date().toISOString();\n result.last_seq = last_seq;\n replicationCompleted = true;\n\n if (fatalError) {\n // need to extend the error because Firefox considers \".result\" read-only\n fatalError = createError(fatalError);\n fatalError.result = result;\n\n // Normalize error name. i.e. 'Unauthorized' -> 'unauthorized' (eg Sync Gateway)\n var errorName = (fatalError.name || '').toLowerCase();\n if (errorName === 'unauthorized' || errorName === 'forbidden') {\n returnValue.emit('error', fatalError);\n returnValue.removeAllListeners();\n } else {\n backOff(opts, returnValue, fatalError, function () {\n replicate(src, target, opts, returnValue);\n });\n }\n } else {\n returnValue.emit('complete', result);\n returnValue.removeAllListeners();\n }\n }\n\n\n function onChange(change, pending, lastSeq) {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n return completeReplication();\n }\n // Attach 'pending' property if server supports it (CouchDB 2.0+)\n /* istanbul ignore if */\n if (typeof pending === 'number') {\n pendingBatch.pending = pending;\n }\n\n var filter = filterChange(opts)(change);\n if (!filter) {\n return;\n }\n pendingBatch.seq = change.seq || lastSeq;\n pendingBatch.changes.push(change);\n nextTick(function () {\n processPendingBatch(batches.length === 0 && changesOpts.live);\n });\n }\n\n\n function onChangesComplete(changes) {\n changesPending = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n return completeReplication();\n }\n\n // if no results were returned then we're done,\n // else fetch more\n if (changes.results.length > 0) {\n changesOpts.since = changes.results[changes.results.length - 1].seq;\n getChanges();\n processPendingBatch(true);\n } else {\n\n var complete = function () {\n if (continuous) {\n changesOpts.live = true;\n getChanges();\n } else {\n changesCompleted = true;\n }\n processPendingBatch(true);\n };\n\n // update the checkpoint so we start from the right seq next time\n if (!currentBatch && changes.results.length === 0) {\n writingCheckpoint = true;\n checkpointer.writeCheckpoint(changes.last_seq,\n session).then(function () {\n writingCheckpoint = false;\n result.last_seq = last_seq = changes.last_seq;\n complete();\n })\n .catch(onCheckpointError);\n } else {\n complete();\n }\n }\n }\n\n\n function onChangesError(err) {\n changesPending = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n return completeReplication();\n }\n abortReplication('changes rejected', err);\n }\n\n\n function getChanges() {\n if (!(\n !changesPending &&\n !changesCompleted &&\n batches.length < batches_limit\n )) {\n return;\n }\n changesPending = true;\n function abortChanges() {\n changes.cancel();\n }\n function removeListener() {\n returnValue.removeListener('cancel', abortChanges);\n }\n\n if (returnValue._changes) { // remove old changes() and listeners\n returnValue.removeListener('cancel', returnValue._abortChanges);\n returnValue._changes.cancel();\n }\n returnValue.once('cancel', abortChanges);\n\n var changes = src.changes(changesOpts)\n .on('change', onChange);\n changes.then(removeListener, removeListener);\n changes.then(onChangesComplete)\n .catch(onChangesError);\n\n if (opts.retry) {\n // save for later so we can cancel if necessary\n returnValue._changes = changes;\n returnValue._abortChanges = abortChanges;\n }\n }\n\n\n function startChanges() {\n initCheckpointer().then(function () {\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n return;\n }\n return checkpointer.getCheckpoint().then(function (checkpoint) {\n last_seq = checkpoint;\n changesOpts = {\n since: last_seq,\n limit: batch_size,\n batch_size: batch_size,\n style: 'all_docs',\n doc_ids: doc_ids,\n selector: selector,\n return_docs: true // required so we know when we're done\n };\n if (opts.filter) {\n if (typeof opts.filter !== 'string') {\n // required for the client-side filter in onChange\n changesOpts.include_docs = true;\n } else { // ddoc filter\n changesOpts.filter = opts.filter;\n }\n }\n if ('heartbeat' in opts) {\n changesOpts.heartbeat = opts.heartbeat;\n }\n if ('timeout' in opts) {\n changesOpts.timeout = opts.timeout;\n }\n if (opts.query_params) {\n changesOpts.query_params = opts.query_params;\n }\n if (opts.view) {\n changesOpts.view = opts.view;\n }\n getChanges();\n });\n }).catch(function (err) {\n abortReplication('getCheckpoint rejected with ', err);\n });\n }\n\n /* istanbul ignore next */\n function onCheckpointError(err) {\n writingCheckpoint = false;\n abortReplication('writeCheckpoint completed with error', err);\n }\n\n /* istanbul ignore if */\n if (returnValue.cancelled) { // cancelled immediately\n completeReplication();\n return;\n }\n\n if (!returnValue._addedListeners) {\n returnValue.once('cancel', completeReplication);\n\n if (typeof opts.complete === 'function') {\n returnValue.once('error', opts.complete);\n returnValue.once('complete', function (result) {\n opts.complete(null, result);\n });\n }\n returnValue._addedListeners = true;\n }\n\n if (typeof opts.since === 'undefined') {\n startChanges();\n } else {\n initCheckpointer().then(function () {\n writingCheckpoint = true;\n return checkpointer.writeCheckpoint(opts.since, session);\n }).then(function () {\n writingCheckpoint = false;\n /* istanbul ignore if */\n if (returnValue.cancelled) {\n completeReplication();\n return;\n }\n last_seq = opts.since;\n startChanges();\n }).catch(onCheckpointError);\n }\n}\n\n// We create a basic promise so the caller can cancel the replication possibly\n// before we have actually started listening to changes etc\ninherits(Replication, EventEmitter);\nfunction Replication() {\n EventEmitter.call(this);\n this.cancelled = false;\n this.state = 'pending';\n var self = this;\n var promise = new Promise(function (fulfill, reject) {\n self.once('complete', fulfill);\n self.once('error', reject);\n });\n self.then = function (resolve, reject) {\n return promise.then(resolve, reject);\n };\n self.catch = function (reject) {\n return promise.catch(reject);\n };\n // As we allow error handling via \"error\" event as well,\n // put a stub in here so that rejecting never throws UnhandledError.\n self.catch(function () {});\n}\n\nReplication.prototype.cancel = function () {\n this.cancelled = true;\n this.state = 'cancelled';\n this.emit('cancel');\n};\n\nReplication.prototype.ready = function (src, target) {\n var self = this;\n if (self._readyCalled) {\n return;\n }\n self._readyCalled = true;\n\n function onDestroy() {\n self.cancel();\n }\n src.once('destroyed', onDestroy);\n target.once('destroyed', onDestroy);\n function cleanup() {\n src.removeListener('destroyed', onDestroy);\n target.removeListener('destroyed', onDestroy);\n }\n self.once('complete', cleanup);\n};\n\nfunction toPouch(db, opts) {\n var PouchConstructor = opts.PouchConstructor;\n if (typeof db === 'string') {\n return new PouchConstructor(db, opts);\n } else {\n return db;\n }\n}\n\nfunction replicateWrapper(src, target, opts, callback) {\n\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n if (typeof opts === 'undefined') {\n opts = {};\n }\n\n if (opts.doc_ids && !Array.isArray(opts.doc_ids)) {\n throw createError(BAD_REQUEST,\n \"`doc_ids` filter parameter is not a list.\");\n }\n\n opts.complete = callback;\n opts = clone(opts);\n opts.continuous = opts.continuous || opts.live;\n opts.retry = ('retry' in opts) ? opts.retry : false;\n /*jshint validthis:true */\n opts.PouchConstructor = opts.PouchConstructor || this;\n var replicateRet = new Replication(opts);\n var srcPouch = toPouch(src, opts);\n var targetPouch = toPouch(target, opts);\n replicate(srcPouch, targetPouch, opts, replicateRet);\n return replicateRet;\n}\n\ninherits(Sync, EventEmitter);\nfunction sync(src, target, opts, callback) {\n if (typeof opts === 'function') {\n callback = opts;\n opts = {};\n }\n if (typeof opts === 'undefined') {\n opts = {};\n }\n opts = clone(opts);\n /*jshint validthis:true */\n opts.PouchConstructor = opts.PouchConstructor || this;\n src = toPouch(src, opts);\n target = toPouch(target, opts);\n return new Sync(src, target, opts, callback);\n}\n\nfunction Sync(src, target, opts, callback) {\n var self = this;\n this.canceled = false;\n\n var optsPush = opts.push ? $inject_Object_assign({}, opts, opts.push) : opts;\n var optsPull = opts.pull ? $inject_Object_assign({}, opts, opts.pull) : opts;\n\n this.push = replicateWrapper(src, target, optsPush);\n this.pull = replicateWrapper(target, src, optsPull);\n\n this.pushPaused = true;\n this.pullPaused = true;\n\n function pullChange(change) {\n self.emit('change', {\n direction: 'pull',\n change: change\n });\n }\n function pushChange(change) {\n self.emit('change', {\n direction: 'push',\n change: change\n });\n }\n function pushDenied(doc) {\n self.emit('denied', {\n direction: 'push',\n doc: doc\n });\n }\n function pullDenied(doc) {\n self.emit('denied', {\n direction: 'pull',\n doc: doc\n });\n }\n function pushPaused() {\n self.pushPaused = true;\n /* istanbul ignore if */\n if (self.pullPaused) {\n self.emit('paused');\n }\n }\n function pullPaused() {\n self.pullPaused = true;\n /* istanbul ignore if */\n if (self.pushPaused) {\n self.emit('paused');\n }\n }\n function pushActive() {\n self.pushPaused = false;\n /* istanbul ignore if */\n if (self.pullPaused) {\n self.emit('active', {\n direction: 'push'\n });\n }\n }\n function pullActive() {\n self.pullPaused = false;\n /* istanbul ignore if */\n if (self.pushPaused) {\n self.emit('active', {\n direction: 'pull'\n });\n }\n }\n\n var removed = {};\n\n function removeAll(type) { // type is 'push' or 'pull'\n return function (event, func) {\n var isChange = event === 'change' &&\n (func === pullChange || func === pushChange);\n var isDenied = event === 'denied' &&\n (func === pullDenied || func === pushDenied);\n var isPaused = event === 'paused' &&\n (func === pullPaused || func === pushPaused);\n var isActive = event === 'active' &&\n (func === pullActive || func === pushActive);\n\n if (isChange || isDenied || isPaused || isActive) {\n if (!(event in removed)) {\n removed[event] = {};\n }\n removed[event][type] = true;\n if (Object.keys(removed[event]).length === 2) {\n // both push and pull have asked to be removed\n self.removeAllListeners(event);\n }\n }\n };\n }\n\n if (opts.live) {\n this.push.on('complete', self.pull.cancel.bind(self.pull));\n this.pull.on('complete', self.push.cancel.bind(self.push));\n }\n\n function addOneListener(ee, event, listener) {\n if (ee.listeners(event).indexOf(listener) == -1) {\n ee.on(event, listener);\n }\n }\n\n this.on('newListener', function (event) {\n if (event === 'change') {\n addOneListener(self.pull, 'change', pullChange);\n addOneListener(self.push, 'change', pushChange);\n } else if (event === 'denied') {\n addOneListener(self.pull, 'denied', pullDenied);\n addOneListener(self.push, 'denied', pushDenied);\n } else if (event === 'active') {\n addOneListener(self.pull, 'active', pullActive);\n addOneListener(self.push, 'active', pushActive);\n } else if (event === 'paused') {\n addOneListener(self.pull, 'paused', pullPaused);\n addOneListener(self.push, 'paused', pushPaused);\n }\n });\n\n this.on('removeListener', function (event) {\n if (event === 'change') {\n self.pull.removeListener('change', pullChange);\n self.push.removeListener('change', pushChange);\n } else if (event === 'denied') {\n self.pull.removeListener('denied', pullDenied);\n self.push.removeListener('denied', pushDenied);\n } else if (event === 'active') {\n self.pull.removeListener('active', pullActive);\n self.push.removeListener('active', pushActive);\n } else if (event === 'paused') {\n self.pull.removeListener('paused', pullPaused);\n self.push.removeListener('paused', pushPaused);\n }\n });\n\n this.pull.on('removeListener', removeAll('pull'));\n this.push.on('removeListener', removeAll('push'));\n\n var promise = Promise.all([\n this.push,\n this.pull\n ]).then(function (resp) {\n var out = {\n push: resp[0],\n pull: resp[1]\n };\n self.emit('complete', out);\n if (callback) {\n callback(null, out);\n }\n self.removeAllListeners();\n return out;\n }, function (err) {\n self.cancel();\n if (callback) {\n // if there's a callback, then the callback can receive\n // the error event\n callback(err);\n } else {\n // if there's no callback, then we're safe to emit an error\n // event, which would otherwise throw an unhandled error\n // due to 'error' being a special event in EventEmitters\n self.emit('error', err);\n }\n self.removeAllListeners();\n if (callback) {\n // no sense throwing if we're already emitting an 'error' event\n throw err;\n }\n });\n\n this.then = function (success, err) {\n return promise.then(success, err);\n };\n\n this.catch = function (err) {\n return promise.catch(err);\n };\n}\n\nSync.prototype.cancel = function () {\n if (!this.canceled) {\n this.canceled = true;\n this.push.cancel();\n this.pull.cancel();\n }\n};\n\nfunction replication(PouchDB) {\n PouchDB.replicate = replicateWrapper;\n PouchDB.sync = sync;\n\n Object.defineProperty(PouchDB.prototype, 'replicate', {\n get: function () {\n var self = this;\n if (typeof this.replicateMethods === 'undefined') {\n this.replicateMethods = {\n from: function (other, opts, callback) {\n return self.constructor.replicate(other, self, opts, callback);\n },\n to: function (other, opts, callback) {\n return self.constructor.replicate(self, other, opts, callback);\n }\n };\n }\n return this.replicateMethods;\n }\n });\n\n PouchDB.prototype.sync = function (dbName, opts, callback) {\n return this.constructor.sync(this, dbName, opts, callback);\n };\n}\n\nPouchDB.plugin(IDBPouch)\n .plugin(HttpPouch$1)\n .plugin(mapreduce)\n .plugin(replication);\n\n// Pull from src because pouchdb-node/pouchdb-browser themselves\n\nexport default PouchDB;\n","import DataUtils,\n{\n REQUEST_TYPE_GET,\n REQUEST_TYPE_PUT,\n REQUEST_TYPE_POST,\n REQUEST_TYPE_DELETE,\n CONTENT_TYPE_JSON,\n CONTENT_TYPE_FORM\n}\nfrom '../../../../brain/tools/utilities/DataUtils';\nimport * as DataEvent from '../../../../brain/tools/events/DataEvent';\nimport DisplayManager from './controllers/DisplayManager';\nimport PouchDB from 'pouchdb';\nexport default class Base\n{\n //--------------------------\n // constructor\n //--------------------------\n //TODO: Flip to unified structure defined in BMG, brah\n constructor()\n {\n var self = this;\n var admin = [];\n var folio = [];\n var displayManager = [];\n this.dataUtils = new DataUtils();\n this.settings = [];\n //this.start();\n this.loadSettings();\n }\n start()\n {\n this.displayManager = new DisplayManager();\n }\n //--------------------------\n // methods\n //--------------------------\n loadSettings()\n {\n var self = this;\n this.dataUtils.request('/api/post', DataEvent.SETTINGS_LOADED).then((response) =>\n {\n //let posts = JSON.parse(response['request'].response);\n var db = new PouchDB('forfipamo');\n \n /** \n self.dataUtils.request(\"/api/post/couch\", DataEvent.POST_IMAGE_ADDED, REQUEST_TYPE_POST, CONTENT_TYPE_JSON, db).then((response) =>\n {\n console.log(JSON.parse(response.request['response']).url);\n }).catch((err) =>\n {\n console.log(err)\n })\n */\n \n var remote = new PouchDB('http://are0h:pa$$@localhost:5984/forfipamo');\n db.sync(remote).then(result=>{\n console.log(result);\n }).catch(err=>{\n console.log(err);\n })\n \n //console.log(posts.length);\n this.start();\n //transfer \n }).catch((err) =>\n {\n //console.log(err);\n });\n }\n //--------------------------\n // event handlers\n //--------------------------\n}","import Base from './Base'\n\ndocument.addEventListener('DOMContentLoaded', function() {\n\n var base = new Base();\n}, false);\n"]} |