From 56f4a3f9401f9ccc34b97a8d0944e606125b7a20 Mon Sep 17 00:00:00 2001 From: Xenia Date: Wed, 17 Apr 2019 15:58:15 +0200 Subject: [PATCH] vuetify eingebunden + erster Versuch Combobox --- node_modules/js-yaml/CHANGELOG.md | 25 + node_modules/js-yaml/README.md | 3 +- node_modules/js-yaml/dist/js-yaml.js | 55 +- node_modules/js-yaml/dist/js-yaml.min.js | 2 +- node_modules/js-yaml/lib/js-yaml/dumper.js | 26 +- node_modules/js-yaml/lib/js-yaml/loader.js | 27 + node_modules/js-yaml/package.json | 24 +- node_modules/mongoose/History.md | 61 + node_modules/mongoose/README.md | 2 +- node_modules/mongoose/lib/document.js | 62 +- .../drivers/node-mongodb-native/collection.js | 2 +- node_modules/mongoose/lib/error/notFound.js | 10 +- .../mongoose/lib/helpers/model/applyHooks.js | 6 +- .../lib/helpers/model/discriminator.js | 20 +- .../lib/helpers/query/castFilterPath.js | 55 + .../lib/helpers/update/castArrayFilters.js | 62 + node_modules/mongoose/lib/index.js | 57 +- node_modules/mongoose/lib/model.js | 102 +- node_modules/mongoose/lib/plugins/sharding.js | 4 + node_modules/mongoose/lib/query.js | 162 +- node_modules/mongoose/lib/queryhelpers.js | 7 +- node_modules/mongoose/lib/schema.js | 26 +- node_modules/mongoose/lib/schema/array.js | 43 +- .../mongoose/lib/schema/documentarray.js | 14 + node_modules/mongoose/lib/schematype.js | 9 +- .../mongoose/lib/types/documentarray.js | 18 +- node_modules/mongoose/lib/utils.js | 24 +- node_modules/mongoose/lib/virtualtype.js | 3 +- .../node_modules/mongodb-core/HISTORY.md | 1085 + .../node_modules/mongodb-core/LICENSE | 201 + .../node_modules/mongodb-core/README.md | 228 + .../node_modules/mongodb-core/index.js | 48 + .../lib/auth/defaultAuthProviders.js | 29 + .../mongodb-core/lib/auth/gssapi.js | 381 + .../mongodb-core/lib/auth/mongocr.js | 214 + .../mongodb-core/lib/auth/plain.js | 183 + .../mongodb-core/lib/auth/scram.js | 442 + .../mongodb-core/lib/auth/sspi.js | 262 + .../mongodb-core/lib/auth/x509.js | 179 + .../mongodb-core/lib/connection/apm.js | 228 + .../lib/connection/command_result.js | 34 + .../mongodb-core/lib/connection/commands.js | 546 + .../mongodb-core/lib/connection/connection.js | 805 + .../mongodb-core/lib/connection/logger.js | 246 + .../mongodb-core/lib/connection/pool.js | 1657 + .../mongodb-core/lib/connection/utils.js | 113 + .../node_modules/mongodb-core/lib/cursor.js | 766 + .../node_modules/mongodb-core/lib/error.js | 146 + .../mongodb-core/lib/sdam/cursor.js | 749 + .../mongodb-core/lib/sdam/monitoring.js | 217 + .../mongodb-core/lib/sdam/server.js | 411 + .../lib/sdam/server_description.js | 141 + .../mongodb-core/lib/sdam/server_selectors.js | 206 + .../mongodb-core/lib/sdam/topology.js | 666 + .../lib/sdam/topology_description.js | 364 + .../node_modules/mongodb-core/lib/sessions.js | 459 + .../mongodb-core/lib/tools/smoke_plugin.js | 61 + .../mongodb-core/lib/topologies/mongos.js | 1504 + .../lib/topologies/read_preference.js | 193 + .../mongodb-core/lib/topologies/replset.js | 1724 + .../lib/topologies/replset_state.js | 1099 + .../mongodb-core/lib/topologies/server.js | 1117 + .../mongodb-core/lib/topologies/shared.js | 434 + .../mongodb-core/lib/transactions.js | 134 + .../mongodb-core/lib/uri_parser.js | 536 + .../node_modules/mongodb-core/lib/utils.js | 97 + .../lib/wireprotocol/2_6_support.js | 267 + .../lib/wireprotocol/3_2_support.js | 397 + .../lib/wireprotocol/compression.js | 73 + .../mongodb-core/lib/wireprotocol/shared.js | 101 + .../node_modules/mongodb-core/package.json | 94 + .../mongoose/node_modules/mongodb/HISTORY.md | 2226 ++ .../mongoose/node_modules/mongodb/LICENSE.md | 201 + .../mongoose/node_modules/mongodb/README.md | 493 + .../mongoose/node_modules/mongodb/index.js | 67 + .../node_modules/mongodb/lib/admin.js | 293 + .../mongodb/lib/aggregation_cursor.js | 407 + .../mongoose/node_modules/mongodb/lib/apm.js | 31 + .../node_modules/mongodb/lib/authenticate.js | 136 + .../node_modules/mongodb/lib/bulk/common.js | 1113 + .../node_modules/mongodb/lib/bulk/ordered.js | 182 + .../mongodb/lib/bulk/unordered.js | 219 + .../node_modules/mongodb/lib/change_stream.js | 469 + .../node_modules/mongodb/lib/collection.js | 2099 ++ .../mongodb/lib/command_cursor.js | 334 + .../node_modules/mongodb/lib/constants.js | 10 + .../node_modules/mongodb/lib/cursor.js | 1152 + .../mongoose/node_modules/mongodb/lib/db.js | 985 + .../node_modules/mongodb/lib/error.js | 43 + .../mongodb/lib/gridfs-stream/download.js | 415 + .../mongodb/lib/gridfs-stream/index.js | 358 + .../mongodb/lib/gridfs-stream/upload.js | 538 + .../node_modules/mongodb/lib/gridfs/chunk.js | 236 + .../mongodb/lib/gridfs/grid_store.js | 1907 ++ .../node_modules/mongodb/lib/mongo_client.js | 472 + .../mongodb/lib/operations/admin_ops.js | 62 + .../mongodb/lib/operations/collection_ops.js | 1494 + .../mongodb/lib/operations/cursor_ops.js | 250 + .../mongodb/lib/operations/db_ops.js | 1006 + .../lib/operations/mongo_client_ops.js | 654 + .../mongodb/lib/topologies/mongos.js | 452 + .../mongodb/lib/topologies/replset.js | 497 + .../mongodb/lib/topologies/server.js | 455 + .../mongodb/lib/topologies/topology_base.js | 446 + .../node_modules/mongodb/lib/url_parser.js | 622 + .../node_modules/mongodb/lib/utils.js | 723 + .../node_modules/mongodb/package.json | 91 + node_modules/mongoose/package.json | 52 +- node_modules/mongoose/search.js | 92 + node_modules/vue/README.md | 191 +- node_modules/vue/dist/README.md | 4 +- node_modules/vue/dist/vue.common.dev.js | 11938 +++++++ node_modules/vue/dist/vue.common.js | 10961 +------ node_modules/vue/dist/vue.common.prod.js | 6 + node_modules/vue/dist/vue.esm.browser.js | 5238 ++-- node_modules/vue/dist/vue.esm.browser.min.js | 6 + node_modules/vue/dist/vue.esm.js | 4586 +-- node_modules/vue/dist/vue.js | 21629 +++++++------ node_modules/vue/dist/vue.min.js | 6 +- .../vue/dist/vue.runtime.common.dev.js | 8417 +++++ node_modules/vue/dist/vue.runtime.common.js | 8035 +---- .../vue/dist/vue.runtime.common.prod.js | 6 + node_modules/vue/dist/vue.runtime.esm.js | 3343 +- node_modules/vue/dist/vue.runtime.js | 15688 +++++----- node_modules/vue/dist/vue.runtime.min.js | 6 +- node_modules/vue/package.json | 97 +- node_modules/vue/src/compiler/codeframe.js | 50 + .../vue/src/compiler/codegen/events.js | 57 +- .../vue/src/compiler/codegen/index.js | 205 +- .../vue/src/compiler/create-compiler.js | 26 +- .../vue/src/compiler/directives/model.js | 2 +- .../vue/src/compiler/error-detector.js | 57 +- node_modules/vue/src/compiler/helpers.js | 131 +- node_modules/vue/src/compiler/optimizer.js | 2 +- .../vue/src/compiler/parser/html-parser.js | 56 +- node_modules/vue/src/compiler/parser/index.js | 618 +- .../vue/src/compiler/parser/text-parser.js | 2 +- node_modules/vue/src/compiler/to-function.js | 27 +- node_modules/vue/src/core/config.js | 9 + node_modules/vue/src/core/global-api/index.js | 7 + node_modules/vue/src/core/instance/events.js | 53 +- node_modules/vue/src/core/instance/init.js | 24 +- node_modules/vue/src/core/instance/inject.js | 7 +- .../vue/src/core/instance/lifecycle.js | 68 +- node_modules/vue/src/core/instance/proxy.js | 19 +- .../render-helpers/bind-dynamic-keys.js | 35 + .../render-helpers/bind-object-props.js | 8 +- .../src/core/instance/render-helpers/index.js | 5 +- .../instance/render-helpers/render-list.js | 27 +- .../instance/render-helpers/render-slot.js | 14 +- .../render-helpers/resolve-scoped-slots.js | 27 + .../instance/render-helpers/resolve-slots.js | 21 +- node_modules/vue/src/core/instance/render.js | 46 +- node_modules/vue/src/core/instance/state.js | 30 +- node_modules/vue/src/core/observer/dep.js | 22 +- node_modules/vue/src/core/observer/index.js | 25 +- .../vue/src/core/observer/scheduler.js | 46 +- node_modules/vue/src/core/observer/watcher.js | 7 +- node_modules/vue/src/core/util/debug.js | 2 +- node_modules/vue/src/core/util/env.js | 4 +- node_modules/vue/src/core/util/error.js | 61 +- node_modules/vue/src/core/util/lang.js | 9 +- node_modules/vue/src/core/util/next-tick.js | 119 +- node_modules/vue/src/core/util/options.js | 58 +- node_modules/vue/src/core/util/perf.js | 2 +- node_modules/vue/src/core/util/props.js | 45 +- .../vue/src/core/vdom/create-component.js | 51 +- .../vue/src/core/vdom/create-element.js | 2 +- .../core/vdom/create-functional-component.js | 29 +- .../vdom/helpers/normalize-scoped-slots.js | 84 + .../vdom/helpers/resolve-async-component.js | 61 +- .../src/core/vdom/helpers/update-listeners.js | 26 +- .../vue/src/core/vdom/modules/directives.js | 1 + node_modules/vue/src/core/vdom/patch.js | 38 +- node_modules/vue/src/core/vdom/vnode.js | 7 +- .../platforms/web/compiler/directives/html.js | 2 +- .../web/compiler/directives/model.js | 9 +- .../platforms/web/compiler/directives/text.js | 2 +- .../platforms/web/compiler/modules/class.js | 3 +- .../platforms/web/compiler/modules/style.js | 3 +- .../vue/src/platforms/web/entry-compiler.js | 1 + .../web/entry-runtime-with-compiler.js | 1 + .../src/platforms/web/runtime/class-util.js | 6 +- .../runtime/components/transition-group.js | 36 +- .../web/runtime/components/transition.js | 8 +- .../vue/src/platforms/web/runtime/index.js | 5 +- .../platforms/web/runtime/modules/attrs.js | 7 +- .../web/runtime/modules/dom-props.js | 37 +- .../platforms/web/runtime/modules/events.js | 55 +- .../platforms/web/runtime/modules/style.js | 4 +- .../web/runtime/modules/transition.js | 4 +- .../platforms/web/runtime/transition-util.js | 15 +- .../src/platforms/web/server/modules/attrs.js | 5 +- .../src/platforms/web/server/modules/style.js | 19 +- .../vue/src/platforms/web/server/util.js | 47 +- .../vue/src/platforms/web/util/attrs.js | 11 + .../vue/src/platforms/web/util/style.js | 3 +- .../weex/compiler/directives/model.js | 3 +- .../platforms/weex/compiler/modules/append.js | 2 +- .../platforms/weex/compiler/modules/class.js | 3 +- .../platforms/weex/compiler/modules/props.js | 7 +- .../modules/recycle-list/component-root.js | 5 +- .../compiler/modules/recycle-list/index.js | 10 +- .../compiler/modules/recycle-list/text.js | 2 +- .../compiler/modules/recycle-list/v-bind.js | 2 +- .../compiler/modules/recycle-list/v-on.js | 2 +- .../compiler/modules/recycle-list/v-once.js | 2 +- .../platforms/weex/compiler/modules/style.js | 3 +- .../vue/src/platforms/weex/entry-compiler.js | 1 + .../platforms/weex/runtime/modules/class.js | 41 +- .../platforms/weex/runtime/modules/events.js | 25 +- .../platforms/weex/runtime/modules/style.js | 2 +- .../weex/runtime/modules/transition.js | 4 +- .../vue/src/platforms/weex/util/element.js | 10 +- .../vue/src/server/create-renderer.js | 46 +- .../src/server/optimizing-compiler/codegen.js | 6 +- .../src/server/optimizing-compiler/modules.js | 10 +- .../server/optimizing-compiler/optimizer.js | 1 + node_modules/vue/src/server/render-context.js | 92 +- node_modules/vue/src/server/render-stream.js | 1 + node_modules/vue/src/server/render.js | 69 +- .../create-async-file-mapper.js | 4 +- .../vue/src/server/template-renderer/index.js | 60 +- .../vue/src/server/webpack-plugin/client.js | 17 +- .../vue/src/server/webpack-plugin/server.js | 6 +- .../vue/src/server/webpack-plugin/util.js | 10 + node_modules/vue/src/server/write.js | 2 +- node_modules/vue/src/sfc/parser.js | 40 +- node_modules/vue/src/shared/constants.js | 3 +- node_modules/vue/src/shared/util.js | 53 +- node_modules/vue/types/index.d.ts | 3 + node_modules/vue/types/options.d.ts | 44 +- node_modules/vue/types/vnode.d.ts | 33 +- node_modules/vue/types/vue.d.ts | 28 +- node_modules/vuetify/LICENSE.md | 21 + node_modules/vuetify/dist/vuetify.css | 10652 +++++++ node_modules/vuetify/dist/vuetify.css.map | 1 + node_modules/vuetify/dist/vuetify.js | 25973 ++++++++++++++++ node_modules/vuetify/dist/vuetify.js.map | 1 + node_modules/vuetify/dist/vuetify.min.css | 5 + node_modules/vuetify/dist/vuetify.min.js | 6 + .../vuetify/es5/components/VAlert/VAlert.js | 114 + .../es5/components/VAlert/VAlert.js.map | 1 + .../vuetify/es5/components/VAlert/index.js | 16 + .../es5/components/VAlert/index.js.map | 1 + .../vuetify/es5/components/VApp/VApp.js | 69 + .../vuetify/es5/components/VApp/VApp.js.map | 1 + .../vuetify/es5/components/VApp/index.js | 16 + .../vuetify/es5/components/VApp/index.js.map | 1 + .../es5/components/VApp/mixins/app-theme.js | 107 + .../components/VApp/mixins/app-theme.js.map | 1 + .../components/VAutocomplete/VAutocomplete.js | 323 + .../VAutocomplete/VAutocomplete.js.map | 1 + .../es5/components/VAutocomplete/index.js | 16 + .../es5/components/VAutocomplete/index.js.map | 1 + .../vuetify/es5/components/VAvatar/VAvatar.js | 53 + .../es5/components/VAvatar/VAvatar.js.map | 1 + .../vuetify/es5/components/VAvatar/index.js | 16 + .../es5/components/VAvatar/index.js.map | 1 + .../vuetify/es5/components/VBadge/VBadge.js | 79 + .../es5/components/VBadge/VBadge.js.map | 1 + .../vuetify/es5/components/VBadge/index.js | 16 + .../es5/components/VBadge/index.js.map | 1 + .../es5/components/VBottomNav/VBottomNav.js | 88 + .../components/VBottomNav/VBottomNav.js.map | 1 + .../es5/components/VBottomNav/index.js | 16 + .../es5/components/VBottomNav/index.js.map | 1 + .../components/VBottomSheet/VBottomSheet.js | 50 + .../VBottomSheet/VBottomSheet.js.map | 1 + .../es5/components/VBottomSheet/index.js | 16 + .../es5/components/VBottomSheet/index.js.map | 1 + .../components/VBreadcrumbs/VBreadcrumbs.js | 110 + .../VBreadcrumbs/VBreadcrumbs.js.map | 1 + .../VBreadcrumbs/VBreadcrumbsItem.js | 45 + .../VBreadcrumbs/VBreadcrumbsItem.js.map | 1 + .../es5/components/VBreadcrumbs/index.js | 31 + .../es5/components/VBreadcrumbs/index.js.map | 1 + .../vuetify/es5/components/VBtn/VBtn.js | 153 + .../vuetify/es5/components/VBtn/VBtn.js.map | 1 + .../vuetify/es5/components/VBtn/index.js | 16 + .../vuetify/es5/components/VBtn/index.js.map | 1 + .../es5/components/VBtnToggle/VBtnToggle.js | 39 + .../components/VBtnToggle/VBtnToggle.js.map | 1 + .../es5/components/VBtnToggle/index.js | 16 + .../es5/components/VBtnToggle/index.js.map | 1 + .../es5/components/VCalendar/VCalendar.js | 209 + .../es5/components/VCalendar/VCalendar.js.map | 1 + .../components/VCalendar/VCalendarDaily.js | 218 + .../VCalendar/VCalendarDaily.js.map | 1 + .../components/VCalendar/VCalendarMonthly.js | 36 + .../VCalendar/VCalendarMonthly.js.map | 1 + .../components/VCalendar/VCalendarWeekly.js | 151 + .../VCalendar/VCalendarWeekly.js.map | 1 + .../vuetify/es5/components/VCalendar/index.js | 38 + .../es5/components/VCalendar/index.js.map | 1 + .../VCalendar/mixins/calendar-base.js | 93 + .../VCalendar/mixins/calendar-base.js.map | 1 + .../mixins/calendar-with-intervals.js | 132 + .../mixins/calendar-with-intervals.js.map | 1 + .../es5/components/VCalendar/mixins/mouse.js | 67 + .../components/VCalendar/mixins/mouse.js.map | 1 + .../es5/components/VCalendar/mixins/times.js | 77 + .../components/VCalendar/mixins/times.js.map | 1 + .../es5/components/VCalendar/util/props.js | 125 + .../components/VCalendar/util/props.js.map | 1 + .../components/VCalendar/util/timestamp.js | 372 + .../VCalendar/util/timestamp.js.map | 1 + .../vuetify/es5/components/VCard/VCard.js | 66 + .../vuetify/es5/components/VCard/VCard.js.map | 1 + .../es5/components/VCard/VCardMedia.js | 25 + .../es5/components/VCard/VCardMedia.js.map | 1 + .../es5/components/VCard/VCardTitle.js | 30 + .../es5/components/VCard/VCardTitle.js.map | 1 + .../vuetify/es5/components/VCard/index.js | 40 + .../vuetify/es5/components/VCard/index.js.map | 1 + .../es5/components/VCarousel/VCarousel.js | 237 + .../es5/components/VCarousel/VCarousel.js.map | 1 + .../es5/components/VCarousel/VCarouselItem.js | 41 + .../components/VCarousel/VCarouselItem.js.map | 1 + .../vuetify/es5/components/VCarousel/index.js | 26 + .../es5/components/VCarousel/index.js.map | 1 + .../es5/components/VCheckbox/VCheckbox.js | 91 + .../es5/components/VCheckbox/VCheckbox.js.map | 1 + .../vuetify/es5/components/VCheckbox/index.js | 16 + .../es5/components/VCheckbox/index.js.map | 1 + .../vuetify/es5/components/VChip/VChip.js | 102 + .../vuetify/es5/components/VChip/VChip.js.map | 1 + .../vuetify/es5/components/VChip/index.js | 16 + .../vuetify/es5/components/VChip/index.js.map | 1 + .../es5/components/VCombobox/VCombobox.js | 198 + .../es5/components/VCombobox/VCombobox.js.map | 1 + .../vuetify/es5/components/VCombobox/index.js | 16 + .../es5/components/VCombobox/index.js.map | 1 + .../es5/components/VCounter/VCounter.js | 50 + .../es5/components/VCounter/VCounter.js.map | 1 + .../vuetify/es5/components/VCounter/index.js | 16 + .../es5/components/VCounter/index.js.map | 1 + .../components/VDataIterator/VDataIterator.js | 103 + .../VDataIterator/VDataIterator.js.map | 1 + .../es5/components/VDataIterator/index.js | 16 + .../es5/components/VDataIterator/index.js.map | 1 + .../es5/components/VDataTable/VDataTable.js | 132 + .../components/VDataTable/VDataTable.js.map | 1 + .../es5/components/VDataTable/VEditDialog.js | 142 + .../components/VDataTable/VEditDialog.js.map | 1 + .../es5/components/VDataTable/index.js | 31 + .../es5/components/VDataTable/index.js.map | 1 + .../es5/components/VDataTable/mixins/body.js | 77 + .../components/VDataTable/mixins/body.js.map | 1 + .../es5/components/VDataTable/mixins/foot.js | 27 + .../components/VDataTable/mixins/foot.js.map | 1 + .../es5/components/VDataTable/mixins/head.js | 142 + .../components/VDataTable/mixins/head.js.map | 1 + .../components/VDataTable/mixins/progress.js | 22 + .../VDataTable/mixins/progress.js.map | 1 + .../es5/components/VDatePicker/VDatePicker.js | 498 + .../components/VDatePicker/VDatePicker.js.map | 1 + .../VDatePicker/VDatePickerDateTable.js | 118 + .../VDatePicker/VDatePickerDateTable.js.map | 1 + .../VDatePicker/VDatePickerHeader.js | 162 + .../VDatePicker/VDatePickerHeader.js.map | 1 + .../VDatePicker/VDatePickerMonthTable.js | 63 + .../VDatePicker/VDatePickerMonthTable.js.map | 1 + .../VDatePicker/VDatePickerTitle.js | 99 + .../VDatePicker/VDatePickerTitle.js.map | 1 + .../VDatePicker/VDatePickerYears.js | 97 + .../VDatePicker/VDatePickerYears.js.map | 1 + .../es5/components/VDatePicker/index.js | 50 + .../es5/components/VDatePicker/index.js.map | 1 + .../VDatePicker/mixins/date-picker-table.js | 222 + .../mixins/date-picker-table.js.map | 1 + .../util/createNativeLocaleFormatter.js | 39 + .../util/createNativeLocaleFormatter.js.map | 1 + .../es5/components/VDatePicker/util/index.js | 25 + .../components/VDatePicker/util/index.js.map | 1 + .../VDatePicker/util/isDateAllowed.js | 10 + .../VDatePicker/util/isDateAllowed.js.map | 1 + .../VDatePicker/util/monthChange.js | 33 + .../VDatePicker/util/monthChange.js.map | 1 + .../es5/components/VDatePicker/util/pad.js | 24 + .../components/VDatePicker/util/pad.js.map | 1 + .../vuetify/es5/components/VDialog/VDialog.js | 343 + .../es5/components/VDialog/VDialog.js.map | 1 + .../vuetify/es5/components/VDialog/index.js | 16 + .../es5/components/VDialog/index.js.map | 1 + .../es5/components/VDivider/VDivider.js | 38 + .../es5/components/VDivider/VDivider.js.map | 1 + .../vuetify/es5/components/VDivider/index.js | 16 + .../es5/components/VDivider/index.js.map | 1 + .../VExpansionPanel/VExpansionPanel.js | 136 + .../VExpansionPanel/VExpansionPanel.js.map | 1 + .../VExpansionPanel/VExpansionPanelContent.js | 149 + .../VExpansionPanelContent.js.map | 1 + .../es5/components/VExpansionPanel/index.js | 26 + .../components/VExpansionPanel/index.js.map | 1 + .../vuetify/es5/components/VFooter/VFooter.js | 94 + .../es5/components/VFooter/VFooter.js.map | 1 + .../vuetify/es5/components/VFooter/index.js | 16 + .../es5/components/VFooter/index.js.map | 1 + .../vuetify/es5/components/VForm/VForm.js | 145 + .../vuetify/es5/components/VForm/VForm.js.map | 1 + .../vuetify/es5/components/VForm/index.js | 16 + .../vuetify/es5/components/VForm/index.js.map | 1 + .../es5/components/VGrid/VContainer.js | 16 + .../es5/components/VGrid/VContainer.js.map | 1 + .../vuetify/es5/components/VGrid/VContent.js | 55 + .../es5/components/VGrid/VContent.js.map | 1 + .../vuetify/es5/components/VGrid/VFlex.js | 16 + .../vuetify/es5/components/VGrid/VFlex.js.map | 1 + .../vuetify/es5/components/VGrid/VLayout.js | 16 + .../es5/components/VGrid/VLayout.js.map | 1 + .../vuetify/es5/components/VGrid/grid.js | 53 + .../vuetify/es5/components/VGrid/grid.js.map | 1 + .../vuetify/es5/components/VGrid/index.js | 43 + .../vuetify/es5/components/VGrid/index.js.map | 1 + .../vuetify/es5/components/VHover/VHover.js | 75 + .../es5/components/VHover/VHover.js.map | 1 + .../vuetify/es5/components/VHover/index.js | 16 + .../es5/components/VHover/index.js.map | 1 + .../vuetify/es5/components/VIcon/VIcon.js | 170 + .../vuetify/es5/components/VIcon/VIcon.js.map | 1 + .../vuetify/es5/components/VIcon/index.js | 16 + .../vuetify/es5/components/VIcon/index.js.map | 1 + .../vuetify/es5/components/VImg/VImg.js | 193 + .../vuetify/es5/components/VImg/VImg.js.map | 1 + .../vuetify/es5/components/VImg/index.js | 16 + .../vuetify/es5/components/VImg/index.js.map | 1 + .../vuetify/es5/components/VInput/VInput.js | 282 + .../es5/components/VInput/VInput.js.map | 1 + .../vuetify/es5/components/VInput/index.js | 16 + .../es5/components/VInput/index.js.map | 1 + .../es5/components/VItemGroup/VItem.js | 57 + .../es5/components/VItemGroup/VItem.js.map | 1 + .../es5/components/VItemGroup/VItemGroup.js | 211 + .../components/VItemGroup/VItemGroup.js.map | 1 + .../es5/components/VItemGroup/index.js | 26 + .../es5/components/VItemGroup/index.js.map | 1 + .../es5/components/VJumbotron/VJumbotron.js | 101 + .../components/VJumbotron/VJumbotron.js.map | 1 + .../es5/components/VJumbotron/index.js | 16 + .../es5/components/VJumbotron/index.js.map | 1 + .../vuetify/es5/components/VLabel/VLabel.js | 80 + .../es5/components/VLabel/VLabel.js.map | 1 + .../vuetify/es5/components/VLabel/index.js | 16 + .../es5/components/VLabel/index.js.map | 1 + .../vuetify/es5/components/VList/VList.js | 109 + .../vuetify/es5/components/VList/VList.js.map | 1 + .../es5/components/VList/VListGroup.js | 170 + .../es5/components/VList/VListGroup.js.map | 1 + .../vuetify/es5/components/VList/VListTile.js | 103 + .../es5/components/VList/VListTile.js.map | 1 + .../es5/components/VList/VListTileAction.js | 30 + .../components/VList/VListTileAction.js.map | 1 + .../es5/components/VList/VListTileAvatar.js | 47 + .../components/VList/VListTileAvatar.js.map | 1 + .../vuetify/es5/components/VList/index.js | 54 + .../vuetify/es5/components/VList/index.js.map | 1 + .../vuetify/es5/components/VMenu/VMenu.js | 256 + .../vuetify/es5/components/VMenu/VMenu.js.map | 1 + .../vuetify/es5/components/VMenu/index.js | 16 + .../vuetify/es5/components/VMenu/index.js.map | 1 + .../components/VMenu/mixins/menu-activator.js | 63 + .../VMenu/mixins/menu-activator.js.map | 1 + .../VMenu/mixins/menu-generators.js | 104 + .../VMenu/mixins/menu-generators.js.map | 1 + .../components/VMenu/mixins/menu-keyable.js | 87 + .../VMenu/mixins/menu-keyable.js.map | 1 + .../components/VMenu/mixins/menu-position.js | 48 + .../VMenu/mixins/menu-position.js.map | 1 + .../es5/components/VMessages/VMessages.js | 63 + .../es5/components/VMessages/VMessages.js.map | 1 + .../vuetify/es5/components/VMessages/index.js | 16 + .../es5/components/VMessages/index.js.map | 1 + .../VNavigationDrawer/VNavigationDrawer.js | 320 + .../VNavigationDrawer.js.map | 1 + .../es5/components/VNavigationDrawer/index.js | 16 + .../components/VNavigationDrawer/index.js.map | 1 + .../components/VOverflowBtn/VOverflowBtn.js | 106 + .../VOverflowBtn/VOverflowBtn.js.map | 1 + .../es5/components/VOverflowBtn/index.js | 16 + .../es5/components/VOverflowBtn/index.js.map | 1 + .../es5/components/VPagination/VPagination.js | 198 + .../components/VPagination/VPagination.js.map | 1 + .../es5/components/VPagination/index.js | 16 + .../es5/components/VPagination/index.js.map | 1 + .../es5/components/VParallax/VParallax.js | 103 + .../es5/components/VParallax/VParallax.js.map | 1 + .../vuetify/es5/components/VParallax/index.js | 16 + .../es5/components/VParallax/index.js.map | 1 + .../vuetify/es5/components/VPicker/VPicker.js | 95 + .../es5/components/VPicker/VPicker.js.map | 1 + .../vuetify/es5/components/VPicker/index.js | 16 + .../es5/components/VPicker/index.js.map | 1 + .../VProgressCircular/VProgressCircular.js | 136 + .../VProgressCircular.js.map | 1 + .../es5/components/VProgressCircular/index.js | 16 + .../components/VProgressCircular/index.js.map | 1 + .../VProgressLinear/VProgressLinear.js | 166 + .../VProgressLinear/VProgressLinear.js.map | 1 + .../es5/components/VProgressLinear/index.js | 16 + .../components/VProgressLinear/index.js.map | 1 + .../es5/components/VRadioGroup/VRadio.js | 169 + .../es5/components/VRadioGroup/VRadio.js.map | 1 + .../es5/components/VRadioGroup/VRadioGroup.js | 137 + .../components/VRadioGroup/VRadioGroup.js.map | 1 + .../es5/components/VRadioGroup/index.js | 26 + .../es5/components/VRadioGroup/index.js.map | 1 + .../components/VRangeSlider/VRangeSlider.js | 161 + .../VRangeSlider/VRangeSlider.js.map | 1 + .../es5/components/VRangeSlider/index.js | 16 + .../es5/components/VRangeSlider/index.js.map | 1 + .../vuetify/es5/components/VRating/VRating.js | 238 + .../es5/components/VRating/VRating.js.map | 1 + .../vuetify/es5/components/VRating/index.js | 16 + .../es5/components/VRating/index.js.map | 1 + .../es5/components/VResponsive/VResponsive.js | 58 + .../components/VResponsive/VResponsive.js.map | 1 + .../es5/components/VResponsive/index.js | 16 + .../es5/components/VResponsive/index.js.map | 1 + .../vuetify/es5/components/VSelect/VSelect.js | 725 + .../es5/components/VSelect/VSelect.js.map | 1 + .../es5/components/VSelect/VSelectList.js | 255 + .../es5/components/VSelect/VSelectList.js.map | 1 + .../vuetify/es5/components/VSelect/index.js | 102 + .../es5/components/VSelect/index.js.map | 1 + .../vuetify/es5/components/VSheet/VSheet.js | 68 + .../es5/components/VSheet/VSheet.js.map | 1 + .../vuetify/es5/components/VSheet/index.js | 16 + .../es5/components/VSheet/index.js.map | 1 + .../vuetify/es5/components/VSlider/VSlider.js | 477 + .../es5/components/VSlider/VSlider.js.map | 1 + .../vuetify/es5/components/VSlider/index.js | 16 + .../es5/components/VSlider/index.js.map | 1 + .../es5/components/VSnackbar/VSnackbar.js | 95 + .../es5/components/VSnackbar/VSnackbar.js.map | 1 + .../vuetify/es5/components/VSnackbar/index.js | 16 + .../es5/components/VSnackbar/index.js.map | 1 + .../es5/components/VSparkline/VSparkline.js | 366 + .../components/VSparkline/VSparkline.js.map | 1 + .../es5/components/VSparkline/helpers/core.js | 34 + .../components/VSparkline/helpers/core.js.map | 1 + .../es5/components/VSparkline/helpers/math.js | 32 + .../components/VSparkline/helpers/math.js.map | 1 + .../es5/components/VSparkline/helpers/path.js | 34 + .../components/VSparkline/helpers/path.js.map | 1 + .../es5/components/VSparkline/index.js | 16 + .../es5/components/VSparkline/index.js.map | 1 + .../es5/components/VSpeedDial/VSpeedDial.js | 116 + .../components/VSpeedDial/VSpeedDial.js.map | 1 + .../es5/components/VSpeedDial/index.js | 16 + .../es5/components/VSpeedDial/index.js.map | 1 + .../es5/components/VStepper/VStepper.js | 125 + .../es5/components/VStepper/VStepper.js.map | 1 + .../components/VStepper/VStepperContent.js | 146 + .../VStepper/VStepperContent.js.map | 1 + .../es5/components/VStepper/VStepperStep.js | 141 + .../components/VStepper/VStepperStep.js.map | 1 + .../vuetify/es5/components/VStepper/index.js | 40 + .../es5/components/VStepper/index.js.map | 1 + .../es5/components/VSubheader/VSubheader.js | 42 + .../components/VSubheader/VSubheader.js.map | 1 + .../es5/components/VSubheader/index.js | 16 + .../es5/components/VSubheader/index.js.map | 1 + .../vuetify/es5/components/VSwitch/VSwitch.js | 104 + .../es5/components/VSwitch/VSwitch.js.map | 1 + .../vuetify/es5/components/VSwitch/index.js | 16 + .../es5/components/VSwitch/index.js.map | 1 + .../es5/components/VSystemBar/VSystemBar.js | 80 + .../components/VSystemBar/VSystemBar.js.map | 1 + .../es5/components/VSystemBar/index.js | 16 + .../es5/components/VSystemBar/index.js.map | 1 + .../vuetify/es5/components/VTabs/VTab.js | 96 + .../vuetify/es5/components/VTabs/VTab.js.map | 1 + .../vuetify/es5/components/VTabs/VTabItem.js | 35 + .../es5/components/VTabs/VTabItem.js.map | 1 + .../vuetify/es5/components/VTabs/VTabs.js | 264 + .../vuetify/es5/components/VTabs/VTabs.js.map | 1 + .../es5/components/VTabs/VTabsItems.js | 68 + .../es5/components/VTabs/VTabsItems.js.map | 1 + .../es5/components/VTabs/VTabsSlider.js | 23 + .../es5/components/VTabs/VTabsSlider.js.map | 1 + .../vuetify/es5/components/VTabs/index.js | 44 + .../vuetify/es5/components/VTabs/index.js.map | 1 + .../components/VTabs/mixins/tabs-computed.js | 38 + .../VTabs/mixins/tabs-computed.js.map | 1 + .../VTabs/mixins/tabs-generators.js | 116 + .../VTabs/mixins/tabs-generators.js.map | 1 + .../es5/components/VTabs/mixins/tabs-props.js | 59 + .../components/VTabs/mixins/tabs-props.js.map | 1 + .../es5/components/VTabs/mixins/tabs-touch.js | 45 + .../components/VTabs/mixins/tabs-touch.js.map | 1 + .../components/VTabs/mixins/tabs-watchers.js | 52 + .../VTabs/mixins/tabs-watchers.js.map | 1 + .../es5/components/VTextField/VTextField.js | 397 + .../components/VTextField/VTextField.js.map | 1 + .../es5/components/VTextField/index.js | 61 + .../es5/components/VTextField/index.js.map | 1 + .../es5/components/VTextarea/VTextarea.js | 115 + .../es5/components/VTextarea/VTextarea.js.map | 1 + .../vuetify/es5/components/VTextarea/index.js | 16 + .../es5/components/VTextarea/index.js.map | 1 + .../es5/components/VTimePicker/VTimePicker.js | 336 + .../components/VTimePicker/VTimePicker.js.map | 1 + .../VTimePicker/VTimePickerClock.js | 258 + .../VTimePicker/VTimePickerClock.js.map | 1 + .../VTimePicker/VTimePickerTitle.js | 77 + .../VTimePicker/VTimePickerTitle.js.map | 1 + .../es5/components/VTimePicker/index.js | 32 + .../es5/components/VTimePicker/index.js.map | 1 + .../es5/components/VTimeline/VTimeline.js | 47 + .../es5/components/VTimeline/VTimeline.js.map | 1 + .../es5/components/VTimeline/VTimelineItem.js | 108 + .../components/VTimeline/VTimelineItem.js.map | 1 + .../vuetify/es5/components/VTimeline/index.js | 26 + .../es5/components/VTimeline/index.js.map | 1 + .../es5/components/VToolbar/VToolbar.js | 238 + .../es5/components/VToolbar/VToolbar.js.map | 1 + .../components/VToolbar/VToolbarSideIcon.js | 43 + .../VToolbar/VToolbarSideIcon.js.map | 1 + .../vuetify/es5/components/VToolbar/index.js | 34 + .../es5/components/VToolbar/index.js.map | 1 + .../es5/components/VTooltip/VTooltip.js | 218 + .../es5/components/VTooltip/VTooltip.js.map | 1 + .../vuetify/es5/components/VTooltip/index.js | 16 + .../es5/components/VTooltip/index.js.map | 1 + .../es5/components/VTreeview/VTreeview.js | 415 + .../es5/components/VTreeview/VTreeview.js.map | 1 + .../es5/components/VTreeview/VTreeviewNode.js | 294 + .../components/VTreeview/VTreeviewNode.js.map | 1 + .../vuetify/es5/components/VTreeview/index.js | 26 + .../es5/components/VTreeview/index.js.map | 1 + .../VTreeview/util/filterTreeItems.js | 32 + .../VTreeview/util/filterTreeItems.js.map | 1 + .../vuetify/es5/components/VWindow/VWindow.js | 132 + .../es5/components/VWindow/VWindow.js.map | 1 + .../es5/components/VWindow/VWindowItem.js | 142 + .../es5/components/VWindow/VWindowItem.js.map | 1 + .../vuetify/es5/components/VWindow/index.js | 26 + .../es5/components/VWindow/index.js.map | 1 + .../Vuetify/goTo/easing-patterns.js | 58 + .../Vuetify/goTo/easing-patterns.js.map | 1 + .../es5/components/Vuetify/goTo/index.js | 61 + .../es5/components/Vuetify/goTo/index.js.map | 1 + .../es5/components/Vuetify/goTo/util.js | 43 + .../es5/components/Vuetify/goTo/util.js.map | 1 + .../vuetify/es5/components/Vuetify/index.js | 111 + .../es5/components/Vuetify/index.js.map | 1 + .../components/Vuetify/mixins/application.js | 42 + .../Vuetify/mixins/application.js.map | 1 + .../components/Vuetify/mixins/breakpoint.js | 144 + .../Vuetify/mixins/breakpoint.js.map | 1 + .../es5/components/Vuetify/mixins/icons.js | 150 + .../components/Vuetify/mixins/icons.js.map | 1 + .../es5/components/Vuetify/mixins/lang.js | 58 + .../es5/components/Vuetify/mixins/lang.js.map | 1 + .../es5/components/Vuetify/mixins/options.js | 21 + .../components/Vuetify/mixins/options.js.map | 1 + .../es5/components/Vuetify/mixins/theme.js | 26 + .../components/Vuetify/mixins/theme.js.map | 1 + .../es5/components/Vuetify/util/goTo.js | 17 + .../es5/components/Vuetify/util/goTo.js.map | 1 + node_modules/vuetify/es5/components/index.js | 810 + .../vuetify/es5/components/index.js.map | 1 + .../transitions/expand-transition.js | 68 + .../transitions/expand-transition.js.map | 1 + .../es5/components/transitions/index.js | 67 + .../es5/components/transitions/index.js.map | 1 + .../vuetify/es5/directives/click-outside.js | 67 + .../es5/directives/click-outside.js.map | 1 + node_modules/vuetify/es5/directives/index.js | 42 + .../vuetify/es5/directives/index.js.map | 1 + node_modules/vuetify/es5/directives/resize.js | 31 + .../vuetify/es5/directives/resize.js.map | 1 + node_modules/vuetify/es5/directives/ripple.js | 202 + .../vuetify/es5/directives/ripple.js.map | 1 + node_modules/vuetify/es5/directives/scroll.js | 32 + .../vuetify/es5/directives/scroll.js.map | 1 + node_modules/vuetify/es5/directives/touch.js | 103 + .../vuetify/es5/directives/touch.js.map | 1 + node_modules/vuetify/es5/entry-lib.js | 45 + node_modules/vuetify/es5/entry-lib.js.map | 1 + node_modules/vuetify/es5/index.js | 41 + node_modules/vuetify/es5/index.js.map | 1 + node_modules/vuetify/es5/locale/af.js | 24 + node_modules/vuetify/es5/locale/af.js.map | 1 + node_modules/vuetify/es5/locale/ar.js | 24 + node_modules/vuetify/es5/locale/ar.js.map | 1 + node_modules/vuetify/es5/locale/ca.js | 24 + node_modules/vuetify/es5/locale/ca.js.map | 1 + node_modules/vuetify/es5/locale/de.js | 24 + node_modules/vuetify/es5/locale/de.js.map | 1 + node_modules/vuetify/es5/locale/el.js | 24 + node_modules/vuetify/es5/locale/el.js.map | 1 + node_modules/vuetify/es5/locale/en.js | 24 + node_modules/vuetify/es5/locale/en.js.map | 1 + node_modules/vuetify/es5/locale/es.js | 24 + node_modules/vuetify/es5/locale/es.js.map | 1 + node_modules/vuetify/es5/locale/et.js | 24 + node_modules/vuetify/es5/locale/et.js.map | 1 + node_modules/vuetify/es5/locale/fa.js | 24 + node_modules/vuetify/es5/locale/fa.js.map | 1 + node_modules/vuetify/es5/locale/fr.js | 24 + node_modules/vuetify/es5/locale/fr.js.map | 1 + node_modules/vuetify/es5/locale/gr.js | 24 + node_modules/vuetify/es5/locale/gr.js.map | 1 + node_modules/vuetify/es5/locale/hr.js | 24 + node_modules/vuetify/es5/locale/hr.js.map | 1 + node_modules/vuetify/es5/locale/hu.js | 24 + node_modules/vuetify/es5/locale/hu.js.map | 1 + node_modules/vuetify/es5/locale/id.js | 24 + node_modules/vuetify/es5/locale/id.js.map | 1 + node_modules/vuetify/es5/locale/index.js | 251 + node_modules/vuetify/es5/locale/index.js.map | 1 + node_modules/vuetify/es5/locale/it.js | 24 + node_modules/vuetify/es5/locale/it.js.map | 1 + node_modules/vuetify/es5/locale/ja.js | 24 + node_modules/vuetify/es5/locale/ja.js.map | 1 + node_modules/vuetify/es5/locale/nl.js | 24 + node_modules/vuetify/es5/locale/nl.js.map | 1 + node_modules/vuetify/es5/locale/pl.js | 24 + node_modules/vuetify/es5/locale/pl.js.map | 1 + node_modules/vuetify/es5/locale/pt.js | 24 + node_modules/vuetify/es5/locale/pt.js.map | 1 + node_modules/vuetify/es5/locale/ro.js | 24 + node_modules/vuetify/es5/locale/ro.js.map | 1 + node_modules/vuetify/es5/locale/ru.js | 24 + node_modules/vuetify/es5/locale/ru.js.map | 1 + node_modules/vuetify/es5/locale/sl.js | 24 + node_modules/vuetify/es5/locale/sl.js.map | 1 + node_modules/vuetify/es5/locale/sr-Cyrl.js | 24 + .../vuetify/es5/locale/sr-Cyrl.js.map | 1 + node_modules/vuetify/es5/locale/th.js | 24 + node_modules/vuetify/es5/locale/th.js.map | 1 + node_modules/vuetify/es5/locale/tr.js | 24 + node_modules/vuetify/es5/locale/tr.js.map | 1 + node_modules/vuetify/es5/locale/uk.js | 24 + node_modules/vuetify/es5/locale/uk.js.map | 1 + node_modules/vuetify/es5/locale/zh-Hans.js | 24 + .../vuetify/es5/locale/zh-Hans.js.map | 1 + node_modules/vuetify/es5/locale/zh-Hant.js | 24 + .../vuetify/es5/locale/zh-Hant.js.map | 1 + .../vuetify/es5/mixins/applicationable.js | 78 + .../vuetify/es5/mixins/applicationable.js.map | 1 + node_modules/vuetify/es5/mixins/bootable.js | 48 + .../vuetify/es5/mixins/bootable.js.map | 1 + .../vuetify/es5/mixins/button-group.js | 30 + .../vuetify/es5/mixins/button-group.js.map | 1 + node_modules/vuetify/es5/mixins/colorable.js | 64 + .../vuetify/es5/mixins/colorable.js.map | 1 + node_modules/vuetify/es5/mixins/comparable.js | 24 + .../vuetify/es5/mixins/comparable.js.map | 1 + .../vuetify/es5/mixins/data-iterable.js | 503 + .../vuetify/es5/mixins/data-iterable.js.map | 1 + node_modules/vuetify/es5/mixins/delayable.js | 61 + .../vuetify/es5/mixins/delayable.js.map | 1 + node_modules/vuetify/es5/mixins/dependent.js | 69 + .../vuetify/es5/mixins/dependent.js.map | 1 + node_modules/vuetify/es5/mixins/detachable.js | 119 + .../vuetify/es5/mixins/detachable.js.map | 1 + node_modules/vuetify/es5/mixins/elevatable.js | 30 + .../vuetify/es5/mixins/elevatable.js.map | 1 + node_modules/vuetify/es5/mixins/filterable.js | 23 + .../vuetify/es5/mixins/filterable.js.map | 1 + node_modules/vuetify/es5/mixins/groupable.js | 55 + .../vuetify/es5/mixins/groupable.js.map | 1 + node_modules/vuetify/es5/mixins/loadable.js | 48 + .../vuetify/es5/mixins/loadable.js.map | 1 + node_modules/vuetify/es5/mixins/maskable.js | 141 + .../vuetify/es5/mixins/maskable.js.map | 1 + node_modules/vuetify/es5/mixins/measurable.js | 46 + .../vuetify/es5/mixins/measurable.js.map | 1 + node_modules/vuetify/es5/mixins/menuable.js | 361 + .../vuetify/es5/mixins/menuable.js.map | 1 + .../vuetify/es5/mixins/overlayable.js | 189 + .../vuetify/es5/mixins/overlayable.js.map | 1 + .../vuetify/es5/mixins/picker-button.js | 44 + .../vuetify/es5/mixins/picker-button.js.map | 1 + node_modules/vuetify/es5/mixins/picker.js | 79 + node_modules/vuetify/es5/mixins/picker.js.map | 1 + .../vuetify/es5/mixins/positionable.js | 60 + .../vuetify/es5/mixins/positionable.js.map | 1 + node_modules/vuetify/es5/mixins/proxyable.js | 55 + .../vuetify/es5/mixins/proxyable.js.map | 1 + .../vuetify/es5/mixins/registrable.js | 51 + .../vuetify/es5/mixins/registrable.js.map | 1 + node_modules/vuetify/es5/mixins/returnable.js | 45 + .../vuetify/es5/mixins/returnable.js.map | 1 + node_modules/vuetify/es5/mixins/rippleable.js | 47 + .../vuetify/es5/mixins/rippleable.js.map | 1 + node_modules/vuetify/es5/mixins/routable.js | 97 + .../vuetify/es5/mixins/routable.js.map | 1 + node_modules/vuetify/es5/mixins/selectable.js | 151 + .../vuetify/es5/mixins/selectable.js.map | 1 + node_modules/vuetify/es5/mixins/sizeable.js | 25 + .../vuetify/es5/mixins/sizeable.js.map | 1 + .../vuetify/es5/mixins/ssr-bootable.js | 40 + .../vuetify/es5/mixins/ssr-bootable.js.map | 1 + node_modules/vuetify/es5/mixins/stackable.js | 64 + .../vuetify/es5/mixins/stackable.js.map | 1 + node_modules/vuetify/es5/mixins/themeable.js | 109 + .../vuetify/es5/mixins/themeable.js.map | 1 + node_modules/vuetify/es5/mixins/toggleable.js | 42 + .../vuetify/es5/mixins/toggleable.js.map | 1 + .../vuetify/es5/mixins/transitionable.js | 21 + .../vuetify/es5/mixins/transitionable.js.map | 1 + .../vuetify/es5/mixins/translatable.js | 64 + .../vuetify/es5/mixins/translatable.js.map | 1 + .../vuetify/es5/mixins/validatable.js | 235 + .../vuetify/es5/mixins/validatable.js.map | 1 + .../vuetify/es5/util/ThemeProvider.js | 34 + .../vuetify/es5/util/ThemeProvider.js.map | 1 + .../vuetify/es5/util/color/transformCIELAB.js | 25 + .../es5/util/color/transformCIELAB.js.map | 1 + .../vuetify/es5/util/color/transformSRGB.js | 48 + .../es5/util/color/transformSRGB.js.map | 1 + node_modules/vuetify/es5/util/colorUtils.js | 47 + .../vuetify/es5/util/colorUtils.js.map | 1 + node_modules/vuetify/es5/util/colors.js | 325 + node_modules/vuetify/es5/util/colors.js.map | 1 + node_modules/vuetify/es5/util/component.js | 10 + .../vuetify/es5/util/component.js.map | 1 + node_modules/vuetify/es5/util/console.js | 89 + node_modules/vuetify/es5/util/console.js.map | 1 + .../vuetify/es5/util/dedupeModelListeners.js | 23 + .../es5/util/dedupeModelListeners.js.map | 1 + .../vuetify/es5/util/easing-patterns.js | 22 + .../vuetify/es5/util/easing-patterns.js.map | 1 + node_modules/vuetify/es5/util/helpers.js | 360 + node_modules/vuetify/es5/util/helpers.js.map | 1 + node_modules/vuetify/es5/util/mask.js | 101 + node_modules/vuetify/es5/util/mask.js.map | 1 + node_modules/vuetify/es5/util/mixins.js | 21 + node_modules/vuetify/es5/util/mixins.js.map | 1 + .../es5/util/rebuildFunctionalSlots.js | 16 + .../es5/util/rebuildFunctionalSlots.js.map | 1 + node_modules/vuetify/es5/util/theme.js | 123 + node_modules/vuetify/es5/util/theme.js.map | 1 + .../vuetify/lib/components/VAlert/VAlert.js | 89 + .../lib/components/VAlert/VAlert.js.map | 1 + .../vuetify/lib/components/VAlert/index.js | 4 + .../lib/components/VAlert/index.js.map | 1 + .../vuetify/lib/components/VApp/VApp.js | 49 + .../vuetify/lib/components/VApp/VApp.js.map | 1 + .../vuetify/lib/components/VApp/index.js | 4 + .../vuetify/lib/components/VApp/index.js.map | 1 + .../lib/components/VApp/mixins/app-theme.js | 96 + .../components/VApp/mixins/app-theme.js.map | 1 + .../components/VAutocomplete/VAutocomplete.js | 305 + .../VAutocomplete/VAutocomplete.js.map | 1 + .../lib/components/VAutocomplete/index.js | 4 + .../lib/components/VAutocomplete/index.js.map | 1 + .../vuetify/lib/components/VAvatar/VAvatar.js | 36 + .../lib/components/VAvatar/VAvatar.js.map | 1 + .../vuetify/lib/components/VAvatar/index.js | 4 + .../lib/components/VAvatar/index.js.map | 1 + .../vuetify/lib/components/VBadge/VBadge.js | 57 + .../lib/components/VBadge/VBadge.js.map | 1 + .../vuetify/lib/components/VBadge/index.js | 4 + .../lib/components/VBadge/index.js.map | 1 + .../lib/components/VBottomNav/VBottomNav.js | 63 + .../components/VBottomNav/VBottomNav.js.map | 1 + .../lib/components/VBottomNav/index.js | 4 + .../lib/components/VBottomNav/index.js.map | 1 + .../components/VBottomSheet/VBottomSheet.js | 38 + .../VBottomSheet/VBottomSheet.js.map | 1 + .../lib/components/VBottomSheet/index.js | 4 + .../lib/components/VBottomSheet/index.js.map | 1 + .../components/VBreadcrumbs/VBreadcrumbs.js | 90 + .../VBreadcrumbs/VBreadcrumbs.js.map | 1 + .../VBreadcrumbs/VBreadcrumbsItem.js | 31 + .../VBreadcrumbs/VBreadcrumbsItem.js.map | 1 + .../lib/components/VBreadcrumbs/index.js | 13 + .../lib/components/VBreadcrumbs/index.js.map | 1 + .../vuetify/lib/components/VBtn/VBtn.js | 120 + .../vuetify/lib/components/VBtn/VBtn.js.map | 1 + .../vuetify/lib/components/VBtn/index.js | 4 + .../vuetify/lib/components/VBtn/index.js.map | 1 + .../lib/components/VBtnToggle/VBtnToggle.js | 26 + .../components/VBtnToggle/VBtnToggle.js.map | 1 + .../lib/components/VBtnToggle/index.js | 4 + .../lib/components/VBtnToggle/index.js.map | 1 + .../lib/components/VCalendar/VCalendar.js | 183 + .../lib/components/VCalendar/VCalendar.js.map | 1 + .../components/VCalendar/VCalendarDaily.js | 199 + .../VCalendar/VCalendarDaily.js.map | 1 + .../components/VCalendar/VCalendarMonthly.js | 22 + .../VCalendar/VCalendarMonthly.js.map | 1 + .../components/VCalendar/VCalendarWeekly.js | 133 + .../VCalendar/VCalendarWeekly.js.map | 1 + .../vuetify/lib/components/VCalendar/index.js | 14 + .../lib/components/VCalendar/index.js.map | 1 + .../VCalendar/mixins/calendar-base.js | 66 + .../VCalendar/mixins/calendar-base.js.map | 1 + .../mixins/calendar-with-intervals.js | 117 + .../mixins/calendar-with-intervals.js.map | 1 + .../lib/components/VCalendar/mixins/mouse.js | 56 + .../components/VCalendar/mixins/mouse.js.map | 1 + .../lib/components/VCalendar/mixins/times.js | 65 + .../components/VCalendar/mixins/times.js.map | 1 + .../lib/components/VCalendar/util/props.js | 117 + .../components/VCalendar/util/props.js.map | 1 + .../components/VCalendar/util/timestamp.js | 336 + .../VCalendar/util/timestamp.js.map | 1 + .../vuetify/lib/components/VCard/VCard.js | 45 + .../vuetify/lib/components/VCard/VCard.js.map | 1 + .../lib/components/VCard/VCardMedia.js | 13 + .../lib/components/VCard/VCardMedia.js.map | 1 + .../lib/components/VCard/VCardTitle.js | 20 + .../lib/components/VCard/VCardTitle.js.map | 1 + .../vuetify/lib/components/VCard/index.js | 17 + .../vuetify/lib/components/VCard/index.js.map | 1 + .../lib/components/VCarousel/VCarousel.js | 212 + .../lib/components/VCarousel/VCarousel.js.map | 1 + .../lib/components/VCarousel/VCarouselItem.js | 28 + .../components/VCarousel/VCarouselItem.js.map | 1 + .../vuetify/lib/components/VCarousel/index.js | 10 + .../lib/components/VCarousel/index.js.map | 1 + .../lib/components/VCheckbox/VCheckbox.js | 74 + .../lib/components/VCheckbox/VCheckbox.js.map | 1 + .../vuetify/lib/components/VCheckbox/index.js | 4 + .../lib/components/VCheckbox/index.js.map | 1 + .../vuetify/lib/components/VChip/VChip.js | 76 + .../vuetify/lib/components/VChip/VChip.js.map | 1 + .../vuetify/lib/components/VChip/index.js | 4 + .../vuetify/lib/components/VChip/index.js.map | 1 + .../lib/components/VCombobox/VCombobox.js | 181 + .../lib/components/VCombobox/VCombobox.js.map | 1 + .../vuetify/lib/components/VCombobox/index.js | 4 + .../lib/components/VCombobox/index.js.map | 1 + .../lib/components/VCounter/VCounter.js | 34 + .../lib/components/VCounter/VCounter.js.map | 1 + .../vuetify/lib/components/VCounter/index.js | 4 + .../lib/components/VCounter/index.js.map | 1 + .../components/VDataIterator/VDataIterator.js | 91 + .../VDataIterator/VDataIterator.js.map | 1 + .../lib/components/VDataIterator/index.js | 4 + .../lib/components/VDataIterator/index.js.map | 1 + .../lib/components/VDataTable/VDataTable.js | 106 + .../components/VDataTable/VDataTable.js.map | 1 + .../lib/components/VDataTable/VEditDialog.js | 119 + .../components/VDataTable/VEditDialog.js.map | 1 + .../lib/components/VDataTable/index.js | 13 + .../lib/components/VDataTable/index.js.map | 1 + .../lib/components/VDataTable/mixins/body.js | 65 + .../components/VDataTable/mixins/body.js.map | 1 + .../lib/components/VDataTable/mixins/foot.js | 22 + .../components/VDataTable/mixins/foot.js.map | 1 + .../lib/components/VDataTable/mixins/head.js | 127 + .../components/VDataTable/mixins/head.js.map | 1 + .../components/VDataTable/mixins/progress.js | 17 + .../VDataTable/mixins/progress.js.map | 1 + .../lib/components/VDatePicker/VDatePicker.js | 461 + .../components/VDatePicker/VDatePicker.js.map | 1 + .../VDatePicker/VDatePickerDateTable.js | 102 + .../VDatePicker/VDatePickerDateTable.js.map | 1 + .../VDatePicker/VDatePickerHeader.js | 134 + .../VDatePicker/VDatePickerHeader.js.map | 1 + .../VDatePicker/VDatePickerMonthTable.js | 49 + .../VDatePicker/VDatePickerMonthTable.js.map | 1 + .../VDatePicker/VDatePickerTitle.js | 80 + .../VDatePicker/VDatePickerTitle.js.map | 1 + .../VDatePicker/VDatePickerYears.js | 81 + .../VDatePicker/VDatePickerYears.js.map | 1 + .../lib/components/VDatePicker/index.js | 18 + .../lib/components/VDatePicker/index.js.map | 1 + .../VDatePicker/mixins/date-picker-table.js | 195 + .../mixins/date-picker-table.js.map | 1 + .../util/createNativeLocaleFormatter.js | 28 + .../util/createNativeLocaleFormatter.js.map | 1 + .../lib/components/VDatePicker/util/index.js | 5 + .../components/VDatePicker/util/index.js.map | 1 + .../VDatePicker/util/isDateAllowed.js | 4 + .../VDatePicker/util/isDateAllowed.js.map | 1 + .../VDatePicker/util/monthChange.js | 22 + .../VDatePicker/util/monthChange.js.map | 1 + .../lib/components/VDatePicker/util/pad.js | 18 + .../components/VDatePicker/util/pad.js.map | 1 + .../vuetify/lib/components/VDialog/VDialog.js | 305 + .../lib/components/VDialog/VDialog.js.map | 1 + .../vuetify/lib/components/VDialog/index.js | 4 + .../lib/components/VDialog/index.js.map | 1 + .../lib/components/VDivider/VDivider.js | 25 + .../lib/components/VDivider/VDivider.js.map | 1 + .../vuetify/lib/components/VDivider/index.js | 4 + .../lib/components/VDivider/index.js.map | 1 + .../VExpansionPanel/VExpansionPanel.js | 120 + .../VExpansionPanel/VExpansionPanel.js.map | 1 + .../VExpansionPanel/VExpansionPanelContent.js | 123 + .../VExpansionPanelContent.js.map | 1 + .../lib/components/VExpansionPanel/index.js | 10 + .../components/VExpansionPanel/index.js.map | 1 + .../vuetify/lib/components/VFooter/VFooter.js | 75 + .../lib/components/VFooter/VFooter.js.map | 1 + .../vuetify/lib/components/VFooter/index.js | 4 + .../lib/components/VFooter/index.js.map | 1 + .../vuetify/lib/components/VForm/VForm.js | 137 + .../vuetify/lib/components/VForm/VForm.js.map | 1 + .../vuetify/lib/components/VForm/index.js | 4 + .../vuetify/lib/components/VForm/index.js.map | 1 + .../lib/components/VGrid/VContainer.js | 4 + .../lib/components/VGrid/VContainer.js.map | 1 + .../vuetify/lib/components/VGrid/VContent.js | 43 + .../lib/components/VGrid/VContent.js.map | 1 + .../vuetify/lib/components/VGrid/VFlex.js | 4 + .../vuetify/lib/components/VGrid/VFlex.js.map | 1 + .../vuetify/lib/components/VGrid/VLayout.js | 4 + .../lib/components/VGrid/VLayout.js.map | 1 + .../vuetify/lib/components/VGrid/grid.js | 47 + .../vuetify/lib/components/VGrid/grid.js.map | 1 + .../vuetify/lib/components/VGrid/index.js | 17 + .../vuetify/lib/components/VGrid/index.js.map | 1 + .../vuetify/lib/components/VHover/VHover.js | 57 + .../lib/components/VHover/VHover.js.map | 1 + .../vuetify/lib/components/VHover/index.js | 4 + .../lib/components/VHover/index.js.map | 1 + .../vuetify/lib/components/VIcon/VIcon.js | 142 + .../vuetify/lib/components/VIcon/VIcon.js.map | 1 + .../vuetify/lib/components/VIcon/index.js | 4 + .../vuetify/lib/components/VIcon/index.js.map | 1 + .../vuetify/lib/components/VImg/VImg.js | 179 + .../vuetify/lib/components/VImg/VImg.js.map | 1 + .../vuetify/lib/components/VImg/index.js | 4 + .../vuetify/lib/components/VImg/index.js.map | 1 + .../vuetify/lib/components/VInput/VInput.js | 247 + .../lib/components/VInput/VInput.js.map | 1 + .../vuetify/lib/components/VInput/index.js | 4 + .../lib/components/VInput/index.js.map | 1 + .../lib/components/VItemGroup/VItem.js | 43 + .../lib/components/VItemGroup/VItem.js.map | 1 + .../lib/components/VItemGroup/VItemGroup.js | 190 + .../components/VItemGroup/VItemGroup.js.map | 1 + .../lib/components/VItemGroup/index.js | 10 + .../lib/components/VItemGroup/index.js.map | 1 + .../lib/components/VJumbotron/VJumbotron.js | 81 + .../components/VJumbotron/VJumbotron.js.map | 1 + .../lib/components/VJumbotron/index.js | 4 + .../lib/components/VJumbotron/index.js.map | 1 + .../vuetify/lib/components/VLabel/VLabel.js | 59 + .../lib/components/VLabel/VLabel.js.map | 1 + .../vuetify/lib/components/VLabel/index.js | 4 + .../lib/components/VLabel/index.js.map | 1 + .../vuetify/lib/components/VList/VList.js | 91 + .../vuetify/lib/components/VList/VList.js.map | 1 + .../lib/components/VList/VListGroup.js | 145 + .../lib/components/VList/VListGroup.js.map | 1 + .../vuetify/lib/components/VList/VListTile.js | 75 + .../lib/components/VList/VListTile.js.map | 1 + .../lib/components/VList/VListTileAction.js | 20 + .../components/VList/VListTileAction.js.map | 1 + .../lib/components/VList/VListTileAvatar.js | 33 + .../components/VList/VListTileAvatar.js.map | 1 + .../vuetify/lib/components/VList/index.js | 25 + .../vuetify/lib/components/VList/index.js.map | 1 + .../vuetify/lib/components/VMenu/VMenu.js | 197 + .../vuetify/lib/components/VMenu/VMenu.js.map | 1 + .../vuetify/lib/components/VMenu/index.js | 4 + .../vuetify/lib/components/VMenu/index.js.map | 1 + .../components/VMenu/mixins/menu-activator.js | 58 + .../VMenu/mixins/menu-activator.js.map | 1 + .../VMenu/mixins/menu-generators.js | 97 + .../VMenu/mixins/menu-generators.js.map | 1 + .../components/VMenu/mixins/menu-keyable.js | 81 + .../VMenu/mixins/menu-keyable.js.map | 1 + .../components/VMenu/mixins/menu-position.js | 43 + .../VMenu/mixins/menu-position.js.map | 1 + .../lib/components/VMessages/VMessages.js | 45 + .../lib/components/VMessages/VMessages.js.map | 1 + .../vuetify/lib/components/VMessages/index.js | 4 + .../lib/components/VMessages/index.js.map | 1 + .../VNavigationDrawer/VNavigationDrawer.js | 280 + .../VNavigationDrawer.js.map | 1 + .../lib/components/VNavigationDrawer/index.js | 4 + .../components/VNavigationDrawer/index.js.map | 1 + .../components/VOverflowBtn/VOverflowBtn.js | 84 + .../VOverflowBtn/VOverflowBtn.js.map | 1 + .../lib/components/VOverflowBtn/index.js | 4 + .../lib/components/VOverflowBtn/index.js.map | 1 + .../lib/components/VPagination/VPagination.js | 172 + .../components/VPagination/VPagination.js.map | 1 + .../lib/components/VPagination/index.js | 4 + .../lib/components/VPagination/index.js.map | 1 + .../lib/components/VParallax/VParallax.js | 88 + .../lib/components/VParallax/VParallax.js.map | 1 + .../vuetify/lib/components/VParallax/index.js | 4 + .../lib/components/VParallax/index.js.map | 1 + .../vuetify/lib/components/VPicker/VPicker.js | 73 + .../lib/components/VPicker/VPicker.js.map | 1 + .../vuetify/lib/components/VPicker/index.js | 4 + .../lib/components/VPicker/index.js.map | 1 + .../VProgressCircular/VProgressCircular.js | 120 + .../VProgressCircular.js.map | 1 + .../lib/components/VProgressCircular/index.js | 4 + .../components/VProgressCircular/index.js.map | 1 + .../VProgressLinear/VProgressLinear.js | 147 + .../VProgressLinear/VProgressLinear.js.map | 1 + .../lib/components/VProgressLinear/index.js | 4 + .../components/VProgressLinear/index.js.map | 1 + .../lib/components/VRadioGroup/VRadio.js | 139 + .../lib/components/VRadioGroup/VRadio.js.map | 1 + .../lib/components/VRadioGroup/VRadioGroup.js | 119 + .../components/VRadioGroup/VRadioGroup.js.map | 1 + .../lib/components/VRadioGroup/index.js | 10 + .../lib/components/VRadioGroup/index.js.map | 1 + .../components/VRangeSlider/VRangeSlider.js | 148 + .../VRangeSlider/VRangeSlider.js.map | 1 + .../lib/components/VRangeSlider/index.js | 4 + .../lib/components/VRangeSlider/index.js.map | 1 + .../vuetify/lib/components/VRating/VRating.js | 205 + .../lib/components/VRating/VRating.js.map | 1 + .../vuetify/lib/components/VRating/index.js | 4 + .../lib/components/VRating/index.js.map | 1 + .../lib/components/VResponsive/VResponsive.js | 42 + .../components/VResponsive/VResponsive.js.map | 1 + .../lib/components/VResponsive/index.js | 4 + .../lib/components/VResponsive/index.js.map | 1 + .../vuetify/lib/components/VSelect/VSelect.js | 686 + .../lib/components/VSelect/VSelect.js.map | 1 + .../lib/components/VSelect/VSelectList.js | 227 + .../lib/components/VSelect/VSelectList.js.map | 1 + .../vuetify/lib/components/VSelect/index.js | 74 + .../lib/components/VSelect/index.js.map | 1 + .../vuetify/lib/components/VSheet/VSheet.js | 42 + .../lib/components/VSheet/VSheet.js.map | 1 + .../vuetify/lib/components/VSheet/index.js | 4 + .../lib/components/VSheet/index.js.map | 1 + .../vuetify/lib/components/VSlider/VSlider.js | 452 + .../lib/components/VSlider/VSlider.js.map | 1 + .../vuetify/lib/components/VSlider/index.js | 4 + .../lib/components/VSlider/index.js.map | 1 + .../lib/components/VSnackbar/VSnackbar.js | 76 + .../lib/components/VSnackbar/VSnackbar.js.map | 1 + .../vuetify/lib/components/VSnackbar/index.js | 4 + .../lib/components/VSnackbar/index.js.map | 1 + .../lib/components/VSparkline/VSparkline.js | 349 + .../components/VSparkline/VSparkline.js.map | 1 + .../lib/components/VSparkline/helpers/core.js | 27 + .../components/VSparkline/helpers/core.js.map | 1 + .../lib/components/VSparkline/helpers/math.js | 24 + .../components/VSparkline/helpers/math.js.map | 1 + .../lib/components/VSparkline/helpers/path.js | 26 + .../components/VSparkline/helpers/path.js.map | 1 + .../lib/components/VSparkline/index.js | 4 + .../lib/components/VSparkline/index.js.map | 1 + .../lib/components/VSpeedDial/VSpeedDial.js | 95 + .../components/VSpeedDial/VSpeedDial.js.map | 1 + .../lib/components/VSpeedDial/index.js | 4 + .../lib/components/VSpeedDial/index.js.map | 1 + .../lib/components/VStepper/VStepper.js | 107 + .../lib/components/VStepper/VStepper.js.map | 1 + .../components/VStepper/VStepperContent.js | 131 + .../VStepper/VStepperContent.js.map | 1 + .../lib/components/VStepper/VStepperStep.js | 119 + .../components/VStepper/VStepperStep.js.map | 1 + .../vuetify/lib/components/VStepper/index.js | 17 + .../lib/components/VStepper/index.js.map | 1 + .../lib/components/VSubheader/VSubheader.js | 26 + .../components/VSubheader/VSubheader.js.map | 1 + .../lib/components/VSubheader/index.js | 4 + .../lib/components/VSubheader/index.js.map | 1 + .../vuetify/lib/components/VSwitch/VSwitch.js | 79 + .../lib/components/VSwitch/VSwitch.js.map | 1 + .../vuetify/lib/components/VSwitch/index.js | 4 + .../lib/components/VSwitch/index.js.map | 1 + .../lib/components/VSystemBar/VSystemBar.js | 59 + .../components/VSystemBar/VSystemBar.js.map | 1 + .../lib/components/VSystemBar/index.js | 4 + .../lib/components/VSystemBar/index.js.map | 1 + .../vuetify/lib/components/VTabs/VTab.js | 79 + .../vuetify/lib/components/VTabs/VTab.js.map | 1 + .../vuetify/lib/components/VTabs/VTabItem.js | 23 + .../lib/components/VTabs/VTabItem.js.map | 1 + .../vuetify/lib/components/VTabs/VTabs.js | 216 + .../vuetify/lib/components/VTabs/VTabs.js.map | 1 + .../lib/components/VTabs/VTabsItems.js | 58 + .../lib/components/VTabs/VTabsItems.js.map | 1 + .../lib/components/VTabs/VTabsSlider.js | 12 + .../lib/components/VTabs/VTabsSlider.js.map | 1 + .../vuetify/lib/components/VTabs/index.js | 16 + .../vuetify/lib/components/VTabs/index.js.map | 1 + .../components/VTabs/mixins/tabs-computed.js | 33 + .../VTabs/mixins/tabs-computed.js.map | 1 + .../VTabs/mixins/tabs-generators.js | 99 + .../VTabs/mixins/tabs-generators.js.map | 1 + .../lib/components/VTabs/mixins/tabs-props.js | 54 + .../components/VTabs/mixins/tabs-props.js.map | 1 + .../lib/components/VTabs/mixins/tabs-touch.js | 40 + .../components/VTabs/mixins/tabs-touch.js.map | 1 + .../components/VTabs/mixins/tabs-watchers.js | 47 + .../VTabs/mixins/tabs-watchers.js.map | 1 + .../lib/components/VTextField/VTextField.js | 363 + .../components/VTextField/VTextField.js.map | 1 + .../lib/components/VTextField/index.js | 39 + .../lib/components/VTextField/index.js.map | 1 + .../lib/components/VTextarea/VTextarea.js | 101 + .../lib/components/VTextarea/VTextarea.js.map | 1 + .../vuetify/lib/components/VTextarea/index.js | 4 + .../lib/components/VTextarea/index.js.map | 1 + .../lib/components/VTimePicker/VTimePicker.js | 309 + .../components/VTimePicker/VTimePicker.js.map | 1 + .../VTimePicker/VTimePickerClock.js | 239 + .../VTimePicker/VTimePickerClock.js.map | 1 + .../VTimePicker/VTimePickerTitle.js | 60 + .../VTimePicker/VTimePickerTitle.js.map | 1 + .../lib/components/VTimePicker/index.js | 12 + .../lib/components/VTimePicker/index.js.map | 1 + .../lib/components/VTimeline/VTimeline.js | 31 + .../lib/components/VTimeline/VTimeline.js.map | 1 + .../lib/components/VTimeline/VTimelineItem.js | 86 + .../components/VTimeline/VTimelineItem.js.map | 1 + .../vuetify/lib/components/VTimeline/index.js | 10 + .../lib/components/VTimeline/index.js.map | 1 + .../lib/components/VToolbar/VToolbar.js | 207 + .../lib/components/VToolbar/VToolbar.js.map | 1 + .../components/VToolbar/VToolbarSideIcon.js | 26 + .../VToolbar/VToolbarSideIcon.js.map | 1 + .../vuetify/lib/components/VToolbar/index.js | 15 + .../lib/components/VToolbar/index.js.map | 1 + .../lib/components/VTooltip/VTooltip.js | 187 + .../lib/components/VTooltip/VTooltip.js.map | 1 + .../vuetify/lib/components/VTooltip/index.js | 4 + .../lib/components/VTooltip/index.js.map | 1 + .../lib/components/VTreeview/VTreeview.js | 390 + .../lib/components/VTreeview/VTreeview.js.map | 1 + .../lib/components/VTreeview/VTreeviewNode.js | 273 + .../components/VTreeview/VTreeviewNode.js.map | 1 + .../vuetify/lib/components/VTreeview/index.js | 10 + .../lib/components/VTreeview/index.js.map | 1 + .../VTreeview/util/filterTreeItems.js | 23 + .../VTreeview/util/filterTreeItems.js.map | 1 + .../vuetify/lib/components/VWindow/VWindow.js | 118 + .../lib/components/VWindow/VWindow.js.map | 1 + .../lib/components/VWindow/VWindowItem.js | 123 + .../lib/components/VWindow/VWindowItem.js.map | 1 + .../vuetify/lib/components/VWindow/index.js | 10 + .../lib/components/VWindow/index.js.map | 1 + .../Vuetify/goTo/easing-patterns.js | 53 + .../Vuetify/goTo/easing-patterns.js.map | 1 + .../lib/components/Vuetify/goTo/index.js | 42 + .../lib/components/Vuetify/goTo/index.js.map | 1 + .../lib/components/Vuetify/goTo/util.js | 36 + .../lib/components/Vuetify/goTo/util.js.map | 1 + .../vuetify/lib/components/Vuetify/index.js | 77 + .../lib/components/Vuetify/index.js.map | 1 + .../components/Vuetify/mixins/application.js | 36 + .../Vuetify/mixins/application.js.map | 1 + .../components/Vuetify/mixins/breakpoint.js | 131 + .../Vuetify/mixins/breakpoint.js.map | 1 + .../lib/components/Vuetify/mixins/icons.js | 143 + .../components/Vuetify/mixins/icons.js.map | 1 + .../lib/components/Vuetify/mixins/lang.js | 44 + .../lib/components/Vuetify/mixins/lang.js.map | 1 + .../lib/components/Vuetify/mixins/options.js | 14 + .../components/Vuetify/mixins/options.js.map | 1 + .../lib/components/Vuetify/mixins/theme.js | 19 + .../components/Vuetify/mixins/theme.js.map | 1 + .../lib/components/Vuetify/util/goTo.js | 5 + .../lib/components/Vuetify/util/goTo.js.map | 1 + node_modules/vuetify/lib/components/index.js | 68 + .../vuetify/lib/components/index.js.map | 1 + .../transitions/expand-transition.js | 61 + .../transitions/expand-transition.js.map | 1 + .../lib/components/transitions/index.js | 54 + .../lib/components/transitions/index.js.map | 1 + .../vuetify/lib/directives/click-outside.js | 62 + .../lib/directives/click-outside.js.map | 1 + node_modules/vuetify/lib/directives/index.js | 14 + .../vuetify/lib/directives/index.js.map | 1 + node_modules/vuetify/lib/directives/resize.js | 26 + .../vuetify/lib/directives/resize.js.map | 1 + node_modules/vuetify/lib/directives/ripple.js | 195 + .../vuetify/lib/directives/ripple.js.map | 1 + node_modules/vuetify/lib/directives/scroll.js | 27 + .../vuetify/lib/directives/scroll.js.map | 1 + node_modules/vuetify/lib/directives/touch.js | 96 + .../vuetify/lib/directives/touch.js.map | 1 + node_modules/vuetify/lib/index.js | 6 + node_modules/vuetify/lib/index.js.map | 1 + node_modules/vuetify/lib/locale/af.js | 19 + node_modules/vuetify/lib/locale/af.js.map | 1 + node_modules/vuetify/lib/locale/ar.js | 19 + node_modules/vuetify/lib/locale/ar.js.map | 1 + node_modules/vuetify/lib/locale/ca.js | 19 + node_modules/vuetify/lib/locale/ca.js.map | 1 + node_modules/vuetify/lib/locale/de.js | 19 + node_modules/vuetify/lib/locale/de.js.map | 1 + node_modules/vuetify/lib/locale/el.js | 19 + node_modules/vuetify/lib/locale/el.js.map | 1 + node_modules/vuetify/lib/locale/en.js | 19 + node_modules/vuetify/lib/locale/en.js.map | 1 + node_modules/vuetify/lib/locale/es.js | 19 + node_modules/vuetify/lib/locale/es.js.map | 1 + node_modules/vuetify/lib/locale/et.js | 19 + node_modules/vuetify/lib/locale/et.js.map | 1 + node_modules/vuetify/lib/locale/fa.js | 19 + node_modules/vuetify/lib/locale/fa.js.map | 1 + node_modules/vuetify/lib/locale/fr.js | 19 + node_modules/vuetify/lib/locale/fr.js.map | 1 + node_modules/vuetify/lib/locale/gr.js | 19 + node_modules/vuetify/lib/locale/gr.js.map | 1 + node_modules/vuetify/lib/locale/hr.js | 19 + node_modules/vuetify/lib/locale/hr.js.map | 1 + node_modules/vuetify/lib/locale/hu.js | 19 + node_modules/vuetify/lib/locale/hu.js.map | 1 + node_modules/vuetify/lib/locale/id.js | 19 + node_modules/vuetify/lib/locale/id.js.map | 1 + node_modules/vuetify/lib/locale/index.js | 28 + node_modules/vuetify/lib/locale/index.js.map | 1 + node_modules/vuetify/lib/locale/it.js | 19 + node_modules/vuetify/lib/locale/it.js.map | 1 + node_modules/vuetify/lib/locale/ja.js | 19 + node_modules/vuetify/lib/locale/ja.js.map | 1 + node_modules/vuetify/lib/locale/nl.js | 19 + node_modules/vuetify/lib/locale/nl.js.map | 1 + node_modules/vuetify/lib/locale/pl.js | 19 + node_modules/vuetify/lib/locale/pl.js.map | 1 + node_modules/vuetify/lib/locale/pt.js | 19 + node_modules/vuetify/lib/locale/pt.js.map | 1 + node_modules/vuetify/lib/locale/ro.js | 19 + node_modules/vuetify/lib/locale/ro.js.map | 1 + node_modules/vuetify/lib/locale/ru.js | 19 + node_modules/vuetify/lib/locale/ru.js.map | 1 + node_modules/vuetify/lib/locale/sl.js | 19 + node_modules/vuetify/lib/locale/sl.js.map | 1 + node_modules/vuetify/lib/locale/sr-Cyrl.js | 19 + .../vuetify/lib/locale/sr-Cyrl.js.map | 1 + node_modules/vuetify/lib/locale/th.js | 19 + node_modules/vuetify/lib/locale/th.js.map | 1 + node_modules/vuetify/lib/locale/tr.js | 19 + node_modules/vuetify/lib/locale/tr.js.map | 1 + node_modules/vuetify/lib/locale/uk.js | 19 + node_modules/vuetify/lib/locale/uk.js.map | 1 + node_modules/vuetify/lib/locale/zh-Hans.js | 19 + .../vuetify/lib/locale/zh-Hans.js.map | 1 + node_modules/vuetify/lib/locale/zh-Hant.js | 19 + .../vuetify/lib/locale/zh-Hant.js.map | 1 + .../vuetify/lib/mixins/applicationable.js | 65 + .../vuetify/lib/mixins/applicationable.js.map | 1 + node_modules/vuetify/lib/mixins/bootable.js | 37 + .../vuetify/lib/mixins/bootable.js.map | 1 + .../vuetify/lib/mixins/button-group.js | 24 + .../vuetify/lib/mixins/button-group.js.map | 1 + node_modules/vuetify/lib/mixins/colorable.js | 53 + .../vuetify/lib/mixins/colorable.js.map | 1 + node_modules/vuetify/lib/mixins/comparable.js | 12 + .../vuetify/lib/mixins/comparable.js.map | 1 + .../vuetify/lib/mixins/data-iterable.js | 475 + .../vuetify/lib/mixins/data-iterable.js.map | 1 + node_modules/vuetify/lib/mixins/delayable.js | 50 + .../vuetify/lib/mixins/delayable.js.map | 1 + node_modules/vuetify/lib/mixins/dependent.js | 58 + .../vuetify/lib/mixins/dependent.js.map | 1 + node_modules/vuetify/lib/mixins/detachable.js | 107 + .../vuetify/lib/mixins/detachable.js.map | 1 + node_modules/vuetify/lib/mixins/elevatable.js | 19 + .../vuetify/lib/mixins/elevatable.js.map | 1 + node_modules/vuetify/lib/mixins/filterable.js | 12 + .../vuetify/lib/mixins/filterable.js.map | 1 + node_modules/vuetify/lib/mixins/groupable.js | 47 + .../vuetify/lib/mixins/groupable.js.map | 1 + node_modules/vuetify/lib/mixins/loadable.js | 34 + .../vuetify/lib/mixins/loadable.js.map | 1 + node_modules/vuetify/lib/mixins/maskable.js | 135 + .../vuetify/lib/mixins/maskable.js.map | 1 + node_modules/vuetify/lib/mixins/measurable.js | 34 + .../vuetify/lib/mixins/measurable.js.map | 1 + node_modules/vuetify/lib/mixins/menuable.js | 344 + .../vuetify/lib/mixins/menuable.js.map | 1 + .../vuetify/lib/mixins/overlayable.js | 175 + .../vuetify/lib/mixins/overlayable.js.map | 1 + .../vuetify/lib/mixins/picker-button.js | 30 + .../vuetify/lib/mixins/picker-button.js.map | 1 + node_modules/vuetify/lib/mixins/picker.js | 58 + node_modules/vuetify/lib/mixins/picker.js.map | 1 + .../vuetify/lib/mixins/positionable.js | 47 + .../vuetify/lib/mixins/positionable.js.map | 1 + node_modules/vuetify/lib/mixins/proxyable.js | 43 + .../vuetify/lib/mixins/proxyable.js.map | 1 + .../vuetify/lib/mixins/registrable.js | 37 + .../vuetify/lib/mixins/registrable.js.map | 1 + node_modules/vuetify/lib/mixins/returnable.js | 34 + .../vuetify/lib/mixins/returnable.js.map | 1 + node_modules/vuetify/lib/mixins/rippleable.js | 33 + .../vuetify/lib/mixins/rippleable.js.map | 1 + node_modules/vuetify/lib/mixins/routable.js | 83 + .../vuetify/lib/mixins/routable.js.map | 1 + node_modules/vuetify/lib/mixins/selectable.js | 134 + .../vuetify/lib/mixins/selectable.js.map | 1 + node_modules/vuetify/lib/mixins/sizeable.js | 14 + .../vuetify/lib/mixins/sizeable.js.map | 1 + .../vuetify/lib/mixins/ssr-bootable.js | 29 + .../vuetify/lib/mixins/ssr-bootable.js.map | 1 + node_modules/vuetify/lib/mixins/stackable.js | 52 + .../vuetify/lib/mixins/stackable.js.map | 1 + node_modules/vuetify/lib/mixins/themeable.js | 96 + .../vuetify/lib/mixins/themeable.js.map | 1 + node_modules/vuetify/lib/mixins/toggleable.js | 30 + .../vuetify/lib/mixins/toggleable.js.map | 1 + .../vuetify/lib/mixins/transitionable.js | 10 + .../vuetify/lib/mixins/transitionable.js.map | 1 + .../vuetify/lib/mixins/translatable.js | 53 + .../vuetify/lib/mixins/translatable.js.map | 1 + .../vuetify/lib/mixins/validatable.js | 217 + .../vuetify/lib/mixins/validatable.js.map | 1 + .../vuetify/lib/util/ThemeProvider.js | 20 + .../vuetify/lib/util/ThemeProvider.js.map | 1 + .../vuetify/lib/util/color/transformCIELAB.js | 18 + .../lib/util/color/transformCIELAB.js.map | 1 + .../vuetify/lib/util/color/transformSRGB.js | 41 + .../lib/util/color/transformSRGB.js.map | 1 + node_modules/vuetify/lib/util/colorUtils.js | 37 + .../vuetify/lib/util/colorUtils.js.map | 1 + node_modules/vuetify/lib/util/colors.js | 320 + node_modules/vuetify/lib/util/colors.js.map | 1 + node_modules/vuetify/lib/util/component.js | 4 + .../vuetify/lib/util/component.js.map | 1 + node_modules/vuetify/lib/util/console.js | 80 + node_modules/vuetify/lib/util/console.js.map | 1 + .../vuetify/lib/util/dedupeModelListeners.js | 17 + .../lib/util/dedupeModelListeners.js.map | 1 + .../vuetify/lib/util/easing-patterns.js | 4 + .../vuetify/lib/util/easing-patterns.js.map | 1 + node_modules/vuetify/lib/util/helpers.js | 324 + node_modules/vuetify/lib/util/helpers.js.map | 1 + node_modules/vuetify/lib/util/mask.js | 96 + node_modules/vuetify/lib/util/mask.js.map | 1 + node_modules/vuetify/lib/util/mixins.js | 10 + node_modules/vuetify/lib/util/mixins.js.map | 1 + .../lib/util/rebuildFunctionalSlots.js | 10 + .../lib/util/rebuildFunctionalSlots.js.map | 1 + node_modules/vuetify/lib/util/theme.js | 104 + node_modules/vuetify/lib/util/theme.js.map | 1 + node_modules/vuetify/package.json | 124 + .../vuetify/src/components/VAlert/VAlert.ts | 107 + .../vuetify/src/components/VAlert/index.ts | 4 + .../vuetify/src/components/VApp/VApp.js | 63 + .../vuetify/src/components/VApp/index.js | 4 + .../src/components/VApp/mixins/app-theme.js | 109 + .../components/VAutocomplete/VAutocomplete.js | 377 + .../src/components/VAutocomplete/index.js | 4 + .../vuetify/src/components/VAvatar/VAvatar.ts | 42 + .../vuetify/src/components/VAvatar/index.ts | 4 + .../vuetify/src/components/VBadge/VBadge.ts | 72 + .../vuetify/src/components/VBadge/index.ts | 4 + .../src/components/VBottomNav/VBottomNav.ts | 79 + .../src/components/VBottomNav/index.ts | 4 + .../components/VBottomSheet/VBottomSheet.js | 48 + .../src/components/VBottomSheet/index.js | 4 + .../components/VBreadcrumbs/VBreadcrumbs.ts | 113 + .../VBreadcrumbs/VBreadcrumbsItem.ts | 35 + .../src/components/VBreadcrumbs/index.ts | 15 + .../vuetify/src/components/VBtn/VBtn.ts | 169 + .../vuetify/src/components/VBtn/index.ts | 4 + .../src/components/VBtnToggle/VBtnToggle.ts | 28 + .../src/components/VBtnToggle/index.ts | 4 + .../src/components/VCalendar/VCalendar.ts | 210 + .../components/VCalendar/VCalendarDaily.ts | 235 + .../components/VCalendar/VCalendarMonthly.ts | 26 + .../components/VCalendar/VCalendarWeekly.ts | 173 + .../vuetify/src/components/VCalendar/index.ts | 15 + .../VCalendar/mixins/calendar-base.ts | 89 + .../mixins/calendar-with-intervals.ts | 146 + .../src/components/VCalendar/mixins/mouse.ts | 82 + .../src/components/VCalendar/mixins/times.ts | 74 + .../src/components/VCalendar/util/props.ts | 115 + .../components/VCalendar/util/timestamp.ts | 401 + .../vuetify/src/components/VCard/VCard.ts | 59 + .../src/components/VCard/VCardMedia.ts | 15 + .../src/components/VCard/VCardTitle.ts | 21 + .../vuetify/src/components/VCard/index.ts | 19 + .../src/components/VCarousel/VCarousel.ts | 248 + .../src/components/VCarousel/VCarouselItem.ts | 32 + .../vuetify/src/components/VCarousel/index.ts | 11 + .../src/components/VCheckbox/VCheckbox.js | 90 + .../vuetify/src/components/VCheckbox/index.js | 4 + .../vuetify/src/components/VChip/VChip.ts | 90 + .../vuetify/src/components/VChip/index.ts | 4 + .../src/components/VCombobox/VCombobox.js | 218 + .../vuetify/src/components/VCombobox/index.js | 4 + .../src/components/VCounter/VCounter.ts | 40 + .../vuetify/src/components/VCounter/index.ts | 4 + .../components/VDataIterator/VDataIterator.js | 110 + .../src/components/VDataIterator/index.js | 4 + .../src/components/VDataTable/VDataTable.js | 121 + .../src/components/VDataTable/VEditDialog.js | 126 + .../src/components/VDataTable/index.js | 16 + .../src/components/VDataTable/mixins/body.js | 77 + .../src/components/VDataTable/mixins/foot.js | 24 + .../src/components/VDataTable/mixins/head.js | 138 + .../components/VDataTable/mixins/progress.js | 17 + .../src/components/VDatePicker/VDatePicker.ts | 457 + .../VDatePicker/VDatePickerDateTable.ts | 124 + .../VDatePicker/VDatePickerHeader.ts | 148 + .../VDatePicker/VDatePickerMonthTable.ts | 58 + .../VDatePicker/VDatePickerTitle.ts | 99 + .../VDatePicker/VDatePickerYears.ts | 101 + .../src/components/VDatePicker/index.js | 26 + .../VDatePicker/mixins/date-picker-table.ts | 198 + .../util/createNativeLocaleFormatter.ts | 41 + .../src/components/VDatePicker/util/index.ts | 9 + .../VDatePicker/util/isDateAllowed.ts | 7 + .../VDatePicker/util/monthChange.ts | 17 + .../src/components/VDatePicker/util/pad.ts | 16 + .../vuetify/src/components/VDialog/VDialog.js | 335 + .../vuetify/src/components/VDialog/index.js | 4 + .../src/components/VDivider/VDivider.ts | 30 + .../vuetify/src/components/VDivider/index.ts | 4 + .../VExpansionPanel/VExpansionPanel.ts | 132 + .../VExpansionPanel/VExpansionPanelContent.ts | 160 + .../src/components/VExpansionPanel/index.ts | 11 + .../vuetify/src/components/VFooter/VFooter.js | 100 + .../vuetify/src/components/VFooter/index.js | 4 + .../vuetify/src/components/VForm/VForm.js | 128 + .../vuetify/src/components/VForm/index.js | 4 + .../src/components/VGrid/VContainer.js | 5 + .../vuetify/src/components/VGrid/VContent.js | 50 + .../vuetify/src/components/VGrid/VFlex.js | 5 + .../vuetify/src/components/VGrid/VLayout.js | 5 + .../vuetify/src/components/VGrid/grid.js | 51 + .../vuetify/src/components/VGrid/index.js | 27 + .../vuetify/src/components/VHover/VHover.ts | 74 + .../vuetify/src/components/VHover/index.ts | 4 + .../vuetify/src/components/VIcon/VIcon.ts | 166 + .../vuetify/src/components/VIcon/index.ts | 4 + .../vuetify/src/components/VImg/VImg.ts | 224 + .../vuetify/src/components/VImg/index.ts | 4 + .../vuetify/src/components/VInput/VInput.ts | 311 + .../vuetify/src/components/VInput/index.ts | 4 + .../src/components/VItemGroup/VItem.ts | 56 + .../src/components/VItemGroup/VItemGroup.ts | 234 + .../src/components/VItemGroup/index.ts | 14 + .../src/components/VJumbotron/VJumbotron.js | 97 + .../src/components/VJumbotron/index.js | 4 + .../vuetify/src/components/VLabel/VLabel.ts | 64 + .../vuetify/src/components/VLabel/index.ts | 4 + .../vuetify/src/components/VList/VList.ts | 81 + .../src/components/VList/VListGroup.ts | 204 + .../vuetify/src/components/VList/VListTile.ts | 90 + .../src/components/VList/VListTileAction.ts | 19 + .../src/components/VList/VListTileAvatar.ts | 35 + .../vuetify/src/components/VList/index.ts | 27 + .../vuetify/src/components/VMenu/VMenu.js | 249 + .../vuetify/src/components/VMenu/index.js | 4 + .../components/VMenu/mixins/menu-activator.js | 51 + .../VMenu/mixins/menu-generators.js | 97 + .../components/VMenu/mixins/menu-keyable.js | 78 + .../components/VMenu/mixins/menu-position.js | 49 + .../src/components/VMessages/VMessages.ts | 51 + .../vuetify/src/components/VMessages/index.ts | 4 + .../VNavigationDrawer/VNavigationDrawer.ts | 357 + .../src/components/VNavigationDrawer/index.ts | 4 + .../components/VOverflowBtn/VOverflowBtn.js | 99 + .../src/components/VOverflowBtn/index.js | 4 + .../src/components/VPagination/VPagination.ts | 193 + .../src/components/VPagination/index.ts | 4 + .../src/components/VParallax/VParallax.ts | 108 + .../vuetify/src/components/VParallax/index.ts | 4 + .../vuetify/src/components/VPicker/VPicker.ts | 87 + .../vuetify/src/components/VPicker/index.ts | 4 + .../VProgressCircular/VProgressCircular.ts | 150 + .../src/components/VProgressCircular/index.ts | 4 + .../VProgressLinear/VProgressLinear.ts | 186 + .../src/components/VProgressLinear/index.ts | 4 + .../src/components/VRadioGroup/VRadio.js | 156 + .../src/components/VRadioGroup/VRadioGroup.js | 132 + .../src/components/VRadioGroup/index.js | 11 + .../components/VRangeSlider/VRangeSlider.js | 155 + .../src/components/VRangeSlider/index.js | 4 + .../vuetify/src/components/VRating/VRating.ts | 228 + .../vuetify/src/components/VRating/index.ts | 4 + .../src/components/VResponsive/VResponsive.ts | 57 + .../src/components/VResponsive/index.ts | 4 + .../vuetify/src/components/VSelect/VSelect.js | 718 + .../src/components/VSelect/VSelectList.js | 245 + .../vuetify/src/components/VSelect/index.js | 78 + .../vuetify/src/components/VSheet/VSheet.ts | 60 + .../vuetify/src/components/VSheet/index.ts | 4 + .../vuetify/src/components/VSlider/VSlider.js | 520 + .../vuetify/src/components/VSlider/index.js | 4 + .../src/components/VSnackbar/VSnackbar.ts | 92 + .../vuetify/src/components/VSnackbar/index.ts | 4 + .../src/components/VSparkline/VSparkline.ts | 424 + .../src/components/VSparkline/helpers/core.ts | 32 + .../src/components/VSparkline/helpers/math.ts | 31 + .../src/components/VSparkline/helpers/path.ts | 37 + .../src/components/VSparkline/index.ts | 5 + .../src/components/VSpeedDial/VSpeedDial.js | 95 + .../src/components/VSpeedDial/index.js | 4 + .../src/components/VStepper/VStepper.ts | 114 + .../components/VStepper/VStepperContent.ts | 176 + .../src/components/VStepper/VStepperStep.ts | 150 + .../vuetify/src/components/VStepper/index.ts | 25 + .../src/components/VSubheader/VSubheader.ts | 32 + .../src/components/VSubheader/index.ts | 4 + .../vuetify/src/components/VSwitch/VSwitch.js | 107 + .../vuetify/src/components/VSwitch/index.js | 4 + .../src/components/VSystemBar/VSystemBar.ts | 72 + .../src/components/VSystemBar/index.ts | 4 + .../vuetify/src/components/VTabs/VTab.js | 103 + .../vuetify/src/components/VTabs/VTabItem.js | 29 + .../vuetify/src/components/VTabs/VTabs.js | 239 + .../src/components/VTabs/VTabsItems.js | 65 + .../src/components/VTabs/VTabsSlider.js | 14 + .../vuetify/src/components/VTabs/index.js | 17 + .../components/VTabs/mixins/tabs-computed.js | 33 + .../VTabs/mixins/tabs-generators.js | 98 + .../src/components/VTabs/mixins/tabs-props.js | 49 + .../src/components/VTabs/mixins/tabs-touch.js | 41 + .../components/VTabs/mixins/tabs-watchers.js | 50 + .../src/components/VTextField/VTextField.js | 427 + .../src/components/VTextField/index.js | 42 + .../src/components/VTextarea/VTextarea.js | 110 + .../vuetify/src/components/VTextarea/index.js | 4 + .../src/components/VTimePicker/VTimePicker.ts | 324 + .../VTimePicker/VTimePickerClock.ts | 265 + .../VTimePicker/VTimePickerTitle.ts | 78 + .../src/components/VTimePicker/index.ts | 13 + .../src/components/VTimeline/VTimeline.ts | 38 + .../src/components/VTimeline/VTimelineItem.ts | 99 + .../vuetify/src/components/VTimeline/index.ts | 11 + .../src/components/VToolbar/VToolbar.ts | 266 + .../components/VToolbar/VToolbarSideIcon.ts | 29 + .../vuetify/src/components/VToolbar/index.ts | 18 + .../src/components/VTooltip/VTooltip.js | 212 + .../vuetify/src/components/VTooltip/index.js | 4 + .../src/components/VTreeview/VTreeview.ts | 389 + .../src/components/VTreeview/VTreeviewNode.ts | 303 + .../vuetify/src/components/VTreeview/index.ts | 11 + .../VTreeview/util/filterTreeItems.ts | 40 + .../vuetify/src/components/VWindow/VWindow.ts | 133 + .../src/components/VWindow/VWindowItem.ts | 159 + .../vuetify/src/components/VWindow/index.ts | 11 + .../Vuetify/goTo/easing-patterns.ts | 28 + .../src/components/Vuetify/goTo/index.ts | 59 + .../src/components/Vuetify/goTo/util.ts | 49 + .../vuetify/src/components/Vuetify/index.ts | 90 + .../components/Vuetify/mixins/application.ts | 40 + .../components/Vuetify/mixins/breakpoint.ts | 152 + .../src/components/Vuetify/mixins/icons.ts | 153 + .../src/components/Vuetify/mixins/lang.ts | 43 + .../src/components/Vuetify/mixins/options.ts | 15 + .../src/components/Vuetify/mixins/theme.ts | 21 + .../src/components/Vuetify/util/goTo.js | 6 + node_modules/vuetify/src/components/index.ts | 67 + .../transitions/expand-transition.js | 65 + .../src/components/transitions/index.js | 61 + .../vuetify/src/directives/click-outside.ts | 80 + node_modules/vuetify/src/directives/index.ts | 21 + node_modules/vuetify/src/directives/resize.ts | 34 + node_modules/vuetify/src/directives/ripple.ts | 229 + node_modules/vuetify/src/directives/scroll.ts | 37 + node_modules/vuetify/src/directives/touch.ts | 141 + node_modules/vuetify/src/entry-lib.ts | 6 + node_modules/vuetify/src/globals.d.ts | 124 + node_modules/vuetify/src/index.ts | 23 + node_modules/vuetify/src/locale/af.ts | 18 + node_modules/vuetify/src/locale/ar.ts | 18 + node_modules/vuetify/src/locale/ca.ts | 18 + node_modules/vuetify/src/locale/de.ts | 18 + node_modules/vuetify/src/locale/el.ts | 18 + node_modules/vuetify/src/locale/en.ts | 18 + node_modules/vuetify/src/locale/es.ts | 18 + node_modules/vuetify/src/locale/et.ts | 18 + node_modules/vuetify/src/locale/fa.ts | 18 + node_modules/vuetify/src/locale/fr.ts | 18 + node_modules/vuetify/src/locale/gr.ts | 18 + node_modules/vuetify/src/locale/hr.ts | 18 + node_modules/vuetify/src/locale/hu.ts | 18 + node_modules/vuetify/src/locale/id.ts | 18 + node_modules/vuetify/src/locale/index.ts | 27 + node_modules/vuetify/src/locale/it.ts | 18 + node_modules/vuetify/src/locale/ja.ts | 18 + node_modules/vuetify/src/locale/nl.ts | 18 + node_modules/vuetify/src/locale/pl.ts | 18 + node_modules/vuetify/src/locale/pt.ts | 18 + node_modules/vuetify/src/locale/ro.ts | 18 + node_modules/vuetify/src/locale/ru.ts | 18 + node_modules/vuetify/src/locale/sl.ts | 18 + node_modules/vuetify/src/locale/sr-Cyrl.ts | 18 + node_modules/vuetify/src/locale/th.ts | 18 + node_modules/vuetify/src/locale/tr.ts | 18 + node_modules/vuetify/src/locale/uk.ts | 18 + node_modules/vuetify/src/locale/zh-Hans.ts | 18 + node_modules/vuetify/src/locale/zh-Hant.ts | 18 + .../vuetify/src/mixins/applicationable.ts | 79 + node_modules/vuetify/src/mixins/bootable.ts | 44 + .../vuetify/src/mixins/button-group.ts | 26 + node_modules/vuetify/src/mixins/colorable.ts | 53 + node_modules/vuetify/src/mixins/comparable.ts | 13 + .../vuetify/src/mixins/data-iterable.js | 495 + node_modules/vuetify/src/mixins/delayable.ts | 50 + node_modules/vuetify/src/mixins/dependent.ts | 80 + node_modules/vuetify/src/mixins/detachable.js | 119 + node_modules/vuetify/src/mixins/elevatable.ts | 20 + node_modules/vuetify/src/mixins/filterable.ts | 13 + node_modules/vuetify/src/mixins/groupable.ts | 72 + node_modules/vuetify/src/mixins/loadable.ts | 43 + node_modules/vuetify/src/mixins/maskable.js | 153 + node_modules/vuetify/src/mixins/measurable.ts | 43 + node_modules/vuetify/src/mixins/menuable.js | 390 + .../vuetify/src/mixins/overlayable.ts | 224 + .../vuetify/src/mixins/picker-button.ts | 38 + node_modules/vuetify/src/mixins/picker.ts | 71 + .../vuetify/src/mixins/positionable.ts | 54 + node_modules/vuetify/src/mixins/proxyable.ts | 60 + .../vuetify/src/mixins/registrable.ts | 50 + node_modules/vuetify/src/mixins/returnable.ts | 34 + node_modules/vuetify/src/mixins/rippleable.ts | 38 + node_modules/vuetify/src/mixins/routable.ts | 96 + node_modules/vuetify/src/mixins/selectable.js | 146 + node_modules/vuetify/src/mixins/sizeable.ts | 15 + .../vuetify/src/mixins/ssr-bootable.ts | 27 + node_modules/vuetify/src/mixins/stackable.ts | 63 + node_modules/vuetify/src/mixins/themeable.ts | 109 + node_modules/vuetify/src/mixins/toggleable.ts | 37 + .../vuetify/src/mixins/transitionable.ts | 11 + .../vuetify/src/mixins/translatable.ts | 60 + .../vuetify/src/mixins/validatable.ts | 239 + node_modules/vuetify/src/stylus/app.styl | 5 + .../vuetify/src/stylus/bootstrap.styl | 2 + node_modules/vuetify/src/stylus/browsers.styl | 3 + .../src/stylus/components/_alerts.styl | 56 + .../vuetify/src/stylus/components/_app.styl | 45 + .../src/stylus/components/_autocompletes.styl | 26 + .../src/stylus/components/_avatars.styl | 26 + .../src/stylus/components/_badges.styl | 70 + .../src/stylus/components/_bottom-navs.styl | 92 + .../src/stylus/components/_bottom-sheets.styl | 18 + .../src/stylus/components/_breadcrumbs.styl | 44 + .../src/stylus/components/_button-toggle.styl | 54 + .../src/stylus/components/_buttons.styl | 332 + .../stylus/components/_calendar-daily.styl | 107 + .../stylus/components/_calendar-weekly.styl | 82 + .../vuetify/src/stylus/components/_cards.styl | 58 + .../src/stylus/components/_carousel.styl | 76 + .../vuetify/src/stylus/components/_chips.styl | 158 + .../src/stylus/components/_content.styl | 18 + .../src/stylus/components/_counters.styl | 14 + .../src/stylus/components/_data-iterator.styl | 59 + .../src/stylus/components/_data-table.styl | 129 + .../components/_date-picker-header.styl | 49 + .../stylus/components/_date-picker-table.styl | 84 + .../stylus/components/_date-picker-title.styl | 36 + .../stylus/components/_date-picker-years.styl | 27 + .../src/stylus/components/_dialogs.styl | 86 + .../src/stylus/components/_dividers.styl | 38 + .../stylus/components/_expansion-panel.styl | 92 + .../src/stylus/components/_footer.styl | 32 + .../vuetify/src/stylus/components/_forms.styl | 14 + .../vuetify/src/stylus/components/_grid.styl | 218 + .../vuetify/src/stylus/components/_icons.styl | 37 + .../src/stylus/components/_images.styl | 25 + .../src/stylus/components/_inputs.styl | 112 + .../src/stylus/components/_item-group.styl | 10 + .../src/stylus/components/_jumbotrons.styl | 44 + .../src/stylus/components/_labels.styl | 16 + .../vuetify/src/stylus/components/_lists.styl | 301 + .../vuetify/src/stylus/components/_menus.styl | 77 + .../src/stylus/components/_messages.styl | 26 + .../stylus/components/_navigation-drawer.styl | 113 + .../stylus/components/_overflow-buttons.styl | 114 + .../src/stylus/components/_overlay.styl | 44 + .../src/stylus/components/_pagination.styl | 86 + .../src/stylus/components/_parallax.styl | 37 + .../src/stylus/components/_pickers.styl | 80 + .../stylus/components/_progress-circular.styl | 61 + .../stylus/components/_progress-linear.styl | 111 + .../src/stylus/components/_radio-group.styl | 25 + .../src/stylus/components/_radios.styl | 23 + .../src/stylus/components/_range-sliders.styl | 22 + .../src/stylus/components/_rating.styl | 13 + .../src/stylus/components/_responsive.styl | 14 + .../src/stylus/components/_ripples.styl | 34 + .../src/stylus/components/_select.styl | 119 + .../components/_selection-controls.styl | 98 + .../vuetify/src/stylus/components/_sheet.styl | 19 + .../src/stylus/components/_sliders.styl | 258 + .../src/stylus/components/_small-dialog.styl | 35 + .../src/stylus/components/_snackbars.styl | 141 + .../src/stylus/components/_speed-dial.styl | 79 + .../src/stylus/components/_steppers.styl | 215 + .../src/stylus/components/_subheaders.styl | 18 + .../src/stylus/components/_switch.styl | 69 + .../src/stylus/components/_system-bars.styl | 46 + .../src/stylus/components/_tables.styl | 100 + .../vuetify/src/stylus/components/_tabs.styl | 153 + .../src/stylus/components/_text-fields.styl | 341 + .../src/stylus/components/_textarea.styl | 90 + .../stylus/components/_time-picker-clock.styl | 128 + .../stylus/components/_time-picker-title.styl | 48 + .../src/stylus/components/_timeline.styl | 185 + .../src/stylus/components/_toolbar.styl | 159 + .../src/stylus/components/_tooltips.styl | 27 + .../src/stylus/components/_treeview.styl | 98 + .../src/stylus/components/_windows.styl | 51 + .../src/stylus/elements/_blockquote.styl | 4 + .../vuetify/src/stylus/elements/_code.styl | 20 + .../vuetify/src/stylus/elements/_global.styl | 15 + .../src/stylus/elements/_headings.styl | 4 + .../vuetify/src/stylus/elements/_lists.styl | 2 + .../src/stylus/elements/_typography.styl | 60 + .../src/stylus/generic/_animations.styl | 9 + .../vuetify/src/stylus/generic/_colors.styl | 35 + .../src/stylus/generic/_elevations.styl | 6 + .../vuetify/src/stylus/generic/_reset.styl | 332 + .../src/stylus/generic/_transitions.styl | 224 + node_modules/vuetify/src/stylus/main.styl | 2 + .../vuetify/src/stylus/settings/_colors.styl | 339 + .../src/stylus/settings/_elevations.styl | 91 + .../vuetify/src/stylus/settings/_rtl.styl | 5 + .../vuetify/src/stylus/settings/_theme.styl | 230 + .../src/stylus/settings/_variables.styl | 347 + node_modules/vuetify/src/stylus/theme.styl | 13 + .../vuetify/src/stylus/tools/_bootable.styl | 5 + .../vuetify/src/stylus/trumps/_display.styl | 14 + .../vuetify/src/stylus/trumps/_helpers.styl | 5 + .../vuetify/src/stylus/trumps/_spacing.styl | 63 + .../vuetify/src/stylus/trumps/_text.styl | 42 + .../src/stylus/trumps/_transition.styl | 3 + .../vuetify/src/util/ThemeProvider.ts | 22 + .../vuetify/src/util/color/transformCIELAB.ts | 36 + .../vuetify/src/util/color/transformSRGB.ts | 69 + node_modules/vuetify/src/util/colorUtils.ts | 46 + node_modules/vuetify/src/util/colors.ts | 339 + node_modules/vuetify/src/util/component.ts | 21 + node_modules/vuetify/src/util/console.ts | 103 + .../vuetify/src/util/dedupeModelListeners.ts | 18 + .../vuetify/src/util/easing-patterns.js | 5 + node_modules/vuetify/src/util/helpers.spec.js | 16 + node_modules/vuetify/src/util/helpers.ts | 381 + node_modules/vuetify/src/util/mask.ts | 87 + node_modules/vuetify/src/util/mixins.ts | 21 + .../src/util/rebuildFunctionalSlots.ts | 13 + node_modules/vuetify/src/util/theme.ts | 146 + node_modules/vuetify/types/alacarte.d.ts | 38 + node_modules/vuetify/types/colors.d.ts | 107 + node_modules/vuetify/types/index.d.ts | 208 + node_modules/vuetify/types/lang.d.ts | 10 + node_modules/vuetify/types/lib.d.ts | 279 + package-lock.json | 19 +- package.json | 5 +- public/index.html | 14 +- public/lib/vue.js | 21629 +++++++------ public/main.js | 1 + public/routes/createMessage.js | 77 +- public/routes/profil.js | 4 +- public/routes/vuetifyImport.js | 4 + 1846 files changed, 219701 insertions(+), 53848 deletions(-) create mode 100644 node_modules/mongoose/lib/helpers/query/castFilterPath.js create mode 100644 node_modules/mongoose/lib/helpers/update/castArrayFilters.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/HISTORY.md create mode 100644 node_modules/mongoose/node_modules/mongodb-core/LICENSE create mode 100644 node_modules/mongoose/node_modules/mongodb-core/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb-core/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/gssapi.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/mongocr.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/plain.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/sspi.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/auth/x509.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/apm.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/command_result.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/commands.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/logger.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/connection/utils.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/error.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/monitoring.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_description.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_selectors.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology_description.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/sessions.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/tools/smoke_plugin.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/topologies/mongos.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/topologies/read_preference.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset_state.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/topologies/shared.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/transactions.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/uri_parser.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/utils.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/compression.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/shared.js create mode 100644 node_modules/mongoose/node_modules/mongodb-core/package.json create mode 100644 node_modules/mongoose/node_modules/mongodb/HISTORY.md create mode 100644 node_modules/mongoose/node_modules/mongodb/LICENSE.md create mode 100644 node_modules/mongoose/node_modules/mongodb/README.md create mode 100644 node_modules/mongoose/node_modules/mongodb/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/admin.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/apm.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/authenticate.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/change_stream.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/collection.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/constants.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/cursor.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/db.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/error.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/url_parser.js create mode 100644 node_modules/mongoose/node_modules/mongodb/lib/utils.js create mode 100644 node_modules/mongoose/node_modules/mongodb/package.json create mode 100644 node_modules/mongoose/search.js create mode 100644 node_modules/vue/dist/vue.common.dev.js create mode 100644 node_modules/vue/dist/vue.common.prod.js create mode 100644 node_modules/vue/dist/vue.esm.browser.min.js create mode 100644 node_modules/vue/dist/vue.runtime.common.dev.js create mode 100644 node_modules/vue/dist/vue.runtime.common.prod.js create mode 100644 node_modules/vue/src/compiler/codeframe.js create mode 100644 node_modules/vue/src/core/instance/render-helpers/bind-dynamic-keys.js create mode 100644 node_modules/vue/src/core/instance/render-helpers/resolve-scoped-slots.js create mode 100644 node_modules/vue/src/core/vdom/helpers/normalize-scoped-slots.js create mode 100644 node_modules/vuetify/LICENSE.md create mode 100644 node_modules/vuetify/dist/vuetify.css create mode 100644 node_modules/vuetify/dist/vuetify.css.map create mode 100644 node_modules/vuetify/dist/vuetify.js create mode 100644 node_modules/vuetify/dist/vuetify.js.map create mode 100644 node_modules/vuetify/dist/vuetify.min.css create mode 100644 node_modules/vuetify/dist/vuetify.min.js create mode 100644 node_modules/vuetify/es5/components/VAlert/VAlert.js create mode 100644 node_modules/vuetify/es5/components/VAlert/VAlert.js.map create mode 100644 node_modules/vuetify/es5/components/VAlert/index.js create mode 100644 node_modules/vuetify/es5/components/VAlert/index.js.map create mode 100644 node_modules/vuetify/es5/components/VApp/VApp.js create mode 100644 node_modules/vuetify/es5/components/VApp/VApp.js.map create mode 100644 node_modules/vuetify/es5/components/VApp/index.js create mode 100644 node_modules/vuetify/es5/components/VApp/index.js.map create mode 100644 node_modules/vuetify/es5/components/VApp/mixins/app-theme.js create mode 100644 node_modules/vuetify/es5/components/VApp/mixins/app-theme.js.map create mode 100644 node_modules/vuetify/es5/components/VAutocomplete/VAutocomplete.js create mode 100644 node_modules/vuetify/es5/components/VAutocomplete/VAutocomplete.js.map create mode 100644 node_modules/vuetify/es5/components/VAutocomplete/index.js create mode 100644 node_modules/vuetify/es5/components/VAutocomplete/index.js.map create mode 100644 node_modules/vuetify/es5/components/VAvatar/VAvatar.js create mode 100644 node_modules/vuetify/es5/components/VAvatar/VAvatar.js.map create mode 100644 node_modules/vuetify/es5/components/VAvatar/index.js create mode 100644 node_modules/vuetify/es5/components/VAvatar/index.js.map create mode 100644 node_modules/vuetify/es5/components/VBadge/VBadge.js create mode 100644 node_modules/vuetify/es5/components/VBadge/VBadge.js.map create mode 100644 node_modules/vuetify/es5/components/VBadge/index.js create mode 100644 node_modules/vuetify/es5/components/VBadge/index.js.map create mode 100644 node_modules/vuetify/es5/components/VBottomNav/VBottomNav.js create mode 100644 node_modules/vuetify/es5/components/VBottomNav/VBottomNav.js.map create mode 100644 node_modules/vuetify/es5/components/VBottomNav/index.js create mode 100644 node_modules/vuetify/es5/components/VBottomNav/index.js.map create mode 100644 node_modules/vuetify/es5/components/VBottomSheet/VBottomSheet.js create mode 100644 node_modules/vuetify/es5/components/VBottomSheet/VBottomSheet.js.map create mode 100644 node_modules/vuetify/es5/components/VBottomSheet/index.js create mode 100644 node_modules/vuetify/es5/components/VBottomSheet/index.js.map create mode 100644 node_modules/vuetify/es5/components/VBreadcrumbs/VBreadcrumbs.js create mode 100644 node_modules/vuetify/es5/components/VBreadcrumbs/VBreadcrumbs.js.map create mode 100644 node_modules/vuetify/es5/components/VBreadcrumbs/VBreadcrumbsItem.js create mode 100644 node_modules/vuetify/es5/components/VBreadcrumbs/VBreadcrumbsItem.js.map create mode 100644 node_modules/vuetify/es5/components/VBreadcrumbs/index.js create mode 100644 node_modules/vuetify/es5/components/VBreadcrumbs/index.js.map create mode 100644 node_modules/vuetify/es5/components/VBtn/VBtn.js create mode 100644 node_modules/vuetify/es5/components/VBtn/VBtn.js.map create mode 100644 node_modules/vuetify/es5/components/VBtn/index.js create mode 100644 node_modules/vuetify/es5/components/VBtn/index.js.map create mode 100644 node_modules/vuetify/es5/components/VBtnToggle/VBtnToggle.js create mode 100644 node_modules/vuetify/es5/components/VBtnToggle/VBtnToggle.js.map create mode 100644 node_modules/vuetify/es5/components/VBtnToggle/index.js create mode 100644 node_modules/vuetify/es5/components/VBtnToggle/index.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendar.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendar.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendarDaily.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendarDaily.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendarMonthly.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendarMonthly.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendarWeekly.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/VCalendarWeekly.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/index.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/index.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/calendar-base.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/calendar-base.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/calendar-with-intervals.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/calendar-with-intervals.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/mouse.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/mouse.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/times.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/mixins/times.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/util/props.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/util/props.js.map create mode 100644 node_modules/vuetify/es5/components/VCalendar/util/timestamp.js create mode 100644 node_modules/vuetify/es5/components/VCalendar/util/timestamp.js.map create mode 100644 node_modules/vuetify/es5/components/VCard/VCard.js create mode 100644 node_modules/vuetify/es5/components/VCard/VCard.js.map create mode 100644 node_modules/vuetify/es5/components/VCard/VCardMedia.js create mode 100644 node_modules/vuetify/es5/components/VCard/VCardMedia.js.map create mode 100644 node_modules/vuetify/es5/components/VCard/VCardTitle.js create mode 100644 node_modules/vuetify/es5/components/VCard/VCardTitle.js.map create mode 100644 node_modules/vuetify/es5/components/VCard/index.js create mode 100644 node_modules/vuetify/es5/components/VCard/index.js.map create mode 100644 node_modules/vuetify/es5/components/VCarousel/VCarousel.js create mode 100644 node_modules/vuetify/es5/components/VCarousel/VCarousel.js.map create mode 100644 node_modules/vuetify/es5/components/VCarousel/VCarouselItem.js create mode 100644 node_modules/vuetify/es5/components/VCarousel/VCarouselItem.js.map create mode 100644 node_modules/vuetify/es5/components/VCarousel/index.js create mode 100644 node_modules/vuetify/es5/components/VCarousel/index.js.map create mode 100644 node_modules/vuetify/es5/components/VCheckbox/VCheckbox.js create mode 100644 node_modules/vuetify/es5/components/VCheckbox/VCheckbox.js.map create mode 100644 node_modules/vuetify/es5/components/VCheckbox/index.js create mode 100644 node_modules/vuetify/es5/components/VCheckbox/index.js.map create mode 100644 node_modules/vuetify/es5/components/VChip/VChip.js create mode 100644 node_modules/vuetify/es5/components/VChip/VChip.js.map create mode 100644 node_modules/vuetify/es5/components/VChip/index.js create mode 100644 node_modules/vuetify/es5/components/VChip/index.js.map create mode 100644 node_modules/vuetify/es5/components/VCombobox/VCombobox.js create mode 100644 node_modules/vuetify/es5/components/VCombobox/VCombobox.js.map create mode 100644 node_modules/vuetify/es5/components/VCombobox/index.js create mode 100644 node_modules/vuetify/es5/components/VCombobox/index.js.map create mode 100644 node_modules/vuetify/es5/components/VCounter/VCounter.js create mode 100644 node_modules/vuetify/es5/components/VCounter/VCounter.js.map create mode 100644 node_modules/vuetify/es5/components/VCounter/index.js create mode 100644 node_modules/vuetify/es5/components/VCounter/index.js.map create mode 100644 node_modules/vuetify/es5/components/VDataIterator/VDataIterator.js create mode 100644 node_modules/vuetify/es5/components/VDataIterator/VDataIterator.js.map create mode 100644 node_modules/vuetify/es5/components/VDataIterator/index.js create mode 100644 node_modules/vuetify/es5/components/VDataIterator/index.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/VDataTable.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/VDataTable.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/VEditDialog.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/VEditDialog.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/index.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/index.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/body.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/body.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/foot.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/foot.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/head.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/head.js.map create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/progress.js create mode 100644 node_modules/vuetify/es5/components/VDataTable/mixins/progress.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePicker.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePicker.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerDateTable.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerDateTable.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerHeader.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerHeader.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerMonthTable.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerMonthTable.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerTitle.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerTitle.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerYears.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/VDatePickerYears.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/index.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/index.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/mixins/date-picker-table.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/mixins/date-picker-table.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/createNativeLocaleFormatter.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/createNativeLocaleFormatter.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/index.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/index.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/isDateAllowed.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/isDateAllowed.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/monthChange.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/monthChange.js.map create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/pad.js create mode 100644 node_modules/vuetify/es5/components/VDatePicker/util/pad.js.map create mode 100644 node_modules/vuetify/es5/components/VDialog/VDialog.js create mode 100644 node_modules/vuetify/es5/components/VDialog/VDialog.js.map create mode 100644 node_modules/vuetify/es5/components/VDialog/index.js create mode 100644 node_modules/vuetify/es5/components/VDialog/index.js.map create mode 100644 node_modules/vuetify/es5/components/VDivider/VDivider.js create mode 100644 node_modules/vuetify/es5/components/VDivider/VDivider.js.map create mode 100644 node_modules/vuetify/es5/components/VDivider/index.js create mode 100644 node_modules/vuetify/es5/components/VDivider/index.js.map create mode 100644 node_modules/vuetify/es5/components/VExpansionPanel/VExpansionPanel.js create mode 100644 node_modules/vuetify/es5/components/VExpansionPanel/VExpansionPanel.js.map create mode 100644 node_modules/vuetify/es5/components/VExpansionPanel/VExpansionPanelContent.js create mode 100644 node_modules/vuetify/es5/components/VExpansionPanel/VExpansionPanelContent.js.map create mode 100644 node_modules/vuetify/es5/components/VExpansionPanel/index.js create mode 100644 node_modules/vuetify/es5/components/VExpansionPanel/index.js.map create mode 100644 node_modules/vuetify/es5/components/VFooter/VFooter.js create mode 100644 node_modules/vuetify/es5/components/VFooter/VFooter.js.map create mode 100644 node_modules/vuetify/es5/components/VFooter/index.js create mode 100644 node_modules/vuetify/es5/components/VFooter/index.js.map create mode 100644 node_modules/vuetify/es5/components/VForm/VForm.js create mode 100644 node_modules/vuetify/es5/components/VForm/VForm.js.map create mode 100644 node_modules/vuetify/es5/components/VForm/index.js create mode 100644 node_modules/vuetify/es5/components/VForm/index.js.map create mode 100644 node_modules/vuetify/es5/components/VGrid/VContainer.js create mode 100644 node_modules/vuetify/es5/components/VGrid/VContainer.js.map create mode 100644 node_modules/vuetify/es5/components/VGrid/VContent.js create mode 100644 node_modules/vuetify/es5/components/VGrid/VContent.js.map create mode 100644 node_modules/vuetify/es5/components/VGrid/VFlex.js create mode 100644 node_modules/vuetify/es5/components/VGrid/VFlex.js.map create mode 100644 node_modules/vuetify/es5/components/VGrid/VLayout.js create mode 100644 node_modules/vuetify/es5/components/VGrid/VLayout.js.map create mode 100644 node_modules/vuetify/es5/components/VGrid/grid.js create mode 100644 node_modules/vuetify/es5/components/VGrid/grid.js.map create mode 100644 node_modules/vuetify/es5/components/VGrid/index.js create mode 100644 node_modules/vuetify/es5/components/VGrid/index.js.map create mode 100644 node_modules/vuetify/es5/components/VHover/VHover.js create mode 100644 node_modules/vuetify/es5/components/VHover/VHover.js.map create mode 100644 node_modules/vuetify/es5/components/VHover/index.js create mode 100644 node_modules/vuetify/es5/components/VHover/index.js.map create mode 100644 node_modules/vuetify/es5/components/VIcon/VIcon.js create mode 100644 node_modules/vuetify/es5/components/VIcon/VIcon.js.map create mode 100644 node_modules/vuetify/es5/components/VIcon/index.js create mode 100644 node_modules/vuetify/es5/components/VIcon/index.js.map create mode 100644 node_modules/vuetify/es5/components/VImg/VImg.js create mode 100644 node_modules/vuetify/es5/components/VImg/VImg.js.map create mode 100644 node_modules/vuetify/es5/components/VImg/index.js create mode 100644 node_modules/vuetify/es5/components/VImg/index.js.map create mode 100644 node_modules/vuetify/es5/components/VInput/VInput.js create mode 100644 node_modules/vuetify/es5/components/VInput/VInput.js.map create mode 100644 node_modules/vuetify/es5/components/VInput/index.js create mode 100644 node_modules/vuetify/es5/components/VInput/index.js.map create mode 100644 node_modules/vuetify/es5/components/VItemGroup/VItem.js create mode 100644 node_modules/vuetify/es5/components/VItemGroup/VItem.js.map create mode 100644 node_modules/vuetify/es5/components/VItemGroup/VItemGroup.js create mode 100644 node_modules/vuetify/es5/components/VItemGroup/VItemGroup.js.map create mode 100644 node_modules/vuetify/es5/components/VItemGroup/index.js create mode 100644 node_modules/vuetify/es5/components/VItemGroup/index.js.map create mode 100644 node_modules/vuetify/es5/components/VJumbotron/VJumbotron.js create mode 100644 node_modules/vuetify/es5/components/VJumbotron/VJumbotron.js.map create mode 100644 node_modules/vuetify/es5/components/VJumbotron/index.js create mode 100644 node_modules/vuetify/es5/components/VJumbotron/index.js.map create mode 100644 node_modules/vuetify/es5/components/VLabel/VLabel.js create mode 100644 node_modules/vuetify/es5/components/VLabel/VLabel.js.map create mode 100644 node_modules/vuetify/es5/components/VLabel/index.js create mode 100644 node_modules/vuetify/es5/components/VLabel/index.js.map create mode 100644 node_modules/vuetify/es5/components/VList/VList.js create mode 100644 node_modules/vuetify/es5/components/VList/VList.js.map create mode 100644 node_modules/vuetify/es5/components/VList/VListGroup.js create mode 100644 node_modules/vuetify/es5/components/VList/VListGroup.js.map create mode 100644 node_modules/vuetify/es5/components/VList/VListTile.js create mode 100644 node_modules/vuetify/es5/components/VList/VListTile.js.map create mode 100644 node_modules/vuetify/es5/components/VList/VListTileAction.js create mode 100644 node_modules/vuetify/es5/components/VList/VListTileAction.js.map create mode 100644 node_modules/vuetify/es5/components/VList/VListTileAvatar.js create mode 100644 node_modules/vuetify/es5/components/VList/VListTileAvatar.js.map create mode 100644 node_modules/vuetify/es5/components/VList/index.js create mode 100644 node_modules/vuetify/es5/components/VList/index.js.map create mode 100644 node_modules/vuetify/es5/components/VMenu/VMenu.js create mode 100644 node_modules/vuetify/es5/components/VMenu/VMenu.js.map create mode 100644 node_modules/vuetify/es5/components/VMenu/index.js create mode 100644 node_modules/vuetify/es5/components/VMenu/index.js.map create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-activator.js create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-activator.js.map create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-generators.js create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-generators.js.map create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-keyable.js create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-keyable.js.map create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-position.js create mode 100644 node_modules/vuetify/es5/components/VMenu/mixins/menu-position.js.map create mode 100644 node_modules/vuetify/es5/components/VMessages/VMessages.js create mode 100644 node_modules/vuetify/es5/components/VMessages/VMessages.js.map create mode 100644 node_modules/vuetify/es5/components/VMessages/index.js create mode 100644 node_modules/vuetify/es5/components/VMessages/index.js.map create mode 100644 node_modules/vuetify/es5/components/VNavigationDrawer/VNavigationDrawer.js create mode 100644 node_modules/vuetify/es5/components/VNavigationDrawer/VNavigationDrawer.js.map create mode 100644 node_modules/vuetify/es5/components/VNavigationDrawer/index.js create mode 100644 node_modules/vuetify/es5/components/VNavigationDrawer/index.js.map create mode 100644 node_modules/vuetify/es5/components/VOverflowBtn/VOverflowBtn.js create mode 100644 node_modules/vuetify/es5/components/VOverflowBtn/VOverflowBtn.js.map create mode 100644 node_modules/vuetify/es5/components/VOverflowBtn/index.js create mode 100644 node_modules/vuetify/es5/components/VOverflowBtn/index.js.map create mode 100644 node_modules/vuetify/es5/components/VPagination/VPagination.js create mode 100644 node_modules/vuetify/es5/components/VPagination/VPagination.js.map create mode 100644 node_modules/vuetify/es5/components/VPagination/index.js create mode 100644 node_modules/vuetify/es5/components/VPagination/index.js.map create mode 100644 node_modules/vuetify/es5/components/VParallax/VParallax.js create mode 100644 node_modules/vuetify/es5/components/VParallax/VParallax.js.map create mode 100644 node_modules/vuetify/es5/components/VParallax/index.js create mode 100644 node_modules/vuetify/es5/components/VParallax/index.js.map create mode 100644 node_modules/vuetify/es5/components/VPicker/VPicker.js create mode 100644 node_modules/vuetify/es5/components/VPicker/VPicker.js.map create mode 100644 node_modules/vuetify/es5/components/VPicker/index.js create mode 100644 node_modules/vuetify/es5/components/VPicker/index.js.map create mode 100644 node_modules/vuetify/es5/components/VProgressCircular/VProgressCircular.js create mode 100644 node_modules/vuetify/es5/components/VProgressCircular/VProgressCircular.js.map create mode 100644 node_modules/vuetify/es5/components/VProgressCircular/index.js create mode 100644 node_modules/vuetify/es5/components/VProgressCircular/index.js.map create mode 100644 node_modules/vuetify/es5/components/VProgressLinear/VProgressLinear.js create mode 100644 node_modules/vuetify/es5/components/VProgressLinear/VProgressLinear.js.map create mode 100644 node_modules/vuetify/es5/components/VProgressLinear/index.js create mode 100644 node_modules/vuetify/es5/components/VProgressLinear/index.js.map create mode 100644 node_modules/vuetify/es5/components/VRadioGroup/VRadio.js create mode 100644 node_modules/vuetify/es5/components/VRadioGroup/VRadio.js.map create mode 100644 node_modules/vuetify/es5/components/VRadioGroup/VRadioGroup.js create mode 100644 node_modules/vuetify/es5/components/VRadioGroup/VRadioGroup.js.map create mode 100644 node_modules/vuetify/es5/components/VRadioGroup/index.js create mode 100644 node_modules/vuetify/es5/components/VRadioGroup/index.js.map create mode 100644 node_modules/vuetify/es5/components/VRangeSlider/VRangeSlider.js create mode 100644 node_modules/vuetify/es5/components/VRangeSlider/VRangeSlider.js.map create mode 100644 node_modules/vuetify/es5/components/VRangeSlider/index.js create mode 100644 node_modules/vuetify/es5/components/VRangeSlider/index.js.map create mode 100644 node_modules/vuetify/es5/components/VRating/VRating.js create mode 100644 node_modules/vuetify/es5/components/VRating/VRating.js.map create mode 100644 node_modules/vuetify/es5/components/VRating/index.js create mode 100644 node_modules/vuetify/es5/components/VRating/index.js.map create mode 100644 node_modules/vuetify/es5/components/VResponsive/VResponsive.js create mode 100644 node_modules/vuetify/es5/components/VResponsive/VResponsive.js.map create mode 100644 node_modules/vuetify/es5/components/VResponsive/index.js create mode 100644 node_modules/vuetify/es5/components/VResponsive/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSelect/VSelect.js create mode 100644 node_modules/vuetify/es5/components/VSelect/VSelect.js.map create mode 100644 node_modules/vuetify/es5/components/VSelect/VSelectList.js create mode 100644 node_modules/vuetify/es5/components/VSelect/VSelectList.js.map create mode 100644 node_modules/vuetify/es5/components/VSelect/index.js create mode 100644 node_modules/vuetify/es5/components/VSelect/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSheet/VSheet.js create mode 100644 node_modules/vuetify/es5/components/VSheet/VSheet.js.map create mode 100644 node_modules/vuetify/es5/components/VSheet/index.js create mode 100644 node_modules/vuetify/es5/components/VSheet/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSlider/VSlider.js create mode 100644 node_modules/vuetify/es5/components/VSlider/VSlider.js.map create mode 100644 node_modules/vuetify/es5/components/VSlider/index.js create mode 100644 node_modules/vuetify/es5/components/VSlider/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSnackbar/VSnackbar.js create mode 100644 node_modules/vuetify/es5/components/VSnackbar/VSnackbar.js.map create mode 100644 node_modules/vuetify/es5/components/VSnackbar/index.js create mode 100644 node_modules/vuetify/es5/components/VSnackbar/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSparkline/VSparkline.js create mode 100644 node_modules/vuetify/es5/components/VSparkline/VSparkline.js.map create mode 100644 node_modules/vuetify/es5/components/VSparkline/helpers/core.js create mode 100644 node_modules/vuetify/es5/components/VSparkline/helpers/core.js.map create mode 100644 node_modules/vuetify/es5/components/VSparkline/helpers/math.js create mode 100644 node_modules/vuetify/es5/components/VSparkline/helpers/math.js.map create mode 100644 node_modules/vuetify/es5/components/VSparkline/helpers/path.js create mode 100644 node_modules/vuetify/es5/components/VSparkline/helpers/path.js.map create mode 100644 node_modules/vuetify/es5/components/VSparkline/index.js create mode 100644 node_modules/vuetify/es5/components/VSparkline/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSpeedDial/VSpeedDial.js create mode 100644 node_modules/vuetify/es5/components/VSpeedDial/VSpeedDial.js.map create mode 100644 node_modules/vuetify/es5/components/VSpeedDial/index.js create mode 100644 node_modules/vuetify/es5/components/VSpeedDial/index.js.map create mode 100644 node_modules/vuetify/es5/components/VStepper/VStepper.js create mode 100644 node_modules/vuetify/es5/components/VStepper/VStepper.js.map create mode 100644 node_modules/vuetify/es5/components/VStepper/VStepperContent.js create mode 100644 node_modules/vuetify/es5/components/VStepper/VStepperContent.js.map create mode 100644 node_modules/vuetify/es5/components/VStepper/VStepperStep.js create mode 100644 node_modules/vuetify/es5/components/VStepper/VStepperStep.js.map create mode 100644 node_modules/vuetify/es5/components/VStepper/index.js create mode 100644 node_modules/vuetify/es5/components/VStepper/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSubheader/VSubheader.js create mode 100644 node_modules/vuetify/es5/components/VSubheader/VSubheader.js.map create mode 100644 node_modules/vuetify/es5/components/VSubheader/index.js create mode 100644 node_modules/vuetify/es5/components/VSubheader/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSwitch/VSwitch.js create mode 100644 node_modules/vuetify/es5/components/VSwitch/VSwitch.js.map create mode 100644 node_modules/vuetify/es5/components/VSwitch/index.js create mode 100644 node_modules/vuetify/es5/components/VSwitch/index.js.map create mode 100644 node_modules/vuetify/es5/components/VSystemBar/VSystemBar.js create mode 100644 node_modules/vuetify/es5/components/VSystemBar/VSystemBar.js.map create mode 100644 node_modules/vuetify/es5/components/VSystemBar/index.js create mode 100644 node_modules/vuetify/es5/components/VSystemBar/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/VTab.js create mode 100644 node_modules/vuetify/es5/components/VTabs/VTab.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabItem.js create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabItem.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabs.js create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabs.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabsItems.js create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabsItems.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabsSlider.js create mode 100644 node_modules/vuetify/es5/components/VTabs/VTabsSlider.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/index.js create mode 100644 node_modules/vuetify/es5/components/VTabs/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-computed.js create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-computed.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-generators.js create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-generators.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-props.js create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-props.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-touch.js create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-touch.js.map create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-watchers.js create mode 100644 node_modules/vuetify/es5/components/VTabs/mixins/tabs-watchers.js.map create mode 100644 node_modules/vuetify/es5/components/VTextField/VTextField.js create mode 100644 node_modules/vuetify/es5/components/VTextField/VTextField.js.map create mode 100644 node_modules/vuetify/es5/components/VTextField/index.js create mode 100644 node_modules/vuetify/es5/components/VTextField/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTextarea/VTextarea.js create mode 100644 node_modules/vuetify/es5/components/VTextarea/VTextarea.js.map create mode 100644 node_modules/vuetify/es5/components/VTextarea/index.js create mode 100644 node_modules/vuetify/es5/components/VTextarea/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTimePicker/VTimePicker.js create mode 100644 node_modules/vuetify/es5/components/VTimePicker/VTimePicker.js.map create mode 100644 node_modules/vuetify/es5/components/VTimePicker/VTimePickerClock.js create mode 100644 node_modules/vuetify/es5/components/VTimePicker/VTimePickerClock.js.map create mode 100644 node_modules/vuetify/es5/components/VTimePicker/VTimePickerTitle.js create mode 100644 node_modules/vuetify/es5/components/VTimePicker/VTimePickerTitle.js.map create mode 100644 node_modules/vuetify/es5/components/VTimePicker/index.js create mode 100644 node_modules/vuetify/es5/components/VTimePicker/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTimeline/VTimeline.js create mode 100644 node_modules/vuetify/es5/components/VTimeline/VTimeline.js.map create mode 100644 node_modules/vuetify/es5/components/VTimeline/VTimelineItem.js create mode 100644 node_modules/vuetify/es5/components/VTimeline/VTimelineItem.js.map create mode 100644 node_modules/vuetify/es5/components/VTimeline/index.js create mode 100644 node_modules/vuetify/es5/components/VTimeline/index.js.map create mode 100644 node_modules/vuetify/es5/components/VToolbar/VToolbar.js create mode 100644 node_modules/vuetify/es5/components/VToolbar/VToolbar.js.map create mode 100644 node_modules/vuetify/es5/components/VToolbar/VToolbarSideIcon.js create mode 100644 node_modules/vuetify/es5/components/VToolbar/VToolbarSideIcon.js.map create mode 100644 node_modules/vuetify/es5/components/VToolbar/index.js create mode 100644 node_modules/vuetify/es5/components/VToolbar/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTooltip/VTooltip.js create mode 100644 node_modules/vuetify/es5/components/VTooltip/VTooltip.js.map create mode 100644 node_modules/vuetify/es5/components/VTooltip/index.js create mode 100644 node_modules/vuetify/es5/components/VTooltip/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTreeview/VTreeview.js create mode 100644 node_modules/vuetify/es5/components/VTreeview/VTreeview.js.map create mode 100644 node_modules/vuetify/es5/components/VTreeview/VTreeviewNode.js create mode 100644 node_modules/vuetify/es5/components/VTreeview/VTreeviewNode.js.map create mode 100644 node_modules/vuetify/es5/components/VTreeview/index.js create mode 100644 node_modules/vuetify/es5/components/VTreeview/index.js.map create mode 100644 node_modules/vuetify/es5/components/VTreeview/util/filterTreeItems.js create mode 100644 node_modules/vuetify/es5/components/VTreeview/util/filterTreeItems.js.map create mode 100644 node_modules/vuetify/es5/components/VWindow/VWindow.js create mode 100644 node_modules/vuetify/es5/components/VWindow/VWindow.js.map create mode 100644 node_modules/vuetify/es5/components/VWindow/VWindowItem.js create mode 100644 node_modules/vuetify/es5/components/VWindow/VWindowItem.js.map create mode 100644 node_modules/vuetify/es5/components/VWindow/index.js create mode 100644 node_modules/vuetify/es5/components/VWindow/index.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/goTo/easing-patterns.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/goTo/easing-patterns.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/goTo/index.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/goTo/index.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/goTo/util.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/goTo/util.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/index.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/index.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/application.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/application.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/breakpoint.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/breakpoint.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/icons.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/icons.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/lang.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/lang.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/options.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/options.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/theme.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/mixins/theme.js.map create mode 100644 node_modules/vuetify/es5/components/Vuetify/util/goTo.js create mode 100644 node_modules/vuetify/es5/components/Vuetify/util/goTo.js.map create mode 100644 node_modules/vuetify/es5/components/index.js create mode 100644 node_modules/vuetify/es5/components/index.js.map create mode 100644 node_modules/vuetify/es5/components/transitions/expand-transition.js create mode 100644 node_modules/vuetify/es5/components/transitions/expand-transition.js.map create mode 100644 node_modules/vuetify/es5/components/transitions/index.js create mode 100644 node_modules/vuetify/es5/components/transitions/index.js.map create mode 100644 node_modules/vuetify/es5/directives/click-outside.js create mode 100644 node_modules/vuetify/es5/directives/click-outside.js.map create mode 100644 node_modules/vuetify/es5/directives/index.js create mode 100644 node_modules/vuetify/es5/directives/index.js.map create mode 100644 node_modules/vuetify/es5/directives/resize.js create mode 100644 node_modules/vuetify/es5/directives/resize.js.map create mode 100644 node_modules/vuetify/es5/directives/ripple.js create mode 100644 node_modules/vuetify/es5/directives/ripple.js.map create mode 100644 node_modules/vuetify/es5/directives/scroll.js create mode 100644 node_modules/vuetify/es5/directives/scroll.js.map create mode 100644 node_modules/vuetify/es5/directives/touch.js create mode 100644 node_modules/vuetify/es5/directives/touch.js.map create mode 100644 node_modules/vuetify/es5/entry-lib.js create mode 100644 node_modules/vuetify/es5/entry-lib.js.map create mode 100644 node_modules/vuetify/es5/index.js create mode 100644 node_modules/vuetify/es5/index.js.map create mode 100644 node_modules/vuetify/es5/locale/af.js create mode 100644 node_modules/vuetify/es5/locale/af.js.map create mode 100644 node_modules/vuetify/es5/locale/ar.js create mode 100644 node_modules/vuetify/es5/locale/ar.js.map create mode 100644 node_modules/vuetify/es5/locale/ca.js create mode 100644 node_modules/vuetify/es5/locale/ca.js.map create mode 100644 node_modules/vuetify/es5/locale/de.js create mode 100644 node_modules/vuetify/es5/locale/de.js.map create mode 100644 node_modules/vuetify/es5/locale/el.js create mode 100644 node_modules/vuetify/es5/locale/el.js.map create mode 100644 node_modules/vuetify/es5/locale/en.js create mode 100644 node_modules/vuetify/es5/locale/en.js.map create mode 100644 node_modules/vuetify/es5/locale/es.js create mode 100644 node_modules/vuetify/es5/locale/es.js.map create mode 100644 node_modules/vuetify/es5/locale/et.js create mode 100644 node_modules/vuetify/es5/locale/et.js.map create mode 100644 node_modules/vuetify/es5/locale/fa.js create mode 100644 node_modules/vuetify/es5/locale/fa.js.map create mode 100644 node_modules/vuetify/es5/locale/fr.js create mode 100644 node_modules/vuetify/es5/locale/fr.js.map create mode 100644 node_modules/vuetify/es5/locale/gr.js create mode 100644 node_modules/vuetify/es5/locale/gr.js.map create mode 100644 node_modules/vuetify/es5/locale/hr.js create mode 100644 node_modules/vuetify/es5/locale/hr.js.map create mode 100644 node_modules/vuetify/es5/locale/hu.js create mode 100644 node_modules/vuetify/es5/locale/hu.js.map create mode 100644 node_modules/vuetify/es5/locale/id.js create mode 100644 node_modules/vuetify/es5/locale/id.js.map create mode 100644 node_modules/vuetify/es5/locale/index.js create mode 100644 node_modules/vuetify/es5/locale/index.js.map create mode 100644 node_modules/vuetify/es5/locale/it.js create mode 100644 node_modules/vuetify/es5/locale/it.js.map create mode 100644 node_modules/vuetify/es5/locale/ja.js create mode 100644 node_modules/vuetify/es5/locale/ja.js.map create mode 100644 node_modules/vuetify/es5/locale/nl.js create mode 100644 node_modules/vuetify/es5/locale/nl.js.map create mode 100644 node_modules/vuetify/es5/locale/pl.js create mode 100644 node_modules/vuetify/es5/locale/pl.js.map create mode 100644 node_modules/vuetify/es5/locale/pt.js create mode 100644 node_modules/vuetify/es5/locale/pt.js.map create mode 100644 node_modules/vuetify/es5/locale/ro.js create mode 100644 node_modules/vuetify/es5/locale/ro.js.map create mode 100644 node_modules/vuetify/es5/locale/ru.js create mode 100644 node_modules/vuetify/es5/locale/ru.js.map create mode 100644 node_modules/vuetify/es5/locale/sl.js create mode 100644 node_modules/vuetify/es5/locale/sl.js.map create mode 100644 node_modules/vuetify/es5/locale/sr-Cyrl.js create mode 100644 node_modules/vuetify/es5/locale/sr-Cyrl.js.map create mode 100644 node_modules/vuetify/es5/locale/th.js create mode 100644 node_modules/vuetify/es5/locale/th.js.map create mode 100644 node_modules/vuetify/es5/locale/tr.js create mode 100644 node_modules/vuetify/es5/locale/tr.js.map create mode 100644 node_modules/vuetify/es5/locale/uk.js create mode 100644 node_modules/vuetify/es5/locale/uk.js.map create mode 100644 node_modules/vuetify/es5/locale/zh-Hans.js create mode 100644 node_modules/vuetify/es5/locale/zh-Hans.js.map create mode 100644 node_modules/vuetify/es5/locale/zh-Hant.js create mode 100644 node_modules/vuetify/es5/locale/zh-Hant.js.map create mode 100644 node_modules/vuetify/es5/mixins/applicationable.js create mode 100644 node_modules/vuetify/es5/mixins/applicationable.js.map create mode 100644 node_modules/vuetify/es5/mixins/bootable.js create mode 100644 node_modules/vuetify/es5/mixins/bootable.js.map create mode 100644 node_modules/vuetify/es5/mixins/button-group.js create mode 100644 node_modules/vuetify/es5/mixins/button-group.js.map create mode 100644 node_modules/vuetify/es5/mixins/colorable.js create mode 100644 node_modules/vuetify/es5/mixins/colorable.js.map create mode 100644 node_modules/vuetify/es5/mixins/comparable.js create mode 100644 node_modules/vuetify/es5/mixins/comparable.js.map create mode 100644 node_modules/vuetify/es5/mixins/data-iterable.js create mode 100644 node_modules/vuetify/es5/mixins/data-iterable.js.map create mode 100644 node_modules/vuetify/es5/mixins/delayable.js create mode 100644 node_modules/vuetify/es5/mixins/delayable.js.map create mode 100644 node_modules/vuetify/es5/mixins/dependent.js create mode 100644 node_modules/vuetify/es5/mixins/dependent.js.map create mode 100644 node_modules/vuetify/es5/mixins/detachable.js create mode 100644 node_modules/vuetify/es5/mixins/detachable.js.map create mode 100644 node_modules/vuetify/es5/mixins/elevatable.js create mode 100644 node_modules/vuetify/es5/mixins/elevatable.js.map create mode 100644 node_modules/vuetify/es5/mixins/filterable.js create mode 100644 node_modules/vuetify/es5/mixins/filterable.js.map create mode 100644 node_modules/vuetify/es5/mixins/groupable.js create mode 100644 node_modules/vuetify/es5/mixins/groupable.js.map create mode 100644 node_modules/vuetify/es5/mixins/loadable.js create mode 100644 node_modules/vuetify/es5/mixins/loadable.js.map create mode 100644 node_modules/vuetify/es5/mixins/maskable.js create mode 100644 node_modules/vuetify/es5/mixins/maskable.js.map create mode 100644 node_modules/vuetify/es5/mixins/measurable.js create mode 100644 node_modules/vuetify/es5/mixins/measurable.js.map create mode 100644 node_modules/vuetify/es5/mixins/menuable.js create mode 100644 node_modules/vuetify/es5/mixins/menuable.js.map create mode 100644 node_modules/vuetify/es5/mixins/overlayable.js create mode 100644 node_modules/vuetify/es5/mixins/overlayable.js.map create mode 100644 node_modules/vuetify/es5/mixins/picker-button.js create mode 100644 node_modules/vuetify/es5/mixins/picker-button.js.map create mode 100644 node_modules/vuetify/es5/mixins/picker.js create mode 100644 node_modules/vuetify/es5/mixins/picker.js.map create mode 100644 node_modules/vuetify/es5/mixins/positionable.js create mode 100644 node_modules/vuetify/es5/mixins/positionable.js.map create mode 100644 node_modules/vuetify/es5/mixins/proxyable.js create mode 100644 node_modules/vuetify/es5/mixins/proxyable.js.map create mode 100644 node_modules/vuetify/es5/mixins/registrable.js create mode 100644 node_modules/vuetify/es5/mixins/registrable.js.map create mode 100644 node_modules/vuetify/es5/mixins/returnable.js create mode 100644 node_modules/vuetify/es5/mixins/returnable.js.map create mode 100644 node_modules/vuetify/es5/mixins/rippleable.js create mode 100644 node_modules/vuetify/es5/mixins/rippleable.js.map create mode 100644 node_modules/vuetify/es5/mixins/routable.js create mode 100644 node_modules/vuetify/es5/mixins/routable.js.map create mode 100644 node_modules/vuetify/es5/mixins/selectable.js create mode 100644 node_modules/vuetify/es5/mixins/selectable.js.map create mode 100644 node_modules/vuetify/es5/mixins/sizeable.js create mode 100644 node_modules/vuetify/es5/mixins/sizeable.js.map create mode 100644 node_modules/vuetify/es5/mixins/ssr-bootable.js create mode 100644 node_modules/vuetify/es5/mixins/ssr-bootable.js.map create mode 100644 node_modules/vuetify/es5/mixins/stackable.js create mode 100644 node_modules/vuetify/es5/mixins/stackable.js.map create mode 100644 node_modules/vuetify/es5/mixins/themeable.js create mode 100644 node_modules/vuetify/es5/mixins/themeable.js.map create mode 100644 node_modules/vuetify/es5/mixins/toggleable.js create mode 100644 node_modules/vuetify/es5/mixins/toggleable.js.map create mode 100644 node_modules/vuetify/es5/mixins/transitionable.js create mode 100644 node_modules/vuetify/es5/mixins/transitionable.js.map create mode 100644 node_modules/vuetify/es5/mixins/translatable.js create mode 100644 node_modules/vuetify/es5/mixins/translatable.js.map create mode 100644 node_modules/vuetify/es5/mixins/validatable.js create mode 100644 node_modules/vuetify/es5/mixins/validatable.js.map create mode 100644 node_modules/vuetify/es5/util/ThemeProvider.js create mode 100644 node_modules/vuetify/es5/util/ThemeProvider.js.map create mode 100644 node_modules/vuetify/es5/util/color/transformCIELAB.js create mode 100644 node_modules/vuetify/es5/util/color/transformCIELAB.js.map create mode 100644 node_modules/vuetify/es5/util/color/transformSRGB.js create mode 100644 node_modules/vuetify/es5/util/color/transformSRGB.js.map create mode 100644 node_modules/vuetify/es5/util/colorUtils.js create mode 100644 node_modules/vuetify/es5/util/colorUtils.js.map create mode 100644 node_modules/vuetify/es5/util/colors.js create mode 100644 node_modules/vuetify/es5/util/colors.js.map create mode 100644 node_modules/vuetify/es5/util/component.js create mode 100644 node_modules/vuetify/es5/util/component.js.map create mode 100644 node_modules/vuetify/es5/util/console.js create mode 100644 node_modules/vuetify/es5/util/console.js.map create mode 100644 node_modules/vuetify/es5/util/dedupeModelListeners.js create mode 100644 node_modules/vuetify/es5/util/dedupeModelListeners.js.map create mode 100644 node_modules/vuetify/es5/util/easing-patterns.js create mode 100644 node_modules/vuetify/es5/util/easing-patterns.js.map create mode 100644 node_modules/vuetify/es5/util/helpers.js create mode 100644 node_modules/vuetify/es5/util/helpers.js.map create mode 100644 node_modules/vuetify/es5/util/mask.js create mode 100644 node_modules/vuetify/es5/util/mask.js.map create mode 100644 node_modules/vuetify/es5/util/mixins.js create mode 100644 node_modules/vuetify/es5/util/mixins.js.map create mode 100644 node_modules/vuetify/es5/util/rebuildFunctionalSlots.js create mode 100644 node_modules/vuetify/es5/util/rebuildFunctionalSlots.js.map create mode 100644 node_modules/vuetify/es5/util/theme.js create mode 100644 node_modules/vuetify/es5/util/theme.js.map create mode 100644 node_modules/vuetify/lib/components/VAlert/VAlert.js create mode 100644 node_modules/vuetify/lib/components/VAlert/VAlert.js.map create mode 100644 node_modules/vuetify/lib/components/VAlert/index.js create mode 100644 node_modules/vuetify/lib/components/VAlert/index.js.map create mode 100644 node_modules/vuetify/lib/components/VApp/VApp.js create mode 100644 node_modules/vuetify/lib/components/VApp/VApp.js.map create mode 100644 node_modules/vuetify/lib/components/VApp/index.js create mode 100644 node_modules/vuetify/lib/components/VApp/index.js.map create mode 100644 node_modules/vuetify/lib/components/VApp/mixins/app-theme.js create mode 100644 node_modules/vuetify/lib/components/VApp/mixins/app-theme.js.map create mode 100644 node_modules/vuetify/lib/components/VAutocomplete/VAutocomplete.js create mode 100644 node_modules/vuetify/lib/components/VAutocomplete/VAutocomplete.js.map create mode 100644 node_modules/vuetify/lib/components/VAutocomplete/index.js create mode 100644 node_modules/vuetify/lib/components/VAutocomplete/index.js.map create mode 100644 node_modules/vuetify/lib/components/VAvatar/VAvatar.js create mode 100644 node_modules/vuetify/lib/components/VAvatar/VAvatar.js.map create mode 100644 node_modules/vuetify/lib/components/VAvatar/index.js create mode 100644 node_modules/vuetify/lib/components/VAvatar/index.js.map create mode 100644 node_modules/vuetify/lib/components/VBadge/VBadge.js create mode 100644 node_modules/vuetify/lib/components/VBadge/VBadge.js.map create mode 100644 node_modules/vuetify/lib/components/VBadge/index.js create mode 100644 node_modules/vuetify/lib/components/VBadge/index.js.map create mode 100644 node_modules/vuetify/lib/components/VBottomNav/VBottomNav.js create mode 100644 node_modules/vuetify/lib/components/VBottomNav/VBottomNav.js.map create mode 100644 node_modules/vuetify/lib/components/VBottomNav/index.js create mode 100644 node_modules/vuetify/lib/components/VBottomNav/index.js.map create mode 100644 node_modules/vuetify/lib/components/VBottomSheet/VBottomSheet.js create mode 100644 node_modules/vuetify/lib/components/VBottomSheet/VBottomSheet.js.map create mode 100644 node_modules/vuetify/lib/components/VBottomSheet/index.js create mode 100644 node_modules/vuetify/lib/components/VBottomSheet/index.js.map create mode 100644 node_modules/vuetify/lib/components/VBreadcrumbs/VBreadcrumbs.js create mode 100644 node_modules/vuetify/lib/components/VBreadcrumbs/VBreadcrumbs.js.map create mode 100644 node_modules/vuetify/lib/components/VBreadcrumbs/VBreadcrumbsItem.js create mode 100644 node_modules/vuetify/lib/components/VBreadcrumbs/VBreadcrumbsItem.js.map create mode 100644 node_modules/vuetify/lib/components/VBreadcrumbs/index.js create mode 100644 node_modules/vuetify/lib/components/VBreadcrumbs/index.js.map create mode 100644 node_modules/vuetify/lib/components/VBtn/VBtn.js create mode 100644 node_modules/vuetify/lib/components/VBtn/VBtn.js.map create mode 100644 node_modules/vuetify/lib/components/VBtn/index.js create mode 100644 node_modules/vuetify/lib/components/VBtn/index.js.map create mode 100644 node_modules/vuetify/lib/components/VBtnToggle/VBtnToggle.js create mode 100644 node_modules/vuetify/lib/components/VBtnToggle/VBtnToggle.js.map create mode 100644 node_modules/vuetify/lib/components/VBtnToggle/index.js create mode 100644 node_modules/vuetify/lib/components/VBtnToggle/index.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendar.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendar.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendarDaily.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendarDaily.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendarMonthly.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendarMonthly.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendarWeekly.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/VCalendarWeekly.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/index.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/index.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/calendar-base.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/calendar-base.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/calendar-with-intervals.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/calendar-with-intervals.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/mouse.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/mouse.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/times.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/mixins/times.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/util/props.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/util/props.js.map create mode 100644 node_modules/vuetify/lib/components/VCalendar/util/timestamp.js create mode 100644 node_modules/vuetify/lib/components/VCalendar/util/timestamp.js.map create mode 100644 node_modules/vuetify/lib/components/VCard/VCard.js create mode 100644 node_modules/vuetify/lib/components/VCard/VCard.js.map create mode 100644 node_modules/vuetify/lib/components/VCard/VCardMedia.js create mode 100644 node_modules/vuetify/lib/components/VCard/VCardMedia.js.map create mode 100644 node_modules/vuetify/lib/components/VCard/VCardTitle.js create mode 100644 node_modules/vuetify/lib/components/VCard/VCardTitle.js.map create mode 100644 node_modules/vuetify/lib/components/VCard/index.js create mode 100644 node_modules/vuetify/lib/components/VCard/index.js.map create mode 100644 node_modules/vuetify/lib/components/VCarousel/VCarousel.js create mode 100644 node_modules/vuetify/lib/components/VCarousel/VCarousel.js.map create mode 100644 node_modules/vuetify/lib/components/VCarousel/VCarouselItem.js create mode 100644 node_modules/vuetify/lib/components/VCarousel/VCarouselItem.js.map create mode 100644 node_modules/vuetify/lib/components/VCarousel/index.js create mode 100644 node_modules/vuetify/lib/components/VCarousel/index.js.map create mode 100644 node_modules/vuetify/lib/components/VCheckbox/VCheckbox.js create mode 100644 node_modules/vuetify/lib/components/VCheckbox/VCheckbox.js.map create mode 100644 node_modules/vuetify/lib/components/VCheckbox/index.js create mode 100644 node_modules/vuetify/lib/components/VCheckbox/index.js.map create mode 100644 node_modules/vuetify/lib/components/VChip/VChip.js create mode 100644 node_modules/vuetify/lib/components/VChip/VChip.js.map create mode 100644 node_modules/vuetify/lib/components/VChip/index.js create mode 100644 node_modules/vuetify/lib/components/VChip/index.js.map create mode 100644 node_modules/vuetify/lib/components/VCombobox/VCombobox.js create mode 100644 node_modules/vuetify/lib/components/VCombobox/VCombobox.js.map create mode 100644 node_modules/vuetify/lib/components/VCombobox/index.js create mode 100644 node_modules/vuetify/lib/components/VCombobox/index.js.map create mode 100644 node_modules/vuetify/lib/components/VCounter/VCounter.js create mode 100644 node_modules/vuetify/lib/components/VCounter/VCounter.js.map create mode 100644 node_modules/vuetify/lib/components/VCounter/index.js create mode 100644 node_modules/vuetify/lib/components/VCounter/index.js.map create mode 100644 node_modules/vuetify/lib/components/VDataIterator/VDataIterator.js create mode 100644 node_modules/vuetify/lib/components/VDataIterator/VDataIterator.js.map create mode 100644 node_modules/vuetify/lib/components/VDataIterator/index.js create mode 100644 node_modules/vuetify/lib/components/VDataIterator/index.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/VDataTable.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/VDataTable.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/VEditDialog.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/VEditDialog.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/index.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/index.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/body.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/body.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/foot.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/foot.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/head.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/head.js.map create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/progress.js create mode 100644 node_modules/vuetify/lib/components/VDataTable/mixins/progress.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePicker.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePicker.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerDateTable.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerDateTable.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerHeader.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerHeader.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerMonthTable.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerMonthTable.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerTitle.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerTitle.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerYears.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/VDatePickerYears.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/index.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/index.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/mixins/date-picker-table.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/mixins/date-picker-table.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/createNativeLocaleFormatter.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/createNativeLocaleFormatter.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/index.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/index.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/isDateAllowed.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/isDateAllowed.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/monthChange.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/monthChange.js.map create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/pad.js create mode 100644 node_modules/vuetify/lib/components/VDatePicker/util/pad.js.map create mode 100644 node_modules/vuetify/lib/components/VDialog/VDialog.js create mode 100644 node_modules/vuetify/lib/components/VDialog/VDialog.js.map create mode 100644 node_modules/vuetify/lib/components/VDialog/index.js create mode 100644 node_modules/vuetify/lib/components/VDialog/index.js.map create mode 100644 node_modules/vuetify/lib/components/VDivider/VDivider.js create mode 100644 node_modules/vuetify/lib/components/VDivider/VDivider.js.map create mode 100644 node_modules/vuetify/lib/components/VDivider/index.js create mode 100644 node_modules/vuetify/lib/components/VDivider/index.js.map create mode 100644 node_modules/vuetify/lib/components/VExpansionPanel/VExpansionPanel.js create mode 100644 node_modules/vuetify/lib/components/VExpansionPanel/VExpansionPanel.js.map create mode 100644 node_modules/vuetify/lib/components/VExpansionPanel/VExpansionPanelContent.js create mode 100644 node_modules/vuetify/lib/components/VExpansionPanel/VExpansionPanelContent.js.map create mode 100644 node_modules/vuetify/lib/components/VExpansionPanel/index.js create mode 100644 node_modules/vuetify/lib/components/VExpansionPanel/index.js.map create mode 100644 node_modules/vuetify/lib/components/VFooter/VFooter.js create mode 100644 node_modules/vuetify/lib/components/VFooter/VFooter.js.map create mode 100644 node_modules/vuetify/lib/components/VFooter/index.js create mode 100644 node_modules/vuetify/lib/components/VFooter/index.js.map create mode 100644 node_modules/vuetify/lib/components/VForm/VForm.js create mode 100644 node_modules/vuetify/lib/components/VForm/VForm.js.map create mode 100644 node_modules/vuetify/lib/components/VForm/index.js create mode 100644 node_modules/vuetify/lib/components/VForm/index.js.map create mode 100644 node_modules/vuetify/lib/components/VGrid/VContainer.js create mode 100644 node_modules/vuetify/lib/components/VGrid/VContainer.js.map create mode 100644 node_modules/vuetify/lib/components/VGrid/VContent.js create mode 100644 node_modules/vuetify/lib/components/VGrid/VContent.js.map create mode 100644 node_modules/vuetify/lib/components/VGrid/VFlex.js create mode 100644 node_modules/vuetify/lib/components/VGrid/VFlex.js.map create mode 100644 node_modules/vuetify/lib/components/VGrid/VLayout.js create mode 100644 node_modules/vuetify/lib/components/VGrid/VLayout.js.map create mode 100644 node_modules/vuetify/lib/components/VGrid/grid.js create mode 100644 node_modules/vuetify/lib/components/VGrid/grid.js.map create mode 100644 node_modules/vuetify/lib/components/VGrid/index.js create mode 100644 node_modules/vuetify/lib/components/VGrid/index.js.map create mode 100644 node_modules/vuetify/lib/components/VHover/VHover.js create mode 100644 node_modules/vuetify/lib/components/VHover/VHover.js.map create mode 100644 node_modules/vuetify/lib/components/VHover/index.js create mode 100644 node_modules/vuetify/lib/components/VHover/index.js.map create mode 100644 node_modules/vuetify/lib/components/VIcon/VIcon.js create mode 100644 node_modules/vuetify/lib/components/VIcon/VIcon.js.map create mode 100644 node_modules/vuetify/lib/components/VIcon/index.js create mode 100644 node_modules/vuetify/lib/components/VIcon/index.js.map create mode 100644 node_modules/vuetify/lib/components/VImg/VImg.js create mode 100644 node_modules/vuetify/lib/components/VImg/VImg.js.map create mode 100644 node_modules/vuetify/lib/components/VImg/index.js create mode 100644 node_modules/vuetify/lib/components/VImg/index.js.map create mode 100644 node_modules/vuetify/lib/components/VInput/VInput.js create mode 100644 node_modules/vuetify/lib/components/VInput/VInput.js.map create mode 100644 node_modules/vuetify/lib/components/VInput/index.js create mode 100644 node_modules/vuetify/lib/components/VInput/index.js.map create mode 100644 node_modules/vuetify/lib/components/VItemGroup/VItem.js create mode 100644 node_modules/vuetify/lib/components/VItemGroup/VItem.js.map create mode 100644 node_modules/vuetify/lib/components/VItemGroup/VItemGroup.js create mode 100644 node_modules/vuetify/lib/components/VItemGroup/VItemGroup.js.map create mode 100644 node_modules/vuetify/lib/components/VItemGroup/index.js create mode 100644 node_modules/vuetify/lib/components/VItemGroup/index.js.map create mode 100644 node_modules/vuetify/lib/components/VJumbotron/VJumbotron.js create mode 100644 node_modules/vuetify/lib/components/VJumbotron/VJumbotron.js.map create mode 100644 node_modules/vuetify/lib/components/VJumbotron/index.js create mode 100644 node_modules/vuetify/lib/components/VJumbotron/index.js.map create mode 100644 node_modules/vuetify/lib/components/VLabel/VLabel.js create mode 100644 node_modules/vuetify/lib/components/VLabel/VLabel.js.map create mode 100644 node_modules/vuetify/lib/components/VLabel/index.js create mode 100644 node_modules/vuetify/lib/components/VLabel/index.js.map create mode 100644 node_modules/vuetify/lib/components/VList/VList.js create mode 100644 node_modules/vuetify/lib/components/VList/VList.js.map create mode 100644 node_modules/vuetify/lib/components/VList/VListGroup.js create mode 100644 node_modules/vuetify/lib/components/VList/VListGroup.js.map create mode 100644 node_modules/vuetify/lib/components/VList/VListTile.js create mode 100644 node_modules/vuetify/lib/components/VList/VListTile.js.map create mode 100644 node_modules/vuetify/lib/components/VList/VListTileAction.js create mode 100644 node_modules/vuetify/lib/components/VList/VListTileAction.js.map create mode 100644 node_modules/vuetify/lib/components/VList/VListTileAvatar.js create mode 100644 node_modules/vuetify/lib/components/VList/VListTileAvatar.js.map create mode 100644 node_modules/vuetify/lib/components/VList/index.js create mode 100644 node_modules/vuetify/lib/components/VList/index.js.map create mode 100644 node_modules/vuetify/lib/components/VMenu/VMenu.js create mode 100644 node_modules/vuetify/lib/components/VMenu/VMenu.js.map create mode 100644 node_modules/vuetify/lib/components/VMenu/index.js create mode 100644 node_modules/vuetify/lib/components/VMenu/index.js.map create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-activator.js create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-activator.js.map create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-generators.js create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-generators.js.map create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-keyable.js create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-keyable.js.map create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-position.js create mode 100644 node_modules/vuetify/lib/components/VMenu/mixins/menu-position.js.map create mode 100644 node_modules/vuetify/lib/components/VMessages/VMessages.js create mode 100644 node_modules/vuetify/lib/components/VMessages/VMessages.js.map create mode 100644 node_modules/vuetify/lib/components/VMessages/index.js create mode 100644 node_modules/vuetify/lib/components/VMessages/index.js.map create mode 100644 node_modules/vuetify/lib/components/VNavigationDrawer/VNavigationDrawer.js create mode 100644 node_modules/vuetify/lib/components/VNavigationDrawer/VNavigationDrawer.js.map create mode 100644 node_modules/vuetify/lib/components/VNavigationDrawer/index.js create mode 100644 node_modules/vuetify/lib/components/VNavigationDrawer/index.js.map create mode 100644 node_modules/vuetify/lib/components/VOverflowBtn/VOverflowBtn.js create mode 100644 node_modules/vuetify/lib/components/VOverflowBtn/VOverflowBtn.js.map create mode 100644 node_modules/vuetify/lib/components/VOverflowBtn/index.js create mode 100644 node_modules/vuetify/lib/components/VOverflowBtn/index.js.map create mode 100644 node_modules/vuetify/lib/components/VPagination/VPagination.js create mode 100644 node_modules/vuetify/lib/components/VPagination/VPagination.js.map create mode 100644 node_modules/vuetify/lib/components/VPagination/index.js create mode 100644 node_modules/vuetify/lib/components/VPagination/index.js.map create mode 100644 node_modules/vuetify/lib/components/VParallax/VParallax.js create mode 100644 node_modules/vuetify/lib/components/VParallax/VParallax.js.map create mode 100644 node_modules/vuetify/lib/components/VParallax/index.js create mode 100644 node_modules/vuetify/lib/components/VParallax/index.js.map create mode 100644 node_modules/vuetify/lib/components/VPicker/VPicker.js create mode 100644 node_modules/vuetify/lib/components/VPicker/VPicker.js.map create mode 100644 node_modules/vuetify/lib/components/VPicker/index.js create mode 100644 node_modules/vuetify/lib/components/VPicker/index.js.map create mode 100644 node_modules/vuetify/lib/components/VProgressCircular/VProgressCircular.js create mode 100644 node_modules/vuetify/lib/components/VProgressCircular/VProgressCircular.js.map create mode 100644 node_modules/vuetify/lib/components/VProgressCircular/index.js create mode 100644 node_modules/vuetify/lib/components/VProgressCircular/index.js.map create mode 100644 node_modules/vuetify/lib/components/VProgressLinear/VProgressLinear.js create mode 100644 node_modules/vuetify/lib/components/VProgressLinear/VProgressLinear.js.map create mode 100644 node_modules/vuetify/lib/components/VProgressLinear/index.js create mode 100644 node_modules/vuetify/lib/components/VProgressLinear/index.js.map create mode 100644 node_modules/vuetify/lib/components/VRadioGroup/VRadio.js create mode 100644 node_modules/vuetify/lib/components/VRadioGroup/VRadio.js.map create mode 100644 node_modules/vuetify/lib/components/VRadioGroup/VRadioGroup.js create mode 100644 node_modules/vuetify/lib/components/VRadioGroup/VRadioGroup.js.map create mode 100644 node_modules/vuetify/lib/components/VRadioGroup/index.js create mode 100644 node_modules/vuetify/lib/components/VRadioGroup/index.js.map create mode 100644 node_modules/vuetify/lib/components/VRangeSlider/VRangeSlider.js create mode 100644 node_modules/vuetify/lib/components/VRangeSlider/VRangeSlider.js.map create mode 100644 node_modules/vuetify/lib/components/VRangeSlider/index.js create mode 100644 node_modules/vuetify/lib/components/VRangeSlider/index.js.map create mode 100644 node_modules/vuetify/lib/components/VRating/VRating.js create mode 100644 node_modules/vuetify/lib/components/VRating/VRating.js.map create mode 100644 node_modules/vuetify/lib/components/VRating/index.js create mode 100644 node_modules/vuetify/lib/components/VRating/index.js.map create mode 100644 node_modules/vuetify/lib/components/VResponsive/VResponsive.js create mode 100644 node_modules/vuetify/lib/components/VResponsive/VResponsive.js.map create mode 100644 node_modules/vuetify/lib/components/VResponsive/index.js create mode 100644 node_modules/vuetify/lib/components/VResponsive/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSelect/VSelect.js create mode 100644 node_modules/vuetify/lib/components/VSelect/VSelect.js.map create mode 100644 node_modules/vuetify/lib/components/VSelect/VSelectList.js create mode 100644 node_modules/vuetify/lib/components/VSelect/VSelectList.js.map create mode 100644 node_modules/vuetify/lib/components/VSelect/index.js create mode 100644 node_modules/vuetify/lib/components/VSelect/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSheet/VSheet.js create mode 100644 node_modules/vuetify/lib/components/VSheet/VSheet.js.map create mode 100644 node_modules/vuetify/lib/components/VSheet/index.js create mode 100644 node_modules/vuetify/lib/components/VSheet/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSlider/VSlider.js create mode 100644 node_modules/vuetify/lib/components/VSlider/VSlider.js.map create mode 100644 node_modules/vuetify/lib/components/VSlider/index.js create mode 100644 node_modules/vuetify/lib/components/VSlider/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSnackbar/VSnackbar.js create mode 100644 node_modules/vuetify/lib/components/VSnackbar/VSnackbar.js.map create mode 100644 node_modules/vuetify/lib/components/VSnackbar/index.js create mode 100644 node_modules/vuetify/lib/components/VSnackbar/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSparkline/VSparkline.js create mode 100644 node_modules/vuetify/lib/components/VSparkline/VSparkline.js.map create mode 100644 node_modules/vuetify/lib/components/VSparkline/helpers/core.js create mode 100644 node_modules/vuetify/lib/components/VSparkline/helpers/core.js.map create mode 100644 node_modules/vuetify/lib/components/VSparkline/helpers/math.js create mode 100644 node_modules/vuetify/lib/components/VSparkline/helpers/math.js.map create mode 100644 node_modules/vuetify/lib/components/VSparkline/helpers/path.js create mode 100644 node_modules/vuetify/lib/components/VSparkline/helpers/path.js.map create mode 100644 node_modules/vuetify/lib/components/VSparkline/index.js create mode 100644 node_modules/vuetify/lib/components/VSparkline/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSpeedDial/VSpeedDial.js create mode 100644 node_modules/vuetify/lib/components/VSpeedDial/VSpeedDial.js.map create mode 100644 node_modules/vuetify/lib/components/VSpeedDial/index.js create mode 100644 node_modules/vuetify/lib/components/VSpeedDial/index.js.map create mode 100644 node_modules/vuetify/lib/components/VStepper/VStepper.js create mode 100644 node_modules/vuetify/lib/components/VStepper/VStepper.js.map create mode 100644 node_modules/vuetify/lib/components/VStepper/VStepperContent.js create mode 100644 node_modules/vuetify/lib/components/VStepper/VStepperContent.js.map create mode 100644 node_modules/vuetify/lib/components/VStepper/VStepperStep.js create mode 100644 node_modules/vuetify/lib/components/VStepper/VStepperStep.js.map create mode 100644 node_modules/vuetify/lib/components/VStepper/index.js create mode 100644 node_modules/vuetify/lib/components/VStepper/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSubheader/VSubheader.js create mode 100644 node_modules/vuetify/lib/components/VSubheader/VSubheader.js.map create mode 100644 node_modules/vuetify/lib/components/VSubheader/index.js create mode 100644 node_modules/vuetify/lib/components/VSubheader/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSwitch/VSwitch.js create mode 100644 node_modules/vuetify/lib/components/VSwitch/VSwitch.js.map create mode 100644 node_modules/vuetify/lib/components/VSwitch/index.js create mode 100644 node_modules/vuetify/lib/components/VSwitch/index.js.map create mode 100644 node_modules/vuetify/lib/components/VSystemBar/VSystemBar.js create mode 100644 node_modules/vuetify/lib/components/VSystemBar/VSystemBar.js.map create mode 100644 node_modules/vuetify/lib/components/VSystemBar/index.js create mode 100644 node_modules/vuetify/lib/components/VSystemBar/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/VTab.js create mode 100644 node_modules/vuetify/lib/components/VTabs/VTab.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabItem.js create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabItem.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabs.js create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabs.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabsItems.js create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabsItems.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabsSlider.js create mode 100644 node_modules/vuetify/lib/components/VTabs/VTabsSlider.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/index.js create mode 100644 node_modules/vuetify/lib/components/VTabs/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-computed.js create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-computed.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-generators.js create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-generators.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-props.js create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-props.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-touch.js create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-touch.js.map create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-watchers.js create mode 100644 node_modules/vuetify/lib/components/VTabs/mixins/tabs-watchers.js.map create mode 100644 node_modules/vuetify/lib/components/VTextField/VTextField.js create mode 100644 node_modules/vuetify/lib/components/VTextField/VTextField.js.map create mode 100644 node_modules/vuetify/lib/components/VTextField/index.js create mode 100644 node_modules/vuetify/lib/components/VTextField/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTextarea/VTextarea.js create mode 100644 node_modules/vuetify/lib/components/VTextarea/VTextarea.js.map create mode 100644 node_modules/vuetify/lib/components/VTextarea/index.js create mode 100644 node_modules/vuetify/lib/components/VTextarea/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTimePicker/VTimePicker.js create mode 100644 node_modules/vuetify/lib/components/VTimePicker/VTimePicker.js.map create mode 100644 node_modules/vuetify/lib/components/VTimePicker/VTimePickerClock.js create mode 100644 node_modules/vuetify/lib/components/VTimePicker/VTimePickerClock.js.map create mode 100644 node_modules/vuetify/lib/components/VTimePicker/VTimePickerTitle.js create mode 100644 node_modules/vuetify/lib/components/VTimePicker/VTimePickerTitle.js.map create mode 100644 node_modules/vuetify/lib/components/VTimePicker/index.js create mode 100644 node_modules/vuetify/lib/components/VTimePicker/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTimeline/VTimeline.js create mode 100644 node_modules/vuetify/lib/components/VTimeline/VTimeline.js.map create mode 100644 node_modules/vuetify/lib/components/VTimeline/VTimelineItem.js create mode 100644 node_modules/vuetify/lib/components/VTimeline/VTimelineItem.js.map create mode 100644 node_modules/vuetify/lib/components/VTimeline/index.js create mode 100644 node_modules/vuetify/lib/components/VTimeline/index.js.map create mode 100644 node_modules/vuetify/lib/components/VToolbar/VToolbar.js create mode 100644 node_modules/vuetify/lib/components/VToolbar/VToolbar.js.map create mode 100644 node_modules/vuetify/lib/components/VToolbar/VToolbarSideIcon.js create mode 100644 node_modules/vuetify/lib/components/VToolbar/VToolbarSideIcon.js.map create mode 100644 node_modules/vuetify/lib/components/VToolbar/index.js create mode 100644 node_modules/vuetify/lib/components/VToolbar/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTooltip/VTooltip.js create mode 100644 node_modules/vuetify/lib/components/VTooltip/VTooltip.js.map create mode 100644 node_modules/vuetify/lib/components/VTooltip/index.js create mode 100644 node_modules/vuetify/lib/components/VTooltip/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTreeview/VTreeview.js create mode 100644 node_modules/vuetify/lib/components/VTreeview/VTreeview.js.map create mode 100644 node_modules/vuetify/lib/components/VTreeview/VTreeviewNode.js create mode 100644 node_modules/vuetify/lib/components/VTreeview/VTreeviewNode.js.map create mode 100644 node_modules/vuetify/lib/components/VTreeview/index.js create mode 100644 node_modules/vuetify/lib/components/VTreeview/index.js.map create mode 100644 node_modules/vuetify/lib/components/VTreeview/util/filterTreeItems.js create mode 100644 node_modules/vuetify/lib/components/VTreeview/util/filterTreeItems.js.map create mode 100644 node_modules/vuetify/lib/components/VWindow/VWindow.js create mode 100644 node_modules/vuetify/lib/components/VWindow/VWindow.js.map create mode 100644 node_modules/vuetify/lib/components/VWindow/VWindowItem.js create mode 100644 node_modules/vuetify/lib/components/VWindow/VWindowItem.js.map create mode 100644 node_modules/vuetify/lib/components/VWindow/index.js create mode 100644 node_modules/vuetify/lib/components/VWindow/index.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/goTo/easing-patterns.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/goTo/easing-patterns.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/goTo/index.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/goTo/index.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/goTo/util.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/goTo/util.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/index.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/index.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/application.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/application.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/breakpoint.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/breakpoint.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/icons.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/icons.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/lang.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/lang.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/options.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/options.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/theme.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/mixins/theme.js.map create mode 100644 node_modules/vuetify/lib/components/Vuetify/util/goTo.js create mode 100644 node_modules/vuetify/lib/components/Vuetify/util/goTo.js.map create mode 100644 node_modules/vuetify/lib/components/index.js create mode 100644 node_modules/vuetify/lib/components/index.js.map create mode 100644 node_modules/vuetify/lib/components/transitions/expand-transition.js create mode 100644 node_modules/vuetify/lib/components/transitions/expand-transition.js.map create mode 100644 node_modules/vuetify/lib/components/transitions/index.js create mode 100644 node_modules/vuetify/lib/components/transitions/index.js.map create mode 100644 node_modules/vuetify/lib/directives/click-outside.js create mode 100644 node_modules/vuetify/lib/directives/click-outside.js.map create mode 100644 node_modules/vuetify/lib/directives/index.js create mode 100644 node_modules/vuetify/lib/directives/index.js.map create mode 100644 node_modules/vuetify/lib/directives/resize.js create mode 100644 node_modules/vuetify/lib/directives/resize.js.map create mode 100644 node_modules/vuetify/lib/directives/ripple.js create mode 100644 node_modules/vuetify/lib/directives/ripple.js.map create mode 100644 node_modules/vuetify/lib/directives/scroll.js create mode 100644 node_modules/vuetify/lib/directives/scroll.js.map create mode 100644 node_modules/vuetify/lib/directives/touch.js create mode 100644 node_modules/vuetify/lib/directives/touch.js.map create mode 100644 node_modules/vuetify/lib/index.js create mode 100644 node_modules/vuetify/lib/index.js.map create mode 100644 node_modules/vuetify/lib/locale/af.js create mode 100644 node_modules/vuetify/lib/locale/af.js.map create mode 100644 node_modules/vuetify/lib/locale/ar.js create mode 100644 node_modules/vuetify/lib/locale/ar.js.map create mode 100644 node_modules/vuetify/lib/locale/ca.js create mode 100644 node_modules/vuetify/lib/locale/ca.js.map create mode 100644 node_modules/vuetify/lib/locale/de.js create mode 100644 node_modules/vuetify/lib/locale/de.js.map create mode 100644 node_modules/vuetify/lib/locale/el.js create mode 100644 node_modules/vuetify/lib/locale/el.js.map create mode 100644 node_modules/vuetify/lib/locale/en.js create mode 100644 node_modules/vuetify/lib/locale/en.js.map create mode 100644 node_modules/vuetify/lib/locale/es.js create mode 100644 node_modules/vuetify/lib/locale/es.js.map create mode 100644 node_modules/vuetify/lib/locale/et.js create mode 100644 node_modules/vuetify/lib/locale/et.js.map create mode 100644 node_modules/vuetify/lib/locale/fa.js create mode 100644 node_modules/vuetify/lib/locale/fa.js.map create mode 100644 node_modules/vuetify/lib/locale/fr.js create mode 100644 node_modules/vuetify/lib/locale/fr.js.map create mode 100644 node_modules/vuetify/lib/locale/gr.js create mode 100644 node_modules/vuetify/lib/locale/gr.js.map create mode 100644 node_modules/vuetify/lib/locale/hr.js create mode 100644 node_modules/vuetify/lib/locale/hr.js.map create mode 100644 node_modules/vuetify/lib/locale/hu.js create mode 100644 node_modules/vuetify/lib/locale/hu.js.map create mode 100644 node_modules/vuetify/lib/locale/id.js create mode 100644 node_modules/vuetify/lib/locale/id.js.map create mode 100644 node_modules/vuetify/lib/locale/index.js create mode 100644 node_modules/vuetify/lib/locale/index.js.map create mode 100644 node_modules/vuetify/lib/locale/it.js create mode 100644 node_modules/vuetify/lib/locale/it.js.map create mode 100644 node_modules/vuetify/lib/locale/ja.js create mode 100644 node_modules/vuetify/lib/locale/ja.js.map create mode 100644 node_modules/vuetify/lib/locale/nl.js create mode 100644 node_modules/vuetify/lib/locale/nl.js.map create mode 100644 node_modules/vuetify/lib/locale/pl.js create mode 100644 node_modules/vuetify/lib/locale/pl.js.map create mode 100644 node_modules/vuetify/lib/locale/pt.js create mode 100644 node_modules/vuetify/lib/locale/pt.js.map create mode 100644 node_modules/vuetify/lib/locale/ro.js create mode 100644 node_modules/vuetify/lib/locale/ro.js.map create mode 100644 node_modules/vuetify/lib/locale/ru.js create mode 100644 node_modules/vuetify/lib/locale/ru.js.map create mode 100644 node_modules/vuetify/lib/locale/sl.js create mode 100644 node_modules/vuetify/lib/locale/sl.js.map create mode 100644 node_modules/vuetify/lib/locale/sr-Cyrl.js create mode 100644 node_modules/vuetify/lib/locale/sr-Cyrl.js.map create mode 100644 node_modules/vuetify/lib/locale/th.js create mode 100644 node_modules/vuetify/lib/locale/th.js.map create mode 100644 node_modules/vuetify/lib/locale/tr.js create mode 100644 node_modules/vuetify/lib/locale/tr.js.map create mode 100644 node_modules/vuetify/lib/locale/uk.js create mode 100644 node_modules/vuetify/lib/locale/uk.js.map create mode 100644 node_modules/vuetify/lib/locale/zh-Hans.js create mode 100644 node_modules/vuetify/lib/locale/zh-Hans.js.map create mode 100644 node_modules/vuetify/lib/locale/zh-Hant.js create mode 100644 node_modules/vuetify/lib/locale/zh-Hant.js.map create mode 100644 node_modules/vuetify/lib/mixins/applicationable.js create mode 100644 node_modules/vuetify/lib/mixins/applicationable.js.map create mode 100644 node_modules/vuetify/lib/mixins/bootable.js create mode 100644 node_modules/vuetify/lib/mixins/bootable.js.map create mode 100644 node_modules/vuetify/lib/mixins/button-group.js create mode 100644 node_modules/vuetify/lib/mixins/button-group.js.map create mode 100644 node_modules/vuetify/lib/mixins/colorable.js create mode 100644 node_modules/vuetify/lib/mixins/colorable.js.map create mode 100644 node_modules/vuetify/lib/mixins/comparable.js create mode 100644 node_modules/vuetify/lib/mixins/comparable.js.map create mode 100644 node_modules/vuetify/lib/mixins/data-iterable.js create mode 100644 node_modules/vuetify/lib/mixins/data-iterable.js.map create mode 100644 node_modules/vuetify/lib/mixins/delayable.js create mode 100644 node_modules/vuetify/lib/mixins/delayable.js.map create mode 100644 node_modules/vuetify/lib/mixins/dependent.js create mode 100644 node_modules/vuetify/lib/mixins/dependent.js.map create mode 100644 node_modules/vuetify/lib/mixins/detachable.js create mode 100644 node_modules/vuetify/lib/mixins/detachable.js.map create mode 100644 node_modules/vuetify/lib/mixins/elevatable.js create mode 100644 node_modules/vuetify/lib/mixins/elevatable.js.map create mode 100644 node_modules/vuetify/lib/mixins/filterable.js create mode 100644 node_modules/vuetify/lib/mixins/filterable.js.map create mode 100644 node_modules/vuetify/lib/mixins/groupable.js create mode 100644 node_modules/vuetify/lib/mixins/groupable.js.map create mode 100644 node_modules/vuetify/lib/mixins/loadable.js create mode 100644 node_modules/vuetify/lib/mixins/loadable.js.map create mode 100644 node_modules/vuetify/lib/mixins/maskable.js create mode 100644 node_modules/vuetify/lib/mixins/maskable.js.map create mode 100644 node_modules/vuetify/lib/mixins/measurable.js create mode 100644 node_modules/vuetify/lib/mixins/measurable.js.map create mode 100644 node_modules/vuetify/lib/mixins/menuable.js create mode 100644 node_modules/vuetify/lib/mixins/menuable.js.map create mode 100644 node_modules/vuetify/lib/mixins/overlayable.js create mode 100644 node_modules/vuetify/lib/mixins/overlayable.js.map create mode 100644 node_modules/vuetify/lib/mixins/picker-button.js create mode 100644 node_modules/vuetify/lib/mixins/picker-button.js.map create mode 100644 node_modules/vuetify/lib/mixins/picker.js create mode 100644 node_modules/vuetify/lib/mixins/picker.js.map create mode 100644 node_modules/vuetify/lib/mixins/positionable.js create mode 100644 node_modules/vuetify/lib/mixins/positionable.js.map create mode 100644 node_modules/vuetify/lib/mixins/proxyable.js create mode 100644 node_modules/vuetify/lib/mixins/proxyable.js.map create mode 100644 node_modules/vuetify/lib/mixins/registrable.js create mode 100644 node_modules/vuetify/lib/mixins/registrable.js.map create mode 100644 node_modules/vuetify/lib/mixins/returnable.js create mode 100644 node_modules/vuetify/lib/mixins/returnable.js.map create mode 100644 node_modules/vuetify/lib/mixins/rippleable.js create mode 100644 node_modules/vuetify/lib/mixins/rippleable.js.map create mode 100644 node_modules/vuetify/lib/mixins/routable.js create mode 100644 node_modules/vuetify/lib/mixins/routable.js.map create mode 100644 node_modules/vuetify/lib/mixins/selectable.js create mode 100644 node_modules/vuetify/lib/mixins/selectable.js.map create mode 100644 node_modules/vuetify/lib/mixins/sizeable.js create mode 100644 node_modules/vuetify/lib/mixins/sizeable.js.map create mode 100644 node_modules/vuetify/lib/mixins/ssr-bootable.js create mode 100644 node_modules/vuetify/lib/mixins/ssr-bootable.js.map create mode 100644 node_modules/vuetify/lib/mixins/stackable.js create mode 100644 node_modules/vuetify/lib/mixins/stackable.js.map create mode 100644 node_modules/vuetify/lib/mixins/themeable.js create mode 100644 node_modules/vuetify/lib/mixins/themeable.js.map create mode 100644 node_modules/vuetify/lib/mixins/toggleable.js create mode 100644 node_modules/vuetify/lib/mixins/toggleable.js.map create mode 100644 node_modules/vuetify/lib/mixins/transitionable.js create mode 100644 node_modules/vuetify/lib/mixins/transitionable.js.map create mode 100644 node_modules/vuetify/lib/mixins/translatable.js create mode 100644 node_modules/vuetify/lib/mixins/translatable.js.map create mode 100644 node_modules/vuetify/lib/mixins/validatable.js create mode 100644 node_modules/vuetify/lib/mixins/validatable.js.map create mode 100644 node_modules/vuetify/lib/util/ThemeProvider.js create mode 100644 node_modules/vuetify/lib/util/ThemeProvider.js.map create mode 100644 node_modules/vuetify/lib/util/color/transformCIELAB.js create mode 100644 node_modules/vuetify/lib/util/color/transformCIELAB.js.map create mode 100644 node_modules/vuetify/lib/util/color/transformSRGB.js create mode 100644 node_modules/vuetify/lib/util/color/transformSRGB.js.map create mode 100644 node_modules/vuetify/lib/util/colorUtils.js create mode 100644 node_modules/vuetify/lib/util/colorUtils.js.map create mode 100644 node_modules/vuetify/lib/util/colors.js create mode 100644 node_modules/vuetify/lib/util/colors.js.map create mode 100644 node_modules/vuetify/lib/util/component.js create mode 100644 node_modules/vuetify/lib/util/component.js.map create mode 100644 node_modules/vuetify/lib/util/console.js create mode 100644 node_modules/vuetify/lib/util/console.js.map create mode 100644 node_modules/vuetify/lib/util/dedupeModelListeners.js create mode 100644 node_modules/vuetify/lib/util/dedupeModelListeners.js.map create mode 100644 node_modules/vuetify/lib/util/easing-patterns.js create mode 100644 node_modules/vuetify/lib/util/easing-patterns.js.map create mode 100644 node_modules/vuetify/lib/util/helpers.js create mode 100644 node_modules/vuetify/lib/util/helpers.js.map create mode 100644 node_modules/vuetify/lib/util/mask.js create mode 100644 node_modules/vuetify/lib/util/mask.js.map create mode 100644 node_modules/vuetify/lib/util/mixins.js create mode 100644 node_modules/vuetify/lib/util/mixins.js.map create mode 100644 node_modules/vuetify/lib/util/rebuildFunctionalSlots.js create mode 100644 node_modules/vuetify/lib/util/rebuildFunctionalSlots.js.map create mode 100644 node_modules/vuetify/lib/util/theme.js create mode 100644 node_modules/vuetify/lib/util/theme.js.map create mode 100644 node_modules/vuetify/package.json create mode 100644 node_modules/vuetify/src/components/VAlert/VAlert.ts create mode 100644 node_modules/vuetify/src/components/VAlert/index.ts create mode 100644 node_modules/vuetify/src/components/VApp/VApp.js create mode 100644 node_modules/vuetify/src/components/VApp/index.js create mode 100644 node_modules/vuetify/src/components/VApp/mixins/app-theme.js create mode 100644 node_modules/vuetify/src/components/VAutocomplete/VAutocomplete.js create mode 100644 node_modules/vuetify/src/components/VAutocomplete/index.js create mode 100644 node_modules/vuetify/src/components/VAvatar/VAvatar.ts create mode 100644 node_modules/vuetify/src/components/VAvatar/index.ts create mode 100644 node_modules/vuetify/src/components/VBadge/VBadge.ts create mode 100644 node_modules/vuetify/src/components/VBadge/index.ts create mode 100644 node_modules/vuetify/src/components/VBottomNav/VBottomNav.ts create mode 100644 node_modules/vuetify/src/components/VBottomNav/index.ts create mode 100644 node_modules/vuetify/src/components/VBottomSheet/VBottomSheet.js create mode 100644 node_modules/vuetify/src/components/VBottomSheet/index.js create mode 100644 node_modules/vuetify/src/components/VBreadcrumbs/VBreadcrumbs.ts create mode 100644 node_modules/vuetify/src/components/VBreadcrumbs/VBreadcrumbsItem.ts create mode 100644 node_modules/vuetify/src/components/VBreadcrumbs/index.ts create mode 100644 node_modules/vuetify/src/components/VBtn/VBtn.ts create mode 100644 node_modules/vuetify/src/components/VBtn/index.ts create mode 100644 node_modules/vuetify/src/components/VBtnToggle/VBtnToggle.ts create mode 100644 node_modules/vuetify/src/components/VBtnToggle/index.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/VCalendar.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/VCalendarDaily.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/VCalendarMonthly.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/VCalendarWeekly.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/index.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/mixins/calendar-base.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/mixins/calendar-with-intervals.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/mixins/mouse.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/mixins/times.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/util/props.ts create mode 100644 node_modules/vuetify/src/components/VCalendar/util/timestamp.ts create mode 100644 node_modules/vuetify/src/components/VCard/VCard.ts create mode 100644 node_modules/vuetify/src/components/VCard/VCardMedia.ts create mode 100644 node_modules/vuetify/src/components/VCard/VCardTitle.ts create mode 100644 node_modules/vuetify/src/components/VCard/index.ts create mode 100644 node_modules/vuetify/src/components/VCarousel/VCarousel.ts create mode 100644 node_modules/vuetify/src/components/VCarousel/VCarouselItem.ts create mode 100644 node_modules/vuetify/src/components/VCarousel/index.ts create mode 100644 node_modules/vuetify/src/components/VCheckbox/VCheckbox.js create mode 100644 node_modules/vuetify/src/components/VCheckbox/index.js create mode 100644 node_modules/vuetify/src/components/VChip/VChip.ts create mode 100644 node_modules/vuetify/src/components/VChip/index.ts create mode 100644 node_modules/vuetify/src/components/VCombobox/VCombobox.js create mode 100644 node_modules/vuetify/src/components/VCombobox/index.js create mode 100644 node_modules/vuetify/src/components/VCounter/VCounter.ts create mode 100644 node_modules/vuetify/src/components/VCounter/index.ts create mode 100644 node_modules/vuetify/src/components/VDataIterator/VDataIterator.js create mode 100644 node_modules/vuetify/src/components/VDataIterator/index.js create mode 100644 node_modules/vuetify/src/components/VDataTable/VDataTable.js create mode 100644 node_modules/vuetify/src/components/VDataTable/VEditDialog.js create mode 100644 node_modules/vuetify/src/components/VDataTable/index.js create mode 100644 node_modules/vuetify/src/components/VDataTable/mixins/body.js create mode 100644 node_modules/vuetify/src/components/VDataTable/mixins/foot.js create mode 100644 node_modules/vuetify/src/components/VDataTable/mixins/head.js create mode 100644 node_modules/vuetify/src/components/VDataTable/mixins/progress.js create mode 100644 node_modules/vuetify/src/components/VDatePicker/VDatePicker.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/VDatePickerDateTable.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/VDatePickerHeader.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/VDatePickerMonthTable.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/VDatePickerTitle.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/VDatePickerYears.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/index.js create mode 100644 node_modules/vuetify/src/components/VDatePicker/mixins/date-picker-table.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/util/createNativeLocaleFormatter.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/util/index.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/util/isDateAllowed.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/util/monthChange.ts create mode 100644 node_modules/vuetify/src/components/VDatePicker/util/pad.ts create mode 100644 node_modules/vuetify/src/components/VDialog/VDialog.js create mode 100644 node_modules/vuetify/src/components/VDialog/index.js create mode 100644 node_modules/vuetify/src/components/VDivider/VDivider.ts create mode 100644 node_modules/vuetify/src/components/VDivider/index.ts create mode 100644 node_modules/vuetify/src/components/VExpansionPanel/VExpansionPanel.ts create mode 100644 node_modules/vuetify/src/components/VExpansionPanel/VExpansionPanelContent.ts create mode 100644 node_modules/vuetify/src/components/VExpansionPanel/index.ts create mode 100644 node_modules/vuetify/src/components/VFooter/VFooter.js create mode 100644 node_modules/vuetify/src/components/VFooter/index.js create mode 100644 node_modules/vuetify/src/components/VForm/VForm.js create mode 100644 node_modules/vuetify/src/components/VForm/index.js create mode 100644 node_modules/vuetify/src/components/VGrid/VContainer.js create mode 100644 node_modules/vuetify/src/components/VGrid/VContent.js create mode 100644 node_modules/vuetify/src/components/VGrid/VFlex.js create mode 100644 node_modules/vuetify/src/components/VGrid/VLayout.js create mode 100644 node_modules/vuetify/src/components/VGrid/grid.js create mode 100644 node_modules/vuetify/src/components/VGrid/index.js create mode 100644 node_modules/vuetify/src/components/VHover/VHover.ts create mode 100644 node_modules/vuetify/src/components/VHover/index.ts create mode 100644 node_modules/vuetify/src/components/VIcon/VIcon.ts create mode 100644 node_modules/vuetify/src/components/VIcon/index.ts create mode 100644 node_modules/vuetify/src/components/VImg/VImg.ts create mode 100644 node_modules/vuetify/src/components/VImg/index.ts create mode 100644 node_modules/vuetify/src/components/VInput/VInput.ts create mode 100644 node_modules/vuetify/src/components/VInput/index.ts create mode 100644 node_modules/vuetify/src/components/VItemGroup/VItem.ts create mode 100644 node_modules/vuetify/src/components/VItemGroup/VItemGroup.ts create mode 100644 node_modules/vuetify/src/components/VItemGroup/index.ts create mode 100644 node_modules/vuetify/src/components/VJumbotron/VJumbotron.js create mode 100644 node_modules/vuetify/src/components/VJumbotron/index.js create mode 100644 node_modules/vuetify/src/components/VLabel/VLabel.ts create mode 100644 node_modules/vuetify/src/components/VLabel/index.ts create mode 100644 node_modules/vuetify/src/components/VList/VList.ts create mode 100644 node_modules/vuetify/src/components/VList/VListGroup.ts create mode 100644 node_modules/vuetify/src/components/VList/VListTile.ts create mode 100644 node_modules/vuetify/src/components/VList/VListTileAction.ts create mode 100644 node_modules/vuetify/src/components/VList/VListTileAvatar.ts create mode 100644 node_modules/vuetify/src/components/VList/index.ts create mode 100644 node_modules/vuetify/src/components/VMenu/VMenu.js create mode 100644 node_modules/vuetify/src/components/VMenu/index.js create mode 100644 node_modules/vuetify/src/components/VMenu/mixins/menu-activator.js create mode 100644 node_modules/vuetify/src/components/VMenu/mixins/menu-generators.js create mode 100644 node_modules/vuetify/src/components/VMenu/mixins/menu-keyable.js create mode 100644 node_modules/vuetify/src/components/VMenu/mixins/menu-position.js create mode 100644 node_modules/vuetify/src/components/VMessages/VMessages.ts create mode 100644 node_modules/vuetify/src/components/VMessages/index.ts create mode 100644 node_modules/vuetify/src/components/VNavigationDrawer/VNavigationDrawer.ts create mode 100644 node_modules/vuetify/src/components/VNavigationDrawer/index.ts create mode 100644 node_modules/vuetify/src/components/VOverflowBtn/VOverflowBtn.js create mode 100644 node_modules/vuetify/src/components/VOverflowBtn/index.js create mode 100644 node_modules/vuetify/src/components/VPagination/VPagination.ts create mode 100644 node_modules/vuetify/src/components/VPagination/index.ts create mode 100644 node_modules/vuetify/src/components/VParallax/VParallax.ts create mode 100644 node_modules/vuetify/src/components/VParallax/index.ts create mode 100644 node_modules/vuetify/src/components/VPicker/VPicker.ts create mode 100644 node_modules/vuetify/src/components/VPicker/index.ts create mode 100644 node_modules/vuetify/src/components/VProgressCircular/VProgressCircular.ts create mode 100644 node_modules/vuetify/src/components/VProgressCircular/index.ts create mode 100644 node_modules/vuetify/src/components/VProgressLinear/VProgressLinear.ts create mode 100644 node_modules/vuetify/src/components/VProgressLinear/index.ts create mode 100644 node_modules/vuetify/src/components/VRadioGroup/VRadio.js create mode 100644 node_modules/vuetify/src/components/VRadioGroup/VRadioGroup.js create mode 100644 node_modules/vuetify/src/components/VRadioGroup/index.js create mode 100644 node_modules/vuetify/src/components/VRangeSlider/VRangeSlider.js create mode 100644 node_modules/vuetify/src/components/VRangeSlider/index.js create mode 100644 node_modules/vuetify/src/components/VRating/VRating.ts create mode 100644 node_modules/vuetify/src/components/VRating/index.ts create mode 100644 node_modules/vuetify/src/components/VResponsive/VResponsive.ts create mode 100644 node_modules/vuetify/src/components/VResponsive/index.ts create mode 100644 node_modules/vuetify/src/components/VSelect/VSelect.js create mode 100644 node_modules/vuetify/src/components/VSelect/VSelectList.js create mode 100644 node_modules/vuetify/src/components/VSelect/index.js create mode 100644 node_modules/vuetify/src/components/VSheet/VSheet.ts create mode 100644 node_modules/vuetify/src/components/VSheet/index.ts create mode 100644 node_modules/vuetify/src/components/VSlider/VSlider.js create mode 100644 node_modules/vuetify/src/components/VSlider/index.js create mode 100644 node_modules/vuetify/src/components/VSnackbar/VSnackbar.ts create mode 100644 node_modules/vuetify/src/components/VSnackbar/index.ts create mode 100644 node_modules/vuetify/src/components/VSparkline/VSparkline.ts create mode 100644 node_modules/vuetify/src/components/VSparkline/helpers/core.ts create mode 100644 node_modules/vuetify/src/components/VSparkline/helpers/math.ts create mode 100644 node_modules/vuetify/src/components/VSparkline/helpers/path.ts create mode 100644 node_modules/vuetify/src/components/VSparkline/index.ts create mode 100644 node_modules/vuetify/src/components/VSpeedDial/VSpeedDial.js create mode 100644 node_modules/vuetify/src/components/VSpeedDial/index.js create mode 100644 node_modules/vuetify/src/components/VStepper/VStepper.ts create mode 100644 node_modules/vuetify/src/components/VStepper/VStepperContent.ts create mode 100644 node_modules/vuetify/src/components/VStepper/VStepperStep.ts create mode 100644 node_modules/vuetify/src/components/VStepper/index.ts create mode 100644 node_modules/vuetify/src/components/VSubheader/VSubheader.ts create mode 100644 node_modules/vuetify/src/components/VSubheader/index.ts create mode 100644 node_modules/vuetify/src/components/VSwitch/VSwitch.js create mode 100644 node_modules/vuetify/src/components/VSwitch/index.js create mode 100644 node_modules/vuetify/src/components/VSystemBar/VSystemBar.ts create mode 100644 node_modules/vuetify/src/components/VSystemBar/index.ts create mode 100644 node_modules/vuetify/src/components/VTabs/VTab.js create mode 100644 node_modules/vuetify/src/components/VTabs/VTabItem.js create mode 100644 node_modules/vuetify/src/components/VTabs/VTabs.js create mode 100644 node_modules/vuetify/src/components/VTabs/VTabsItems.js create mode 100644 node_modules/vuetify/src/components/VTabs/VTabsSlider.js create mode 100644 node_modules/vuetify/src/components/VTabs/index.js create mode 100644 node_modules/vuetify/src/components/VTabs/mixins/tabs-computed.js create mode 100644 node_modules/vuetify/src/components/VTabs/mixins/tabs-generators.js create mode 100644 node_modules/vuetify/src/components/VTabs/mixins/tabs-props.js create mode 100644 node_modules/vuetify/src/components/VTabs/mixins/tabs-touch.js create mode 100644 node_modules/vuetify/src/components/VTabs/mixins/tabs-watchers.js create mode 100644 node_modules/vuetify/src/components/VTextField/VTextField.js create mode 100644 node_modules/vuetify/src/components/VTextField/index.js create mode 100644 node_modules/vuetify/src/components/VTextarea/VTextarea.js create mode 100644 node_modules/vuetify/src/components/VTextarea/index.js create mode 100644 node_modules/vuetify/src/components/VTimePicker/VTimePicker.ts create mode 100644 node_modules/vuetify/src/components/VTimePicker/VTimePickerClock.ts create mode 100644 node_modules/vuetify/src/components/VTimePicker/VTimePickerTitle.ts create mode 100644 node_modules/vuetify/src/components/VTimePicker/index.ts create mode 100644 node_modules/vuetify/src/components/VTimeline/VTimeline.ts create mode 100644 node_modules/vuetify/src/components/VTimeline/VTimelineItem.ts create mode 100644 node_modules/vuetify/src/components/VTimeline/index.ts create mode 100644 node_modules/vuetify/src/components/VToolbar/VToolbar.ts create mode 100644 node_modules/vuetify/src/components/VToolbar/VToolbarSideIcon.ts create mode 100644 node_modules/vuetify/src/components/VToolbar/index.ts create mode 100644 node_modules/vuetify/src/components/VTooltip/VTooltip.js create mode 100644 node_modules/vuetify/src/components/VTooltip/index.js create mode 100644 node_modules/vuetify/src/components/VTreeview/VTreeview.ts create mode 100644 node_modules/vuetify/src/components/VTreeview/VTreeviewNode.ts create mode 100644 node_modules/vuetify/src/components/VTreeview/index.ts create mode 100755 node_modules/vuetify/src/components/VTreeview/util/filterTreeItems.ts create mode 100644 node_modules/vuetify/src/components/VWindow/VWindow.ts create mode 100644 node_modules/vuetify/src/components/VWindow/VWindowItem.ts create mode 100644 node_modules/vuetify/src/components/VWindow/index.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/goTo/easing-patterns.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/goTo/index.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/goTo/util.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/index.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/mixins/application.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/mixins/breakpoint.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/mixins/icons.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/mixins/lang.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/mixins/options.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/mixins/theme.ts create mode 100644 node_modules/vuetify/src/components/Vuetify/util/goTo.js create mode 100644 node_modules/vuetify/src/components/index.ts create mode 100644 node_modules/vuetify/src/components/transitions/expand-transition.js create mode 100644 node_modules/vuetify/src/components/transitions/index.js create mode 100644 node_modules/vuetify/src/directives/click-outside.ts create mode 100644 node_modules/vuetify/src/directives/index.ts create mode 100644 node_modules/vuetify/src/directives/resize.ts create mode 100644 node_modules/vuetify/src/directives/ripple.ts create mode 100644 node_modules/vuetify/src/directives/scroll.ts create mode 100644 node_modules/vuetify/src/directives/touch.ts create mode 100644 node_modules/vuetify/src/entry-lib.ts create mode 100644 node_modules/vuetify/src/globals.d.ts create mode 100644 node_modules/vuetify/src/index.ts create mode 100644 node_modules/vuetify/src/locale/af.ts create mode 100644 node_modules/vuetify/src/locale/ar.ts create mode 100644 node_modules/vuetify/src/locale/ca.ts create mode 100644 node_modules/vuetify/src/locale/de.ts create mode 100755 node_modules/vuetify/src/locale/el.ts create mode 100644 node_modules/vuetify/src/locale/en.ts create mode 100644 node_modules/vuetify/src/locale/es.ts create mode 100644 node_modules/vuetify/src/locale/et.ts create mode 100644 node_modules/vuetify/src/locale/fa.ts create mode 100644 node_modules/vuetify/src/locale/fr.ts create mode 100644 node_modules/vuetify/src/locale/gr.ts create mode 100644 node_modules/vuetify/src/locale/hr.ts create mode 100644 node_modules/vuetify/src/locale/hu.ts create mode 100644 node_modules/vuetify/src/locale/id.ts create mode 100755 node_modules/vuetify/src/locale/index.ts create mode 100644 node_modules/vuetify/src/locale/it.ts create mode 100644 node_modules/vuetify/src/locale/ja.ts create mode 100644 node_modules/vuetify/src/locale/nl.ts create mode 100644 node_modules/vuetify/src/locale/pl.ts create mode 100644 node_modules/vuetify/src/locale/pt.ts create mode 100644 node_modules/vuetify/src/locale/ro.ts create mode 100644 node_modules/vuetify/src/locale/ru.ts create mode 100644 node_modules/vuetify/src/locale/sl.ts create mode 100644 node_modules/vuetify/src/locale/sr-Cyrl.ts create mode 100644 node_modules/vuetify/src/locale/th.ts create mode 100644 node_modules/vuetify/src/locale/tr.ts create mode 100644 node_modules/vuetify/src/locale/uk.ts create mode 100644 node_modules/vuetify/src/locale/zh-Hans.ts create mode 100644 node_modules/vuetify/src/locale/zh-Hant.ts create mode 100644 node_modules/vuetify/src/mixins/applicationable.ts create mode 100644 node_modules/vuetify/src/mixins/bootable.ts create mode 100644 node_modules/vuetify/src/mixins/button-group.ts create mode 100644 node_modules/vuetify/src/mixins/colorable.ts create mode 100644 node_modules/vuetify/src/mixins/comparable.ts create mode 100644 node_modules/vuetify/src/mixins/data-iterable.js create mode 100644 node_modules/vuetify/src/mixins/delayable.ts create mode 100644 node_modules/vuetify/src/mixins/dependent.ts create mode 100644 node_modules/vuetify/src/mixins/detachable.js create mode 100644 node_modules/vuetify/src/mixins/elevatable.ts create mode 100644 node_modules/vuetify/src/mixins/filterable.ts create mode 100644 node_modules/vuetify/src/mixins/groupable.ts create mode 100644 node_modules/vuetify/src/mixins/loadable.ts create mode 100644 node_modules/vuetify/src/mixins/maskable.js create mode 100644 node_modules/vuetify/src/mixins/measurable.ts create mode 100644 node_modules/vuetify/src/mixins/menuable.js create mode 100644 node_modules/vuetify/src/mixins/overlayable.ts create mode 100644 node_modules/vuetify/src/mixins/picker-button.ts create mode 100644 node_modules/vuetify/src/mixins/picker.ts create mode 100644 node_modules/vuetify/src/mixins/positionable.ts create mode 100644 node_modules/vuetify/src/mixins/proxyable.ts create mode 100644 node_modules/vuetify/src/mixins/registrable.ts create mode 100644 node_modules/vuetify/src/mixins/returnable.ts create mode 100644 node_modules/vuetify/src/mixins/rippleable.ts create mode 100644 node_modules/vuetify/src/mixins/routable.ts create mode 100644 node_modules/vuetify/src/mixins/selectable.js create mode 100644 node_modules/vuetify/src/mixins/sizeable.ts create mode 100644 node_modules/vuetify/src/mixins/ssr-bootable.ts create mode 100644 node_modules/vuetify/src/mixins/stackable.ts create mode 100644 node_modules/vuetify/src/mixins/themeable.ts create mode 100644 node_modules/vuetify/src/mixins/toggleable.ts create mode 100644 node_modules/vuetify/src/mixins/transitionable.ts create mode 100644 node_modules/vuetify/src/mixins/translatable.ts create mode 100644 node_modules/vuetify/src/mixins/validatable.ts create mode 100644 node_modules/vuetify/src/stylus/app.styl create mode 100644 node_modules/vuetify/src/stylus/bootstrap.styl create mode 100644 node_modules/vuetify/src/stylus/browsers.styl create mode 100644 node_modules/vuetify/src/stylus/components/_alerts.styl create mode 100644 node_modules/vuetify/src/stylus/components/_app.styl create mode 100644 node_modules/vuetify/src/stylus/components/_autocompletes.styl create mode 100644 node_modules/vuetify/src/stylus/components/_avatars.styl create mode 100644 node_modules/vuetify/src/stylus/components/_badges.styl create mode 100644 node_modules/vuetify/src/stylus/components/_bottom-navs.styl create mode 100644 node_modules/vuetify/src/stylus/components/_bottom-sheets.styl create mode 100644 node_modules/vuetify/src/stylus/components/_breadcrumbs.styl create mode 100644 node_modules/vuetify/src/stylus/components/_button-toggle.styl create mode 100644 node_modules/vuetify/src/stylus/components/_buttons.styl create mode 100644 node_modules/vuetify/src/stylus/components/_calendar-daily.styl create mode 100644 node_modules/vuetify/src/stylus/components/_calendar-weekly.styl create mode 100644 node_modules/vuetify/src/stylus/components/_cards.styl create mode 100644 node_modules/vuetify/src/stylus/components/_carousel.styl create mode 100644 node_modules/vuetify/src/stylus/components/_chips.styl create mode 100644 node_modules/vuetify/src/stylus/components/_content.styl create mode 100644 node_modules/vuetify/src/stylus/components/_counters.styl create mode 100644 node_modules/vuetify/src/stylus/components/_data-iterator.styl create mode 100644 node_modules/vuetify/src/stylus/components/_data-table.styl create mode 100644 node_modules/vuetify/src/stylus/components/_date-picker-header.styl create mode 100644 node_modules/vuetify/src/stylus/components/_date-picker-table.styl create mode 100644 node_modules/vuetify/src/stylus/components/_date-picker-title.styl create mode 100644 node_modules/vuetify/src/stylus/components/_date-picker-years.styl create mode 100644 node_modules/vuetify/src/stylus/components/_dialogs.styl create mode 100644 node_modules/vuetify/src/stylus/components/_dividers.styl create mode 100644 node_modules/vuetify/src/stylus/components/_expansion-panel.styl create mode 100644 node_modules/vuetify/src/stylus/components/_footer.styl create mode 100644 node_modules/vuetify/src/stylus/components/_forms.styl create mode 100644 node_modules/vuetify/src/stylus/components/_grid.styl create mode 100644 node_modules/vuetify/src/stylus/components/_icons.styl create mode 100644 node_modules/vuetify/src/stylus/components/_images.styl create mode 100644 node_modules/vuetify/src/stylus/components/_inputs.styl create mode 100644 node_modules/vuetify/src/stylus/components/_item-group.styl create mode 100644 node_modules/vuetify/src/stylus/components/_jumbotrons.styl create mode 100644 node_modules/vuetify/src/stylus/components/_labels.styl create mode 100644 node_modules/vuetify/src/stylus/components/_lists.styl create mode 100644 node_modules/vuetify/src/stylus/components/_menus.styl create mode 100644 node_modules/vuetify/src/stylus/components/_messages.styl create mode 100644 node_modules/vuetify/src/stylus/components/_navigation-drawer.styl create mode 100644 node_modules/vuetify/src/stylus/components/_overflow-buttons.styl create mode 100644 node_modules/vuetify/src/stylus/components/_overlay.styl create mode 100644 node_modules/vuetify/src/stylus/components/_pagination.styl create mode 100644 node_modules/vuetify/src/stylus/components/_parallax.styl create mode 100644 node_modules/vuetify/src/stylus/components/_pickers.styl create mode 100644 node_modules/vuetify/src/stylus/components/_progress-circular.styl create mode 100644 node_modules/vuetify/src/stylus/components/_progress-linear.styl create mode 100644 node_modules/vuetify/src/stylus/components/_radio-group.styl create mode 100644 node_modules/vuetify/src/stylus/components/_radios.styl create mode 100644 node_modules/vuetify/src/stylus/components/_range-sliders.styl create mode 100644 node_modules/vuetify/src/stylus/components/_rating.styl create mode 100644 node_modules/vuetify/src/stylus/components/_responsive.styl create mode 100644 node_modules/vuetify/src/stylus/components/_ripples.styl create mode 100644 node_modules/vuetify/src/stylus/components/_select.styl create mode 100644 node_modules/vuetify/src/stylus/components/_selection-controls.styl create mode 100644 node_modules/vuetify/src/stylus/components/_sheet.styl create mode 100644 node_modules/vuetify/src/stylus/components/_sliders.styl create mode 100644 node_modules/vuetify/src/stylus/components/_small-dialog.styl create mode 100644 node_modules/vuetify/src/stylus/components/_snackbars.styl create mode 100644 node_modules/vuetify/src/stylus/components/_speed-dial.styl create mode 100644 node_modules/vuetify/src/stylus/components/_steppers.styl create mode 100644 node_modules/vuetify/src/stylus/components/_subheaders.styl create mode 100644 node_modules/vuetify/src/stylus/components/_switch.styl create mode 100644 node_modules/vuetify/src/stylus/components/_system-bars.styl create mode 100644 node_modules/vuetify/src/stylus/components/_tables.styl create mode 100644 node_modules/vuetify/src/stylus/components/_tabs.styl create mode 100644 node_modules/vuetify/src/stylus/components/_text-fields.styl create mode 100644 node_modules/vuetify/src/stylus/components/_textarea.styl create mode 100644 node_modules/vuetify/src/stylus/components/_time-picker-clock.styl create mode 100644 node_modules/vuetify/src/stylus/components/_time-picker-title.styl create mode 100644 node_modules/vuetify/src/stylus/components/_timeline.styl create mode 100644 node_modules/vuetify/src/stylus/components/_toolbar.styl create mode 100644 node_modules/vuetify/src/stylus/components/_tooltips.styl create mode 100644 node_modules/vuetify/src/stylus/components/_treeview.styl create mode 100644 node_modules/vuetify/src/stylus/components/_windows.styl create mode 100644 node_modules/vuetify/src/stylus/elements/_blockquote.styl create mode 100644 node_modules/vuetify/src/stylus/elements/_code.styl create mode 100644 node_modules/vuetify/src/stylus/elements/_global.styl create mode 100644 node_modules/vuetify/src/stylus/elements/_headings.styl create mode 100644 node_modules/vuetify/src/stylus/elements/_lists.styl create mode 100644 node_modules/vuetify/src/stylus/elements/_typography.styl create mode 100644 node_modules/vuetify/src/stylus/generic/_animations.styl create mode 100644 node_modules/vuetify/src/stylus/generic/_colors.styl create mode 100644 node_modules/vuetify/src/stylus/generic/_elevations.styl create mode 100644 node_modules/vuetify/src/stylus/generic/_reset.styl create mode 100644 node_modules/vuetify/src/stylus/generic/_transitions.styl create mode 100644 node_modules/vuetify/src/stylus/main.styl create mode 100644 node_modules/vuetify/src/stylus/settings/_colors.styl create mode 100644 node_modules/vuetify/src/stylus/settings/_elevations.styl create mode 100644 node_modules/vuetify/src/stylus/settings/_rtl.styl create mode 100644 node_modules/vuetify/src/stylus/settings/_theme.styl create mode 100644 node_modules/vuetify/src/stylus/settings/_variables.styl create mode 100644 node_modules/vuetify/src/stylus/theme.styl create mode 100644 node_modules/vuetify/src/stylus/tools/_bootable.styl create mode 100644 node_modules/vuetify/src/stylus/trumps/_display.styl create mode 100644 node_modules/vuetify/src/stylus/trumps/_helpers.styl create mode 100644 node_modules/vuetify/src/stylus/trumps/_spacing.styl create mode 100644 node_modules/vuetify/src/stylus/trumps/_text.styl create mode 100644 node_modules/vuetify/src/stylus/trumps/_transition.styl create mode 100644 node_modules/vuetify/src/util/ThemeProvider.ts create mode 100644 node_modules/vuetify/src/util/color/transformCIELAB.ts create mode 100644 node_modules/vuetify/src/util/color/transformSRGB.ts create mode 100644 node_modules/vuetify/src/util/colorUtils.ts create mode 100644 node_modules/vuetify/src/util/colors.ts create mode 100644 node_modules/vuetify/src/util/component.ts create mode 100644 node_modules/vuetify/src/util/console.ts create mode 100644 node_modules/vuetify/src/util/dedupeModelListeners.ts create mode 100644 node_modules/vuetify/src/util/easing-patterns.js create mode 100644 node_modules/vuetify/src/util/helpers.spec.js create mode 100644 node_modules/vuetify/src/util/helpers.ts create mode 100644 node_modules/vuetify/src/util/mask.ts create mode 100644 node_modules/vuetify/src/util/mixins.ts create mode 100644 node_modules/vuetify/src/util/rebuildFunctionalSlots.ts create mode 100644 node_modules/vuetify/src/util/theme.ts create mode 100644 node_modules/vuetify/types/alacarte.d.ts create mode 100644 node_modules/vuetify/types/colors.d.ts create mode 100644 node_modules/vuetify/types/index.d.ts create mode 100644 node_modules/vuetify/types/lang.d.ts create mode 100644 node_modules/vuetify/types/lib.d.ts create mode 100644 public/routes/vuetifyImport.js diff --git a/node_modules/js-yaml/CHANGELOG.md b/node_modules/js-yaml/CHANGELOG.md index f07f612..3f1cc98 100644 --- a/node_modules/js-yaml/CHANGELOG.md +++ b/node_modules/js-yaml/CHANGELOG.md @@ -1,3 +1,28 @@ +3.13.1 / 2019-04-05 +------------------- + +- Fix possible code execution in (already unsafe) `.load()`, #480. + + +3.13.0 / 2019-03-20 +------------------- + +- Security fix: `safeLoad()` can hang when arrays with nested refs + used as key. Now throws exception for nested arrays. #475. + + +3.12.2 / 2019-02-26 +------------------- + +- Fix `noArrayIndent` option for root level, #468. + + +3.12.1 / 2019-01-05 +------------------- + +- Added `noArrayIndent` option, #432. + + 3.12.0 / 2018-06-02 ------------------- diff --git a/node_modules/js-yaml/README.md b/node_modules/js-yaml/README.md index c165c35..03a9e5a 100644 --- a/node_modules/js-yaml/README.md +++ b/node_modules/js-yaml/README.md @@ -104,7 +104,7 @@ options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. - Loader will throw on warnings if this function is not provided. + Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 @@ -170,6 +170,7 @@ disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). +- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from diff --git a/node_modules/js-yaml/dist/js-yaml.js b/node_modules/js-yaml/dist/js-yaml.js index 0c9e648..fad044a 100644 --- a/node_modules/js-yaml/dist/js-yaml.js +++ b/node_modules/js-yaml/dist/js-yaml.js @@ -1,4 +1,4 @@ -/* js-yaml 3.12.0 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0)) ? level - 1 : level; if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, level, state.dump, compact); + writeBlockSequence(state, arrayLevel, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { - writeFlowSequence(state, level, state.dump); + writeFlowSequence(state, arrayLevel, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } @@ -1005,6 +1007,8 @@ var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; +function _class(obj) { return Object.prototype.toString.call(obj); } + function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } @@ -1260,6 +1264,31 @@ function mergeMappings(state, destination, source, overridableKeys) { function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { var index, quantity; + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + keyNode = String(keyNode); if (_result === null) { diff --git a/node_modules/js-yaml/dist/js-yaml.min.js b/node_modules/js-yaml/dist/js-yaml.min.js index 0dcb7ba..0623500 100644 --- a/node_modules/js-yaml/dist/js-yaml.min.js +++ b/node_modules/js-yaml/dist/js-yaml.min.js @@ -1 +1 @@ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}}(function(){return function o(a,s,c){function u(t,e){if(!s[t]){if(!a[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(l)return l(t,!0);var i=new Error("Cannot find module '"+t+"'");throw i.code="MODULE_NOT_FOUND",i}var r=s[t]={exports:{}};a[t][0].call(r.exports,function(e){return u(a[t][1][e]||e)},r,r.exports,o,a,s,c)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e=i.flowLevel;switch(H(r,n,i.indent,t,function(e){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+V(r,i.indent)+Z(L(function(e,t){var n,i,r=/(\n+)([^\n]*)/g,o=(s=e.indexOf("\n"),s=-1!==s?s:e.length,r.lastIndex=s,z(e.slice(0,s),t)),a="\n"===e[0]||" "===e[0];var s;for(;i=r.exec(e);){var c=i[1],u=i[2];n=" "===u[0],o+=c+(a||n||""===u?"":"\n")+z(u,t),a=n}return o}(r,t),e));case $:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+c+'" style');i=s.represent[c](t,c)}e.dump=i}return!0}return!1}function Q(e,t,n,i,r,o){e.tag=null,e.dump=n,J(e,n,!1)||J(e,n,!0);var a=l.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return!0}function X(e,t){var n,i,r=[],o=[];for(function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;ot)&&0!==i)_(e,"bad indentation of a sequence entry");else if(e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt)&&(K(e,t,b,!0,r)&&(m?d=e.result:h=e.result),m||(D(e,l,p,f,d,h,o,a),f=d=h=null),q(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)_(e,"bad indentation of a mapping entry");else if(e.lineIndentl&&(l=e.lineIndent),j(o))p++;else{if(e.lineIndent>10),56320+(c-65536&1023)),e.position++}else _(e,"unknown escape sequence");n=i=e.position}else j(s)?(T(e,n,i,!0),R(e,q(e,!1,t)),n=i=e.position):e.position===e.lineStart&&Y(e)?_(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}_(e,"unexpected end of the stream within a double quoted scalar")}(e,p)?m=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!I(i)&&!E(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&_(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),e.anchorMap.hasOwnProperty(n)||_(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],q(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,s,c,u,l,p=e.kind,f=e.result;if(I(l=e.input.charCodeAt(e.position))||E(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(I(i=e.input.charCodeAt(e.position+1))||n&&E(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==l;){if(58===l){if(I(i=e.input.charCodeAt(e.position+1))||n&&E(i))break}else if(35===l){if(I(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&Y(e)||n&&E(l))break;if(j(l)){if(s=e.line,c=e.lineStart,u=e.lineIndent,q(e,!1,-1),e.lineIndent>=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(T(e,r,o,!1),R(e,e.line-s),r=o=e.position,a=!1),S(l)||(o=e.position+1),l=e.input.charCodeAt(++e.position)}return T(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,p,x===n)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||_(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=s&&B(e,f))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):_(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):_(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function $(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(r=e.input.charCodeAt(e.position))&&(q(e,!0,-1),r=e.input.charCodeAt(e.position),!(0t/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var i=e("./common"),r=e("./exception"),o=e("./type");function a(e,t,i){var r=[];return e.include.forEach(function(e){i=a(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new r("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),s.push(a>>8&255),s.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0==(n=r%4*6)?(s.push(a>>16&255),s.push(a>>8&255),s.push(255&a)):18===n?(s.push(a>>10&255),s.push(a>>2&255)):12===n&&s.push(a>>4&255),c?c.from?c.from(s):new c(s):s},predicate:function(e){return c&&c.isBuffer(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=u;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0==(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2===n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1===n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}})},{"../type":13}],15:[function(e,t,n){"use strict";var i=e("../type");t.exports=new i("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type"),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var a=/^[-+]?[0-9]+e/;t.exports=new r("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!o.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n,i,r;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,r=[],0<="+-".indexOf(t[0])&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:0<=t.indexOf(":")?(t.split(":").forEach(function(e){r.unshift(parseFloat(e,10))}),t=0,i=1,r.forEach(function(e){t+=e*i,i*=60}),n*t):n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return n=e.toString(10),a.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type");t.exports=new r("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a=i.flowLevel;switch(H(r,n,i.indent,t,function(e){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+V(r,i.indent)+Z(L(function(t,n){var e,i,r=/(\n+)([^\n]*)/g,o=function(){var e=t.indexOf("\n");return e=-1!==e?e:t.length,r.lastIndex=e,z(t.slice(0,e),n)}(),a="\n"===t[0]||" "===t[0];for(;i=r.exec(t);){var s=i[1],c=i[2];e=" "===c[0],o+=s+(a||e||""===c?"":"\n")+z(c,n),a=e}return o}(r,t),e));case $:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+c+'" style');i=s.represent[c](t,c)}e.dump=i}return!0}return!1}function Q(e,t,n,i,r,o){e.tag=null,e.dump=n,J(e,n,!1)||J(e,n,!0);var a=p.call(e.dump);i&&(i=e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return!0}function X(e,t){var n,i,r=[],o=[];for(function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;ot)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt?d=1:e.lineIndent===t?d=0:e.lineIndentt)&&($(e,t,b,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentl&&(l=e.lineIndent),j(o))p++;else{if(e.lineIndent>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else j(s)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}(e,p)?m=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!I(i)&&!O(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&N(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),e.anchorMap.hasOwnProperty(n)||N(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],Y(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,s,c,u,l,p=e.kind,f=e.result;if(I(l=e.input.charCodeAt(e.position))||O(l)||35===l||38===l||42===l||33===l||124===l||62===l||39===l||34===l||37===l||64===l||96===l)return!1;if((63===l||45===l)&&(I(i=e.input.charCodeAt(e.position+1))||n&&O(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==l;){if(58===l){if(I(i=e.input.charCodeAt(e.position+1))||n&&O(i))break}else if(35===l){if(I(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&R(e)||n&&O(l))break;if(j(l)){if(s=e.line,c=e.lineStart,u=e.lineIndent,Y(e,!1,-1),e.lineIndent>=t){a=!0,l=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),S(l)||(o=e.position+1),l=e.input.charCodeAt(++e.position)}return L(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,p,x===n)&&(m=!0,null===e.tag&&(e.tag="?")):(m=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===d&&(m=s&&P(e,f))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||m}function H(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};0!==(r=e.input.charCodeAt(e.position))&&(Y(e,!0,-1),r=e.input.charCodeAt(e.position),!(0t/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet())&&(n+=":\n"+t),n},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var i=e("./common"),r=e("./exception"),o=e("./type");function a(e,t,i){var r=[];return e.include.forEach(function(e){i=a(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function s(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new r("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=a(this,"implicit",[]),this.compiledExplicit=a(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),s.push(a>>8&255),s.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0==(n=r%4*6)?(s.push(a>>16&255),s.push(a>>8&255),s.push(255&a)):18==n?(s.push(a>>10&255),s.push(a>>2&255)):12==n&&s.push(a>>4&255),c?c.from?c.from(s):new c(s):s},predicate:function(e){return c&&c.isBuffer(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=u;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0==(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2==n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1==n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}})},{"../type":13}],15:[function(e,t,n){"use strict";var i=e("../type");t.exports=new i("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type"),o=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var a=/^[-+]?[0-9]+e/;t.exports=new r("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!o.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n,i,r;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,r=[],0<="+-".indexOf(t[0])&&(t=t.slice(1)),".inf"===t?1==n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:0<=t.indexOf(":")?(t.split(":").forEach(function(e){r.unshift(parseFloat(e,10))}),t=0,i=1,r.forEach(function(e){t+=e*i,i*=60}),n*t):n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){var n;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return n=e.toString(10),a.test(n)?n.replace("e",".e"):n},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),r=e("../type");t.exports=new r("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a 0)) ? level - 1 : level; if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, level, state.dump, compact); + writeBlockSequence(state, arrayLevel, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + state.dump; } } else { - writeFlowSequence(state, level, state.dump); + writeFlowSequence(state, arrayLevel, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } diff --git a/node_modules/js-yaml/lib/js-yaml/loader.js b/node_modules/js-yaml/lib/js-yaml/loader.js index fe2cb4d..2815c95 100644 --- a/node_modules/js-yaml/lib/js-yaml/loader.js +++ b/node_modules/js-yaml/lib/js-yaml/loader.js @@ -30,6 +30,8 @@ var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; +function _class(obj) { return Object.prototype.toString.call(obj); } + function is_EOL(c) { return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); } @@ -285,6 +287,31 @@ function mergeMappings(state, destination, source, overridableKeys) { function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { var index, quantity; + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + keyNode = String(keyNode); if (_result === null) { diff --git a/node_modules/js-yaml/package.json b/node_modules/js-yaml/package.json index 9a24aae..4ad4986 100644 --- a/node_modules/js-yaml/package.json +++ b/node_modules/js-yaml/package.json @@ -1,27 +1,27 @@ { - "_from": "js-yaml@^3.12.0", - "_id": "js-yaml@3.12.0", + "_from": "js-yaml@3.13.1", + "_id": "js-yaml@3.13.1", "_inBundle": false, - "_integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "_integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", "_location": "/js-yaml", "_phantomChildren": {}, "_requested": { - "type": "range", + "type": "version", "registry": true, - "raw": "js-yaml@^3.12.0", + "raw": "js-yaml@3.13.1", "name": "js-yaml", "escapedName": "js-yaml", - "rawSpec": "^3.12.0", + "rawSpec": "3.13.1", "saveSpec": null, - "fetchSpec": "^3.12.0" + "fetchSpec": "3.13.1" }, "_requiredBy": [ "/eslint" ], - "_resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", - "_shasum": "eaed656ec8344f10f527c6bfa1b6e2244de167d1", - "_spec": "js-yaml@^3.12.0", - "_where": "/home/erik/Documents/workspace_brackets/BME_Project_Ohm/om/node_modules/eslint", + "_resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "_shasum": "aff151b30bfdfa8e49e05da22e7415e9dfa37847", + "_spec": "js-yaml@3.13.1", + "_where": "/Users/xenia/Desktop/B_ME5/Projekt/om/node_modules/eslint", "author": { "name": "Vladimir Zapparov", "email": "dervus.grim@gmail.com" @@ -89,5 +89,5 @@ "scripts": { "test": "make test" }, - "version": "3.12.0" + "version": "3.13.1" } diff --git a/node_modules/mongoose/History.md b/node_modules/mongoose/History.md index 6b0f2d4..99cc5b0 100644 --- a/node_modules/mongoose/History.md +++ b/node_modules/mongoose/History.md @@ -1,3 +1,64 @@ +5.4.10 / 2019-02-05 +=================== + * docs: add search bar and /search page #6706 + * fix: support dotted aliases #7478 [chrischen](https://github.com/chrischen) + * fix(document): copy atomics when setting document array to an existing document array #7472 + * chore: upgrade to mongodb driver 3.1.13 #7488 + * docs: remove confusing references to executing a query "immediately" #7461 + * docs(guides+schematypes): link to custom schematypes docs #7407 + +5.4.9 / 2019-02-01 +================== + * fix(document): make `remove()`, `updateOne()`, and `update()` use the document's associated session #7455 + * fix(document): support passing args to hooked custom methods #7456 + * fix(document): avoid double calling single nested getters on `toObject()` #7442 + * fix(discriminator): handle global plugins modifying top-level discriminator options with applyPluginsToDiscriminators: true #7458 + * docs(documents): improve explanation of documents and use more modern syntax #7463 + * docs(middleware+api): fix a couple typos in examples #7474 [arniu](https://github.com/arniu) + +5.4.8 / 2019-01-30 +================== + * fix(query): fix unhandled error when casting object in array filters #7431 + * fix(query): cast query $elemMatch to discriminator schema if discriminator key set #7449 + * docs: add table of contents to all guides #7430 + +5.4.7 / 2019-01-26 +================== + * fix(populate): set `populated()` when using virtual populate #7440 + * fix(discriminator): defer applying plugins to embedded discriminators until model compilation so global plugins work #7435 + * fix(schema): report correct pathtype underneath map so setting dotted paths underneath maps works #7448 + * fix: get debug from options using the get helper #7451 #7446 [LucGranato](https://github.com/LucGranato) + * fix: use correct variable name #7443 [esben-semmle](https://github.com/esben-semmle) + * docs: fix broken QueryCursor link #7438 [shihabmridha](https://github.com/shihabmridha) + +5.4.6 / 2019-01-22 +================== + * fix(utils): make minimize leave empty objects in arrays instead of setting the array element to undefined #7322 + * fix(document): support passing `{document, query}` options to Schema#pre(regex) and Schema#post(regex) #7423 + * docs: add migrating to 5 guide to docs #7434 + * docs(deprecations): add instructions for fixing `count()` deprecation #7419 + * docs(middleware): add description and example for aggregate hooks #7402 + +4.13.18 / 2019-01-21 +==================== + * fix(model): handle setting populated path set via `Document#populate()` #7302 + * fix(cast): backport fix from #7290 to 4.x + +5.4.5 / 2019-01-18 +================== + * fix(populate): handle nested array `foreignField` with virtual populate #7374 + * fix(query): support not passing any arguments to `orFail()` #7409 + * docs(query): document what the resolved value for `deleteOne()`, `deleteMany()`, and `remove()` contains #7324 + * fix(array): allow opting out of converting non-arrays into arrays with `castNonArrays` option #7371 + * fix(query): ensure updateOne() doesnt unintentionally double call Schema#post(regexp) #7418 + +5.4.4 / 2019-01-14 +================== + * fix(query): run casting on arrayFilters option #7079 + * fix(document): support skipping timestamps on save() with `save({ timestamps: false })` #7357 + * fix(model): apply custom where on `Document#remove()` so we attach the shardKey #7393 + * docs(mongoose): document `mongoose.connections` #7338 + 5.4.3 / 2019-01-09 ================== * fix(populate): handle `count` option when using `Document#populate()` on a virtual #7380 diff --git a/node_modules/mongoose/README.md b/node_modules/mongoose/README.md index e9f696a..2f65bad 100644 --- a/node_modules/mongoose/README.md +++ b/node_modules/mongoose/README.md @@ -12,7 +12,7 @@ Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed [mongoosejs.com](http://mongoosejs.com/) -[Mongoose 5.0.0](https://github.com/Automattic/mongoose/blob/master/History.md#500--2018-01-17) was released on January 17, 2018. You can find more details on backwards breaking changes in 5.0.0 on [GitHub](https://github.com/Automattic/mongoose/blob/master/migrating_to_5.md). +[Mongoose 5.0.0](https://github.com/Automattic/mongoose/blob/master/History.md#500--2018-01-17) was released on January 17, 2018. You can find more details on [backwards breaking changes in 5.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_5.html). ## Support diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js index d12322d..4c8f699 100644 --- a/node_modules/mongoose/lib/document.js +++ b/node_modules/mongoose/lib/document.js @@ -570,7 +570,15 @@ function init(self, obj, doc, prefix) { Document.prototype.update = function update() { const args = utils.args(arguments); args.unshift({_id: this._id}); - return this.constructor.update.apply(this.constructor, args); + const query = this.constructor.update.apply(this.constructor, args); + + if (this.$session() != null) { + if (!('session' in query.options)) { + query.options.session = this.$session(); + } + } + + return query; }; /** @@ -603,6 +611,12 @@ Document.prototype.updateOne = function updateOne(doc, options, callback) { this.constructor._middleware.execPost('updateOne', this, [], {}, cb); }); + if (this.$session() != null) { + if (!('session' in query.options)) { + query.options.session = this.$session(); + } + } + if (callback != null) { return query.exec(callback); } @@ -1502,11 +1516,11 @@ Document.prototype.$isDefault = function(path) { * * ####Example: * product.remove(function (err, product) { - * product.isDeleted(); // true + * product.$isDeleted(); // true * product.remove(); // no-op, doesn't send anything to the db * - * product.isDeleted(false); - * product.isDeleted(); // false + * product.$isDeleted(false); + * product.$isDeleted(); // false * product.remove(); // will execute a remove against the db * }) * @@ -2791,7 +2805,13 @@ function applyGetters(self, json, type, options) { part = parts[ii]; v = cur[part]; if (ii === last) { - branch[part] = clone(self.get(path), options); + const val = self.get(path); + // Ignore single nested docs: getters will run because of `clone()` + // before `applyGetters()` in `$toObject()`. Quirk because single + // nested subdocs are hydrated docs in `_doc` as opposed to POJOs. + if (val != null && val.$__ == null) { + branch[part] = clone(val, options); + } } else if (v == null) { if (part in cur) { branch[part] = v; @@ -3104,43 +3124,41 @@ Document.prototype.depopulate = function(path) { if (typeof path === 'string') { path = path.split(' '); } - let i; let populatedIds; const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; + const populated = get(this, '$__.populated', {}); if (arguments.length === 0) { // Depopulate all - const keys = this.$__.populated ? Object.keys(this.$__.populated) : []; - - for (i = 0; i < virtualKeys.length; i++) { + for (let i = 0; i < virtualKeys.length; i++) { delete this.$$populatedVirtuals[virtualKeys[i]]; delete this._doc[virtualKeys[i]]; + delete populated[virtualKeys[i]]; } - for (i = 0; i < keys.length; i++) { + const keys = Object.keys(populated); + + for (let i = 0; i < keys.length; i++) { populatedIds = this.populated(keys[i]); if (!populatedIds) { continue; } - delete this.$__.populated[keys[i]]; + delete populated[keys[i]]; this.$set(keys[i], populatedIds); } return this; } - for (i = 0; i < path.length; i++) { + for (let i = 0; i < path.length; i++) { populatedIds = this.populated(path[i]); - if (!populatedIds) { - if (virtualKeys.indexOf(path[i]) === -1) { - continue; - } else { - delete this.$$populatedVirtuals[path[i]]; - delete this._doc[path[i]]; - continue; - } + delete populated[path[i]]; + + if (virtualKeys.indexOf(path[i]) !== -1) { + delete this.$$populatedVirtuals[path[i]]; + delete this._doc[path[i]]; + } else { + this.$set(path[i], populatedIds); } - delete this.$__.populated[path[i]]; - this.$set(path[i], populatedIds); } return this; }; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js index deeaa73..be68049 100644 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js +++ b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js @@ -117,7 +117,7 @@ function iter(i) { const collection = this.collection; const args = arguments; const _this = this; - const debug = _this.conn.base.options.debug; + const debug = get(_this, 'conn.base.options.debug'); // If user force closed, queueing will hang forever. See #5664 if (this.opts.$wasForceClosed) { diff --git a/node_modules/mongoose/lib/error/notFound.js b/node_modules/mongoose/lib/error/notFound.js index 6b61242..766fdee 100644 --- a/node_modules/mongoose/lib/error/notFound.js +++ b/node_modules/mongoose/lib/error/notFound.js @@ -13,15 +13,15 @@ const util = require('util'); * @inherits MongooseError */ -function DocumentNotFoundError(query) { +function DocumentNotFoundError(filter) { let msg; const messages = MongooseError.messages; if (messages.DocumentNotFoundError != null) { msg = typeof messages.DocumentNotFoundError === 'function' ? - messages.DocumentNotFoundError(query) : + messages.DocumentNotFoundError(filter) : messages.DocumentNotFoundError; } else { - msg = 'No document found for query "' + util.inspect(query) + '"'; + msg = 'No document found for query "' + util.inspect(filter) + '"'; } MongooseError.call(this, msg); @@ -33,7 +33,9 @@ function DocumentNotFoundError(query) { this.stack = new Error().stack; } - this.query = query; + this.filter = filter; + // Backwards compat + this.query = filter; } /*! diff --git a/node_modules/mongoose/lib/helpers/model/applyHooks.js b/node_modules/mongoose/lib/helpers/model/applyHooks.js index 802d978..0460578 100644 --- a/node_modules/mongoose/lib/helpers/model/applyHooks.js +++ b/node_modules/mongoose/lib/helpers/model/applyHooks.js @@ -109,10 +109,10 @@ function applyHooks(model, schema, options) { objToDecorate[method] = function() { const args = Array.prototype.slice.call(arguments); const cb = utils.last(args); - const argsWithoutCallback = cb == null ? args : - args.slice(0, args.length - 1); + const argsWithoutCallback = typeof cb === 'function' ? + args.slice(0, args.length - 1) : args; return utils.promiseOrCallback(cb, callback => { - this[`$__${method}`].apply(this, + return this[`$__${method}`].apply(this, argsWithoutCallback.concat([callback])); }, model.events); }; diff --git a/node_modules/mongoose/lib/helpers/model/discriminator.js b/node_modules/mongoose/lib/helpers/model/discriminator.js index 52bede1..d63b26c 100644 --- a/node_modules/mongoose/lib/helpers/model/discriminator.js +++ b/node_modules/mongoose/lib/helpers/model/discriminator.js @@ -1,7 +1,7 @@ 'use strict'; const defineKey = require('../document/compile').defineKey; -const get = require('../../helpers/get'); +const get = require('../get'); const utils = require('../../utils'); const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { @@ -15,23 +15,27 @@ const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { * ignore */ -module.exports = function discriminator(model, name, schema, tiedValue) { +module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { if (!(schema && schema.instanceOfSchema)) { throw new Error('You must pass a valid discriminator Schema'); } - const applyPluginsToDiscriminators = get(model.base, - 'options.applyPluginsToDiscriminators', false); - // Even if `applyPluginsToDiscriminators` isn't set, we should still apply - // global plugins to schemas embedded in the discriminator schema (gh-7370) - model.base._applyPlugins(schema, { skipTopLevel: !applyPluginsToDiscriminators }); - if (model.schema.discriminatorMapping && !model.schema.discriminatorMapping.isRoot) { throw new Error('Discriminator "' + name + '" can only be a discriminator of the root model'); } + if (applyPlugins) { + const applyPluginsToDiscriminators = get(model.base, + 'options.applyPluginsToDiscriminators', false); + // Even if `applyPluginsToDiscriminators` isn't set, we should still apply + // global plugins to schemas embedded in the discriminator schema (gh-7370) + model.base._applyPlugins(schema, { + skipTopLevel: !applyPluginsToDiscriminators + }); + } + const key = model.schema.options.discriminatorKey; const baseSchemaAddition = {}; diff --git a/node_modules/mongoose/lib/helpers/query/castFilterPath.js b/node_modules/mongoose/lib/helpers/query/castFilterPath.js new file mode 100644 index 0000000..a01c2b0 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/query/castFilterPath.js @@ -0,0 +1,55 @@ +'use strict'; + +module.exports = function castFilterPath(query, schematype, val) { + const ctx = query; + const any$conditionals = Object.keys(val).some(function(k) { + return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; + }); + + if (!any$conditionals) { + return schematype.castForQueryWrapper({ + val: val, + context: ctx + }); + } + + const ks = Object.keys(val); + + let k = ks.length; + + while (k--) { + const $cond = ks[k]; + const nested = val[$cond]; + + if ($cond === '$not') { + if (nested && schematype && !schematype.caster) { + const _keys = Object.keys(nested); + if (_keys.length && _keys[0].charAt(0) === '$') { + for (const key in nested) { + nested[key] = schematype.castForQueryWrapper({ + $conditional: key, + val: nested[key], + context: ctx + }); + } + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: ctx + }); + } + continue; + } + // cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); + } else { + val[$cond] = schematype.castForQueryWrapper({ + $conditional: $cond, + val: nested, + context: ctx + }); + } + } + + return val; +}; diff --git a/node_modules/mongoose/lib/helpers/update/castArrayFilters.js b/node_modules/mongoose/lib/helpers/update/castArrayFilters.js new file mode 100644 index 0000000..f24dd45 --- /dev/null +++ b/node_modules/mongoose/lib/helpers/update/castArrayFilters.js @@ -0,0 +1,62 @@ +'use strict'; + +const castFilterPath = require('../query/castFilterPath'); +const modifiedPaths = require('./modifiedPaths'); + +module.exports = function castArrayFilters(query) { + const arrayFilters = query.options.arrayFilters; + if (!Array.isArray(arrayFilters)) { + return; + } + + const update = query.getUpdate(); + const schema = query.schema; + + const updatedPaths = modifiedPaths(update); + + const updatedPathsByFilter = Object.keys(updatedPaths).reduce((cur, path) => { + const matches = path.match(/\$\[[^\]]+\]/g); + if (matches == null) { + return cur; + } + for (const match of matches) { + const firstMatch = path.indexOf(match); + if (firstMatch !== path.lastIndexOf(match)) { + throw new Error(`Path '${path}' contains the same array filter multiple times`); + } + cur[match.substring(2, match.length - 1)] = path.substr(0, firstMatch - 1); + } + return cur; + }, {}); + + for (const filter of arrayFilters) { + if (filter == null) { + throw new Error(`Got null array filter in ${arrayFilters}`); + } + const firstKey = Object.keys(filter)[0]; + + if (filter[firstKey] == null) { + continue; + } + + const dot = firstKey.indexOf('.'); + let filterPath = dot === -1 ? + updatedPathsByFilter[firstKey] + '.0' : + updatedPathsByFilter[firstKey.substr(0, dot)] + '.0' + firstKey.substr(dot); + + if (filterPath == null) { + throw new Error(`Filter path not found for ${firstKey}`); + } + + // If there are multiple array filters in the path being updated, make sure + // to replace them so we can get the schema path. + filterPath = filterPath.replace(/\$\[[^\]]+\]/g, '0'); + + const schematype = schema.path(filterPath); + if (typeof filter[firstKey] === 'object') { + filter[firstKey] = castFilterPath(query, schematype, filter[firstKey]); + } else { + filter[firstKey] = schematype.castForQuery(filter[firstKey]); + } + } +}; diff --git a/node_modules/mongoose/lib/index.js b/node_modules/mongoose/lib/index.js index cb0deb3..976f01e 100644 --- a/node_modules/mongoose/lib/index.js +++ b/node_modules/mongoose/lib/index.js @@ -19,6 +19,7 @@ const Types = require('./types'); const Query = require('./query'); const Model = require('./model'); const Document = require('./document'); +const get = require('./helpers/get'); const legacyPluralize = require('mongoose-legacy-pluralize'); const utils = require('./utils'); const pkg = require('../package.json'); @@ -555,17 +556,33 @@ Mongoose.prototype._applyPlugins = function(schema, options) { if (schema.$globalPluginsApplied) { return; } - let i; - let len; + schema.$globalPluginsApplied = true; + if (!options || !options.skipTopLevel) { - for (i = 0, len = this.plugins.length; i < len; ++i) { + for (let i = 0; i < this.plugins.length; ++i) { schema.plugin(this.plugins[i][0], this.plugins[i][1]); } - schema.$globalPluginsApplied = true; } - for (i = 0, len = schema.childSchemas.length; i < len; ++i) { + + for (let i = 0; i < schema.childSchemas.length; ++i) { this._applyPlugins(schema.childSchemas[i].schema); } + + const discriminators = schema.discriminators; + if (discriminators == null) { + return; + } + + const applyPluginsToDiscriminators = get(this, + 'options.applyPluginsToDiscriminators', false); + + const keys = Object.keys(discriminators); + for (let i = 0; i < keys.length; ++i) { + const discriminatorKey = keys[i]; + const discriminatorSchema = discriminators[discriminatorKey]; + + this._applyPlugins(discriminatorSchema, { skipTopLevel: !applyPluginsToDiscriminators }); + } }; /** @@ -586,7 +603,7 @@ Mongoose.prototype.plugin = function(fn, opts) { }; /** - * The default connection of the mongoose module. + * The Mongoose module's default connection. Equivalent to `mongoose.connections][0]`, see [`connections`](#mongoose_Mongoose-connections). * * ####Example: * @@ -596,10 +613,11 @@ Mongoose.prototype.plugin = function(fn, opts) { * * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). * + * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection). + * * @memberOf Mongoose * @instance - * @property connection - * @return {Connection} + * @property {Connection} connection * @api public */ @@ -614,6 +632,29 @@ Mongoose.prototype.__defineSetter__('connection', function(v) { } }); +/** + * An array containing all [connections](connections.html) associated with this + * Mongoose instance. By default, there is 1 connection. Calling + * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection + * to this array. + * + * ####Example: + * + * const mongoose = require('mongoose'); + * mongoose.connections.length; // 1, just the default connection + * mongoose.connections[0] === mongoose.connection; // true + * + * mongoose.createConnection('mongodb://localhost:27017/test'); + * mongoose.connections.length; // 2 + * + * @memberOf Mongoose + * @instance + * @property {Array} connections + * @api public + */ + +Mongoose.prototype.connections; + /*! * Driver dependent APIs */ diff --git a/node_modules/mongoose/lib/model.js b/node_modules/mongoose/lib/model.js index 4fbf5fb..7cb6370 100644 --- a/node_modules/mongoose/lib/model.js +++ b/node_modules/mongoose/lib/model.js @@ -171,13 +171,12 @@ Model.prototype.baseModelName; * MyModel.events.on('error', err => console.log(err.message)); * * // Prints a 'CastError' because of the above handler - * await MyModel.findOne({ _id: 'notanid' }).catch({} => {}); + * await MyModel.findOne({ _id: 'notanid' }).catch(noop); * * @api public * @fires error whenever any query or model function errors - * @property events * @memberOf Model - * @static + * @static events */ Model.events; @@ -193,15 +192,28 @@ Model.events; Model._middleware; +/*! + * ignore + */ + +function _applyCustomWhere(doc, where) { + if (doc.$where == null) { + return; + } + + const keys = Object.keys(doc.$where); + const len = keys.length; + for (let i = 0; i < len; ++i) { + where[keys[i]] = doc.$where[keys[i]]; + } +} + /*! * ignore */ Model.prototype.$__handleSave = function(options, callback) { const _this = this; - let i; - let keys; - let len; let saveOptions = {}; if ('safe' in options) { @@ -285,13 +297,7 @@ Model.prototype.$__handleSave = function(options, callback) { return; } - if (this.$where) { - keys = Object.keys(this.$where); - len = keys.length; - for (i = 0; i < len; ++i) { - where[keys[i]] = this.$where[keys[i]]; - } - } + _applyCustomWhere(this, where); this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, function(err, ret) { if (err) { @@ -420,6 +426,7 @@ function generateVersionError(doc, modifiedPaths) { * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) + * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. * @param {Function} [fn] optional callback * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. * @api public @@ -458,8 +465,11 @@ Model.prototype.save = function(options, fn) { return cb(parallelSave); } + this.$__.saveOptions = options; + this.$__save(options, error => { this.$__.saving = undefined; + delete this.$__.saveOptions; if (error) { this.$__handleReject(error); @@ -915,6 +925,15 @@ Model.prototype.$__remove = function $__remove(options, cb) { return cb(where); } + _applyCustomWhere(this, where); + + if (this.$session() != null) { + options = options || {}; + if (!('session' in options)) { + options.session = this.$session(); + } + } + this[modelCollectionSymbol].deleteOne(where, options, err => { if (!err) { this.$__.isDeleted = true; @@ -985,12 +1004,13 @@ Model.discriminator = function(name, schema, value) { } } - schema = discriminator(this, name, schema, value); + schema = discriminator(this, name, schema, value, true); if (this.db.models[name]) { throw new OverwriteModelError(name); } schema.$isRootDiscriminator = true; + schema.$globalPluginsApplied = true; model = this.db.model(model || name, schema, this.collection.name); this.discriminators[name] = model; @@ -1567,15 +1587,32 @@ Model.discriminators; * @return {Object} the translated 'pure' fields/conditions */ Model.translateAliases = function translateAliases(fields) { - const aliases = this.schema.aliases; - if (typeof fields === 'object') { // Fields is an object (query conditions or document fields) for (const key in fields) { - if (aliases[key]) { - fields[aliases[key]] = fields[key]; - delete fields[key]; + let alias; + const translated = []; + const fieldKeys = key.split('.'); + let currentSchema = this.schema; + for (const field in fieldKeys) { + const name = fieldKeys[field]; + if (currentSchema && currentSchema.aliases[name]) { + alias = currentSchema.aliases[name]; + // Alias found, + translated.push(alias); + } else { + // Alias not found, so treat as un-aliased key + translated.push(name); + } + + // Check if aliased path is a schema + if (currentSchema.paths[alias]) + currentSchema = currentSchema.paths[alias].schema; + else + currentSchema = null; } + fields[translated.join('.')] = fields[key]; + delete fields[key]; // We'll be using the translated key instead } return fields; @@ -1705,16 +1742,16 @@ Model.deleteMany = function deleteMany(conditions, options, callback) { * // named john and at least 18 * MyModel.find({ name: 'john', age: { $gte: 18 }}); * - * // executes immediately, passing results to callback + * // executes, passing results to callback * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); * - * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately + * // executes, name LIKE john and only selecting the "name" and "friends" fields * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) * * // passing options * MyModel.find({ name: /john/i }, null, { skip: 10 }) * - * // passing options and executing immediately + * // passing options and executes * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); * * // executing a query explicitly @@ -1787,7 +1824,7 @@ Model.find = function find(conditions, projection, options, callback) { * * ####Example: * - * // find adventure by id and execute immediately + * // find adventure by id and execute * Adventure.findById(id, function (err, adventure) {}); * * // same as above @@ -2013,7 +2050,7 @@ Model.count = function count(conditions, callback) { /** * Creates a Query for a `distinct` operation. * - * Passing a `callback` immediately executes the query. + * Passing a `callback` executes the query. * * ####Example * @@ -2103,7 +2140,7 @@ Model.$where = function $where() { /** * Issues a mongodb findAndModify update command. * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned. * * ####Options: * @@ -2236,8 +2273,7 @@ function _decorateUpdateWithVersionKey(update, options, versionKey) { * * Finds a matching document, updates it according to the `update` arg, * passing any `options`, and returns the found document (if any) to the - * callback. The query executes immediately if `callback` is passed else a - * Query object is returned. + * callback. The query executes if `callback` is passed. * * This function triggers the following middleware. * @@ -2335,7 +2371,7 @@ Model.findByIdAndUpdate = function(id, update, options, callback) { * Finds a matching document, removes it, and passes the found document * (if any) to the callback. * - * Executes immediately if `callback` is passed else a Query object is returned. + * Executes the query if `callback` is passed. * * This function triggers the following middleware. * @@ -2456,7 +2492,7 @@ Model.findByIdAndDelete = function(id, options, callback) { * Finds a matching document, replaces it with the provided doc, and passes the * returned doc to the callback. * - * Executes immediately if `callback` is passed else a Query object is returned. + * Executes the query if `callback` is passed. * * This function triggers the following query middleware. * @@ -2525,7 +2561,7 @@ Model.findOneAndReplace = function(conditions, options, callback) { * * Finds a matching document, removes it, passing the found document (if any) to the callback. * - * Executes immediately if `callback` is passed else a Query object is returned. + * Executes the query if `callback` is passed. * * This function triggers the following middleware. * @@ -2608,7 +2644,7 @@ Model.findOneAndRemove = function(conditions, options, callback) { * * Finds a matching document, removes it, passing the found document (if any) to the callback. * - * Executes immediately if `callback` is passed, else a `Query` object is returned. + * Executes the query if `callback` is passed. * * This function triggers the following middleware. * @@ -3851,6 +3887,7 @@ function populate(model, docs, options, callback) { for (const foreignField of mod.foreignField) { _val = utils.getValue(foreignField, val); if (Array.isArray(_val)) { + _val = utils.array.flatten(_val); const _valLength = _val.length; for (let j = 0; j < _valLength; ++j) { let __val = _val[j]; @@ -3937,6 +3974,8 @@ function assignVals(o) { justOne: o.justOne }); + const originalIds = [].concat(o.rawIds); + // replace the original ids in our intermediate _ids structure // with the documents found by query assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions); @@ -3978,6 +4017,7 @@ function assignVals(o) { } if (o.isVirtual && docs[i] instanceof Model) { + docs[i].populated(o.path, o.justOne ? originalIds[0] : originalIds, o.allOptions); // If virtual populate and doc is already init-ed, need to walk through // the actual doc to set rather than setting `_doc` directly mpath.set(o.path, rawIds[i], docs[i], setValue); diff --git a/node_modules/mongoose/lib/plugins/sharding.js b/node_modules/mongoose/lib/plugins/sharding.js index 0ea9996..129672a 100644 --- a/node_modules/mongoose/lib/plugins/sharding.js +++ b/node_modules/mongoose/lib/plugins/sharding.js @@ -16,6 +16,10 @@ module.exports = function shardingPlugin(schema) { applyWhere.call(this); next(); }); + schema.pre('remove', function(next) { + applyWhere.call(this); + next(); + }); schema.post('save', function() { storeShard.call(this); }); diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js index 250f6bc..c99bde6 100644 --- a/node_modules/mongoose/lib/query.js +++ b/node_modules/mongoose/lib/query.js @@ -5,12 +5,14 @@ */ const CastError = require('./error/cast'); +const DocumentNotFoundError = require('./error/notFound'); const Kareem = require('kareem'); const ObjectParameterError = require('./error/objectParameter'); const QueryCursor = require('./cursor/QueryCursor'); const ReadPreference = require('./driver').get().ReadPreference; const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); const cast = require('./cast'); +const castArrayFilters = require('./helpers/update/castArrayFilters'); const castUpdate = require('./helpers/query/castUpdate'); const completeMany = require('./helpers/query/completeMany'); const get = require('./helpers/get'); @@ -1728,6 +1730,18 @@ Query.prototype._castConditions = function() { } }; +/*! + * ignore + */ + +function _castArrayFilters(query) { + try { + castArrayFilters(query); + } catch (err) { + query.error(err); + } +} + /** * Thunk around find() * @@ -2388,39 +2402,52 @@ Query.prototype.sort = function(arg) { }; /** - * Declare and/or execute this query as a remove() operation. + * Declare and/or execute this query as a remove() operation. `remove()` is + * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) + * or [`deleteMany()`](#query_Query-deleteMany) instead. * * This function does not trigger any middleware * * ####Example * - * Model.remove({ artist: 'Anne Murray' }, callback) + * Character.remove({ name: /Stark/ }, callback); + * + * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.remove({ name: /Stark/ }); + * // Number of docs deleted + * res.deletedCount; * * ####Note * - * The operation is only executed when a callback is passed. To force execution without a callback, you must first call `remove()` and then execute it by using the `exec()` method. + * Calling `remove()` creates a [Mongoose query](./queries.html), and a query + * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), + * or call [`Query#exec()`](#query_Query-exec). * * // not executed - * var query = Model.find().remove({ name: 'Anne Murray' }) + * const query = Character.remove({ name: /Stark/ }); * * // executed - * query.remove({ name: 'Anne Murray' }, callback) - * query.remove({ name: 'Anne Murray' }).remove(callback) + * Character.remove({ name: /Stark/ }, callback); + * Character.remove({ name: /Stark/ }).remove(callback); * * // executed without a callback - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() + * Character.exec(); * * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, writeOpResult) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) * @return {Query} this - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ + * @deprecated + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove * @api public */ @@ -2462,7 +2489,7 @@ Query.prototype._remove = wrapThunk(function(callback) { callback = _wrapThunkCallback(this, callback); - return Query.base.remove.call(this, helpers.handleWriteOpResult(callback)); + return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback)); }); /** @@ -2474,14 +2501,28 @@ Query.prototype._remove = wrapThunk(function(callback) { * * ####Example * - * Character.deleteOne({ name: 'Eddard Stark' }, callback) - * Character.deleteOne({ name: 'Eddard Stark' }).then(next) + * Character.deleteOne({ name: 'Eddard Stark' }, callback); + * Character.deleteOne({ name: 'Eddard Stark' }).then(next); + * + * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.deleteOne({ name: 'Eddard Stark' }); + * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }` + * res.deletedCount; * * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, writeOpResult) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) * @return {Query} this - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne * @api public */ @@ -2524,7 +2565,7 @@ Query.prototype._deleteOne = wrapThunk(function(callback) { callback = _wrapThunkCallback(this, callback); - return Query.base.deleteOne.call(this, helpers.handleWriteOpResult(callback)); + return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback)); }); /** @@ -2539,11 +2580,25 @@ Query.prototype._deleteOne = wrapThunk(function(callback) { * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback) * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next) * + * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). + * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an + * object that contains 3 properties: + * + * - `ok`: `1` if no errors occurred + * - `deletedCount`: the number of documents deleted + * - `n`: the number of documents deleted. Equal to `deletedCount`. + * + * ####Example + * + * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); + * // `0` if no docs matched the filter, number of docs deleted otherwise + * res.deletedCount; + * * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, writeOpResult) + * @param {Function} [callback] optional params are (error, mongooseDeleteResult) * @return {Query} this - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ + * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult + * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany * @api public */ @@ -2586,7 +2641,7 @@ Query.prototype._deleteMany = wrapThunk(function(callback) { callback = _wrapThunkCallback(this, callback); - return Query.base.deleteMany.call(this, helpers.handleWriteOpResult(callback)); + return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback)); }); /*! @@ -2647,7 +2702,9 @@ function prepareDiscriminatorCriteria(query) { /** * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. + * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found + * document (if any) to the callback. The query executes if + * `callback` is passed. * * This function triggers the following middleware. * @@ -2778,7 +2835,8 @@ Query.prototype._findOneAndUpdate = wrapThunk(function(callback) { /** * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. + * Finds a matching document, removes it, passing the found document (if any) to + * the callback. Executes if `callback` is passed. * * This function triggers the following middleware. * @@ -2856,7 +2914,8 @@ Query.prototype.findOneAndRemove = function(conditions, options, callback) { /** * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command. * - * Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes immediately if `callback` is passed. + * Finds a matching document, removes it, and passes the found document (if any) + * to the callback. Executes if `callback` is passed. * * This function triggers the following middleware. * @@ -2978,7 +3037,8 @@ Query.prototype._findOneAndDelete = wrapThunk(function(callback) { /** * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command. * - * Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes immediately if `callback` is passed. + * Finds a matching document, removes it, and passes the found document (if any) + * to the callback. Executes if `callback` is passed. * * This function triggers the following middleware. * @@ -3147,6 +3207,8 @@ Query.prototype._findAndModify = function(type, callback) { return callback(castedQuery); } + _castArrayFilters(this); + const opts = this._optionsForExec(model); if ('strict' in opts) { @@ -3385,6 +3447,8 @@ function _updateThunk(op, callback) { this._castConditions(); + _castArrayFilters(this); + if (this.error() != null) { callback(this.error()); return null; @@ -3886,7 +3950,7 @@ Query.prototype.map = function(fn) { * @method orFail * @memberOf Query * @instance - * @param {Function|Error} [err] optional error to throw if no docs match `filter` + * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError` * @return {Query} this */ @@ -3895,42 +3959,36 @@ Query.prototype.orFail = function(err) { switch (this.op) { case 'find': if (res.length === 0) { - err = typeof err === 'function' ? err.call(this) : err; - throw err; + throw _orFailError(err, this); } break; case 'findOne': if (res == null) { - err = typeof err === 'function' ? err.call(this) : err; - throw err; + throw _orFailError(err, this); } break; case 'update': case 'updateMany': case 'updateOne': if (get(res, 'result.nModified') === 0) { - err = typeof err === 'function' ? err.call(this) : err; - throw err; + throw _orFailError(err, this); } break; case 'findOneAndDelete': if (get(res, 'lastErrorObject.n') === 0) { - err = typeof err === 'function' ? err.call(this) : err; - throw err; + throw _orFailError(err, this); } break; case 'findOneAndUpdate': if (get(res, 'lastErrorObject.updatedExisting') === false) { - err = typeof err === 'function' ? err.call(this) : err; - throw err; + throw _orFailError(err, this); } break; case 'deleteMany': case 'deleteOne': case 'remove': if (res.n === 0) { - err = typeof err === 'function' ? err.call(this) : err; - throw err; + throw _orFailError(err, this); } break; default: @@ -3942,6 +4000,22 @@ Query.prototype.orFail = function(err) { return this; }; +/*! + * Get the error to throw for `orFail()` + */ + +function _orFailError(err, query) { + if (typeof err === 'function') { + err = err.call(query); + } + + if (err == null) { + err = new DocumentNotFoundError(query.getQuery()); + } + + return err; +} + /** * Executes the query * diff --git a/node_modules/mongoose/lib/queryhelpers.js b/node_modules/mongoose/lib/queryhelpers.js index e5aa74f..d130a51 100644 --- a/node_modules/mongoose/lib/queryhelpers.js +++ b/node_modules/mongoose/lib/queryhelpers.js @@ -296,11 +296,12 @@ function makeLean(val) { * Handle the `WriteOpResult` from the server */ -exports.handleWriteOpResult = function handleWriteOpResult(callback) { - return function _handleWriteOpResult(error, res) { +exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { + return function _handleDeleteWriteOpResult(error, res) { if (error) { return callback(error); } - return callback(null, res.result); + return callback(null, + Object.assign({}, res.result, {deletedCount: res.deletedCount })); }; }; diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js index 4adc3cd..787b8e9 100644 --- a/node_modules/mongoose/lib/schema.js +++ b/node_modules/mongoose/lib/schema.js @@ -23,9 +23,11 @@ const validateRef = require('./helpers/populate/validateRef'); let MongooseTypes; -const allMiddleware = require('./helpers/query/applyQueryMiddleware'). - middlewareFunctions. - concat(require('./helpers/model/applyHooks').middlewareFunctions); +const queryHooks = require('./helpers/query/applyQueryMiddleware'). + middlewareFunctions; +const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions; +const hookNames = queryHooks.concat(documentHooks). + reduce((s, hook) => s.add(hook), new Set()); let id = 0; @@ -851,7 +853,7 @@ Schema.prototype.pathType = function(path) { } const re = new RegExp('^' + _path.replace(/\.\$\*/g, '.[^.]+') + '$'); if (re.test(path)) { - return this.paths[_path]; + return 'real'; } } @@ -918,6 +920,10 @@ Schema.prototype.setupTimestamp = function(timestamps) { this.add(schemaAdditions); this.pre('save', function(next) { + if (get(this, '$__.saveOptions.timestamps') === false) { + return next(); + } + const defaultTimestamp = (this.ownerDocument ? this.ownerDocument() : this). constructor.base.now(); const auto_id = this._id && this._id.auto; @@ -975,7 +981,7 @@ Schema.prototype.setupTimestamp = function(timestamps) { function getPositionalPathType(self, path) { const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); if (subpaths.length < 2) { - return self.paths.hasOwnProperty(subpaths[0]) ? self.paths[subpath[0]] : null; + return self.paths.hasOwnProperty(subpaths[0]) ? self.paths[subpaths[0]] : null; } let val = self.path(subpaths[0]); @@ -985,12 +991,10 @@ function getPositionalPathType(self, path) { } const last = subpaths.length - 1; - let subpath; - let i = 1; - for (; i < subpaths.length; ++i) { + for (let i = 1; i < subpaths.length; ++i) { isNested = false; - subpath = subpaths[i]; + const subpath = subpaths[i]; if (i === last && val && !/\D/.test(subpath)) { if (val.$isMongooseDocumentArray) { @@ -1095,7 +1099,7 @@ Schema.prototype.queue = function(name, args) { Schema.prototype.pre = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of allMiddleware) { + for (const fn of hookNames) { if (name.test(fn)) { this.pre.apply(this, [fn].concat(remainingArgs)); } @@ -1146,7 +1150,7 @@ Schema.prototype.pre = function(name) { Schema.prototype.post = function(name) { if (name instanceof RegExp) { const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of allMiddleware) { + for (const fn of hookNames) { if (name.test(fn)) { this.post.apply(this, [fn].concat(remainingArgs)); } diff --git a/node_modules/mongoose/lib/schema/array.js b/node_modules/mongoose/lib/schema/array.js index f8e7b49..691d2e7 100644 --- a/node_modules/mongoose/lib/schema/array.js +++ b/node_modules/mongoose/lib/schema/array.js @@ -128,6 +128,17 @@ function SchemaArray(key, cast, options, schemaOptions) { */ SchemaArray.schemaName = 'Array'; +/** + * Options for all arrays. + * + * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. + * + * @static options + * @api public + */ + +SchemaArray.options = { castNonArrays: true }; + /*! * Inherits from SchemaType. */ @@ -217,12 +228,17 @@ SchemaArray.prototype.cast = function(value, doc, init) { return value; } - // gh-2442: if we're loading this from the db and its not an array, mark - // the whole array as modified. - if (!!doc && !!init) { - doc.markModified(this.path); + + if (init || SchemaArray.options.castNonArrays) { + // gh-2442: if we're loading this from the db and its not an array, mark + // the whole array as modified. + if (!!doc && !!init) { + doc.markModified(this.path); + } + return this.cast([value], doc, init); } - return this.cast([value], doc, init); + + throw new CastError('Array', util.inspect(value), this.path); }; /*! @@ -336,16 +352,25 @@ function cast$all(val) { function cast$elemMatch(val) { const keys = Object.keys(val); const numKeys = keys.length; - let key; - let value; for (let i = 0; i < numKeys; ++i) { - key = keys[i]; - value = val[key]; + const key = keys[i]; + const value = val[key]; if (key.indexOf('$') === 0 && value) { val[key] = this.castForQuery(key, value); } } + // Is this an embedded discriminator and is the discriminator key set? + // If so, use the discriminator schema. See gh-7449 + const discriminatorKey = get(this, + 'casterConstructor.schema.options.discriminatorKey'); + const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); + if (discriminatorKey != null && + val[discriminatorKey] != null && + discriminators[val[discriminatorKey]] != null) { + return cast(discriminators[val[discriminatorKey]], val); + } + return cast(this.casterConstructor.schema, val); } diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js index ddb0713..d874ff2 100644 --- a/node_modules/mongoose/lib/schema/documentarray.js +++ b/node_modules/mongoose/lib/schema/documentarray.js @@ -61,6 +61,17 @@ function DocumentArray(key, schema, options, schemaOptions) { */ DocumentArray.schemaName = 'DocumentArray'; +/** + * Options for all document arrays. + * + * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. + * + * @static options + * @api public + */ + +DocumentArray.options = { castNonArrays: true }; + /*! * Inherits from ArrayType. */ @@ -310,6 +321,9 @@ DocumentArray.prototype.cast = function(value, doc, init, prev, options) { const _opts = { transform: false, virtuals: false }; if (!Array.isArray(value)) { + if (!init && !DocumentArray.options.castNonArrays) { + throw new CastError('DocumentArray', util.inspect(value), this.path); + } // gh-2442 mark whole array as modified if we're initializing a doc from // the db and the path isn't an array in the document if (!!doc && init) { diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js index 639de33..d78c738 100644 --- a/node_modules/mongoose/lib/schematype.js +++ b/node_modules/mongoose/lib/schematype.js @@ -1249,8 +1249,13 @@ SchemaType.prototype._castForQuery = function(val) { }; /** - * Override the function the required validator uses to check whether a string - * passes the `required` check. + * Override the function the required validator uses to check whether a value + * passes the `required` check. Override this on the individual SchemaType. + * + * ####Example: + * + * // Use this to allow empty strings to pass the `required` validator + * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); * * @param {Function} fn * @return {Function} diff --git a/node_modules/mongoose/lib/types/documentarray.js b/node_modules/mongoose/lib/types/documentarray.js index 1899980..223b7be 100644 --- a/node_modules/mongoose/lib/types/documentarray.js +++ b/node_modules/mongoose/lib/types/documentarray.js @@ -44,12 +44,6 @@ function MongooseDocumentArray(values, path, doc) { // TODO: replace this with `new CoreMongooseArray().concat()` when we remove // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png const arr = new CoreMongooseArray(); - if (Array.isArray(values)) { - values.forEach(v => { - arr.push(v); - }); - } - arr._path = path; const props = { isMongooseDocumentArray: true, @@ -59,6 +53,18 @@ function MongooseDocumentArray(values, path, doc) { _handlers: void 0 }; + if (Array.isArray(values)) { + if (values instanceof CoreMongooseArray && + values._path === path && + values._parent === doc) { + props._atomics = Object.assign({}, values._atomics); + } + values.forEach(v => { + arr.push(v); + }); + } + arr._path = path; + // Values always have to be passed to the constructor to initialize, since // otherwise MongooseArray#push will mark the array as modified to the parent. const keysMA = Object.keys(MongooseArray.mixin); diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js index 5c919f8..0605885 100644 --- a/node_modules/mongoose/lib/utils.js +++ b/node_modules/mongoose/lib/utils.js @@ -176,12 +176,13 @@ exports.last = function(arr) { * * @param {Object} obj the object to clone * @param {Object} options + * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. * @return {Object} the cloned object * @api private */ -exports.clone = function clone(obj, options) { - if (obj === undefined || obj === null) { +exports.clone = function clone(obj, options, isArrayChild) { + if (obj == null) { return obj; } @@ -199,7 +200,7 @@ exports.clone = function clone(obj, options) { if (obj.constructor) { switch (exports.getFunctionName(obj.constructor)) { case 'Object': - return cloneObject(obj, options); + return cloneObject(obj, options, isArrayChild); case 'Date': return new obj.constructor(+obj); case 'RegExp': @@ -222,12 +223,14 @@ exports.clone = function clone(obj, options) { if (!obj.constructor && exports.isObject(obj)) { // object created with Object.create(null) - return cloneObject(obj, options); + return cloneObject(obj, options, isArrayChild); } if (obj.valueOf) { return obj.valueOf(); } + + return cloneObject(obj, options, isArrayChild); }; const clone = exports.clone; @@ -279,19 +282,18 @@ exports.promiseOrCallback = function promiseOrCallback(callback, fn, ee) { * ignore */ -function cloneObject(obj, options) { +function cloneObject(obj, options, isArrayChild) { const minimize = options && options.minimize; const ret = {}; let hasKeys; - let val; - let k; - for (k in obj) { + for (const k in obj) { if (specialProperties.has(k)) { continue; } - val = clone(obj[k], options); + // Don't pass `isArrayChild` down + const val = clone(obj[k], options); if (!minimize || (typeof val !== 'undefined')) { hasKeys || (hasKeys = true); @@ -299,13 +301,13 @@ function cloneObject(obj, options) { } } - return minimize ? hasKeys && ret : ret; + return minimize && !isArrayChild ? hasKeys && ret : ret; } function cloneArray(arr, options) { const ret = []; for (let i = 0, l = arr.length; i < l; i++) { - ret.push(clone(arr[i], options)); + ret.push(clone(arr[i], options, true)); } return ret; } diff --git a/node_modules/mongoose/lib/virtualtype.js b/node_modules/mongoose/lib/virtualtype.js index 4612273..060ec61 100644 --- a/node_modules/mongoose/lib/virtualtype.js +++ b/node_modules/mongoose/lib/virtualtype.js @@ -16,6 +16,7 @@ * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual + * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) * @api public */ @@ -31,7 +32,7 @@ function VirtualType(options, name) { * * @param {Function} fn * @return {VirtualType} this - * @api public + * @api private */ VirtualType.prototype._applyDefaultGetters = function() { diff --git a/node_modules/mongoose/node_modules/mongodb-core/HISTORY.md b/node_modules/mongoose/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..501bbb0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,1085 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.1.11](https://github.com/mongodb-js/mongodb-core/compare/v3.1.10...v3.1.11) (2019-01-16) + + +### Bug Fixes + +* **wire-protocol:** don't allow override of `slaveOk` ([8fcef69](https://github.com/mongodb-js/mongodb-core/commit/8fcef69)) + + + + +## [3.1.10](https://github.com/mongodb-js/mongodb-core/compare/v3.1.9...v3.1.10) (2019-01-15) + + +### Bug Fixes + +* **mongos-replset:** pass connect options to child server instances ([7ffb4bb](https://github.com/mongodb-js/mongodb-core/commit/7ffb4bb)) +* **prettier:** fix prettier file paths for Windows ([00c631e](https://github.com/mongodb-js/mongodb-core/commit/00c631e)) + + + + +## [3.1.9](https://github.com/mongodb-js/mongodb-core/compare/v3.1.8...v3.1.9) (2018-11-16) + + +### Bug Fixes + +* **mongos:** ensure servers are properly cleaned up when destroyed ([68f4fd3](https://github.com/mongodb-js/mongodb-core/commit/68f4fd3)) +* **uri_parser:** uri-encoded auth handling ([81b5b45](https://github.com/mongodb-js/mongodb-core/commit/81b5b45)) +* **url-parser:** support passing in `auth` to parsing options ([29455ca](https://github.com/mongodb-js/mongodb-core/commit/29455ca)) + + + + +## [3.1.8](https://github.com/mongodb-js/mongodb-core/compare/v3.1.7...v3.1.8) (2018-11-05) + + +### Bug Fixes + +* **sspi:** correct auth process for SSPI ([808ab21](https://github.com/mongodb-js/mongodb-core/commit/808ab21)) +* **uri_parser:** add `replSet` to exemption list for number coercion ([d00b1ab](https://github.com/mongodb-js/mongodb-core/commit/d00b1ab)) + + + + +## [3.1.7](https://github.com/mongodb-js/mongodb-core/compare/v3.1.6...v3.1.7) (2018-10-10) + + +### Bug Fixes + +* **uri-parser:** persist default database when authSource present ([aa601d3](https://github.com/mongodb-js/mongodb-core/commit/aa601d3)) + + + + +## [3.1.6](https://github.com/mongodb-js/mongodb-core/compare/v3.1.4...v3.1.6) (2018-10-09) + + +### Bug Fixes + +* **srv-parsing:** ensure parse options are propogated to txt lookup ([923ceb0](https://github.com/mongodb-js/mongodb-core/commit/923ceb0)) +* **uri-parser:** add exemption list for number coercion in options ([82896ea](https://github.com/mongodb-js/mongodb-core/commit/82896ea)) + + + + +## [3.1.5](https://github.com/mongodb-js/mongodb-core/compare/v3.1.4...v3.1.5) (2018-09-15) + +### Bug Fixes + +* **connection:** Revert fast fallback due to Atlas connect issues ([3133fc3](https://github.com/mongodb-js/mongodb-core/commit/3133fc3)) + + + +## [3.1.4](https://github.com/mongodb-js/mongodb-core/compare/v3.1.3...v3.1.4) (2018-09-14) + + +### Bug Fixes + +* **apm:** fix upconversion for OP_QUERY in apm ([f969bee](https://github.com/mongodb-js/mongodb-core/commit/f969bee)) +* **gssapi:** check lowercase and camelCase gssapiServiceName option ([bf0315d](https://github.com/mongodb-js/mongodb-core/commit/bf0315d)) +* **test:** do not check deep equality when test.auth.db is null ([7d3c057](https://github.com/mongodb-js/mongodb-core/commit/7d3c057)) +* **uri_parser:** use admin as default auth.db ([345e6af](https://github.com/mongodb-js/mongodb-core/commit/345e6af)) + + +### Features + +* **connection:** Implement fast fallback ([622394a](https://github.com/mongodb-js/mongodb-core/commit/622394a)) + + + + +## [3.1.3](https://github.com/mongodb-js/mongodb-core/compare/v3.1.2...v3.1.3) (2018-08-25) + + +### Bug Fixes + +* **buffer:** use safe-buffer polyfill to maintain compatibility ([728d897](https://github.com/mongodb-js/mongodb-core/commit/728d897)) +* **EJSON:** export the result of optionally requiring EJSON ([645d73d](https://github.com/mongodb-js/mongodb-core/commit/645d73d)) + + +### Features + +* **kerberos:** bump kerberos dependency to `^1.0.0` ([1155ebe](https://github.com/mongodb-js/mongodb-core/commit/1155ebe)) +* **standard-version:** automate part of the release process ([4c768c4](https://github.com/mongodb-js/mongodb-core/commit/4c768c4)) + + + + +## [3.1.2](https://github.com/mongodb-js/mongodb-core/compare/v3.1.1...v3.1.2) (2018-08-13) + + +### Bug Fixes + +* **mongos:** fix connection leak when mongos reconnects ([2453746](https://github.com/mongodb-js/mongodb-core/commit/2453746)) + + +### Features + +* **bson:** update to bson ^1.1.x ([952a2f0](https://github.com/mongodb-js/mongodb-core/commit/952a2f0)) + + + + +## [3.1.1](https://github.com/mongodb-js/mongodb-core/compare/v3.0.6...v3.1.1) (2018-08-13) + + +### Bug Fixes + +* **auth:** prevent stalling on authentication when connected ([6b4ac89](https://github.com/mongodb-js/mongodb-core/commit/6b4ac89)) +* **buffer:** replace deprecated Buffer constructor ([7c71e19](https://github.com/mongodb-js/mongodb-core/commit/7c71e19)) +* **commands:** check doc.cursor errors ([4f2b263](https://github.com/mongodb-js/mongodb-core/commit/4f2b263)) +* **cursor:** check for session presence independently ([7c76c62](https://github.com/mongodb-js/mongodb-core/commit/7c76c62)) +* **cursor:** check for sessions independently in core cursor ([cb5df28](https://github.com/mongodb-js/mongodb-core/commit/cb5df28)) +* **cursor:** typo in _find() ([95f7fd2](https://github.com/mongodb-js/mongodb-core/commit/95f7fd2)) +* **error:** attach command response to MongoWriteConcernError ([#322](https://github.com/mongodb-js/mongodb-core/issues/322)) ([24c5d06](https://github.com/mongodb-js/mongodb-core/commit/24c5d06)) +* **getmore-killcursor:** slaveOk shall not be included on these ([40fb2f4](https://github.com/mongodb-js/mongodb-core/commit/40fb2f4)) +* **kerberos:** loosen restrictions on kerberos versions ([c4add26](https://github.com/mongodb-js/mongodb-core/commit/c4add26)) +* **mongos:** use `incrementTransactionNumber` directly on session ([e230d54](https://github.com/mongodb-js/mongodb-core/commit/e230d54)) +* **pool:** ensure that lsid is sent in get requests to mongos ([ae820f6](https://github.com/mongodb-js/mongodb-core/commit/ae820f6)) +* **read-preference:** correct server sort for `nearest` selection ([dd4eb9a](https://github.com/mongodb-js/mongodb-core/commit/dd4eb9a)) +* **sdam:** we can't use Array.includes yet ([9c3b5ab](https://github.com/mongodb-js/mongodb-core/commit/9c3b5ab)) +* **server:** correct typo using `this` instead of `server` ([c54f040](https://github.com/mongodb-js/mongodb-core/commit/c54f040)) +* **sessions:** add `toBSON` method to `ClientSession` ([d95a4d1](https://github.com/mongodb-js/mongodb-core/commit/d95a4d1)) +* **sessions:** never send `endSessions` from a `ClientSession` ([05ffe82](https://github.com/mongodb-js/mongodb-core/commit/05ffe82)) +* **topology-description:** we can't use Object.values yet ([91df350](https://github.com/mongodb-js/mongodb-core/commit/91df350)) +* **transactions:** do not send txnNumber for non-write commands ([#308](https://github.com/mongodb-js/mongodb-core/issues/308)) ([eb67b1a](https://github.com/mongodb-js/mongodb-core/commit/eb67b1a)) +* **uri_parser:** ensure default port is 27017 ([426a95e](https://github.com/mongodb-js/mongodb-core/commit/426a95e)) +* **uri-parser:** Incorrect parsing of arrays ([fcff104](https://github.com/mongodb-js/mongodb-core/commit/fcff104)) +* **uri-parser:** Parse comma separated option values ([2dd1de0](https://github.com/mongodb-js/mongodb-core/commit/2dd1de0)) +* **wireprotocol:** only send bypassDocumentValidation if true ([a81678b](https://github.com/mongodb-js/mongodb-core/commit/a81678b)) + + +### Features + +* **auth:** adds saslprep and SCRAM-SHA-256 ([506c087](https://github.com/mongodb-js/mongodb-core/commit/506c087)) +* **cursor:** implement cursor for new sdam implementation ([f289226](https://github.com/mongodb-js/mongodb-core/commit/f289226)) +* **cursor:** store operation time from initial query ([55e761e](https://github.com/mongodb-js/mongodb-core/commit/55e761e)) +* **error:** add more specific error type for write concern errors ([347c5d7](https://github.com/mongodb-js/mongodb-core/commit/347c5d7)) +* **Error:** adding error metadata field ([33be560](https://github.com/mongodb-js/mongodb-core/commit/33be560)) +* **kerberos:** expose warning for kerberos mismatch versions ([efc0e43](https://github.com/mongodb-js/mongodb-core/commit/efc0e43)) +* **max-staleness:** properly support a max staleness reducer ([d9c5c16](https://github.com/mongodb-js/mongodb-core/commit/d9c5c16)) +* **MongoTimeoutError:** add common class for timeout events ([c5b4752](https://github.com/mongodb-js/mongodb-core/commit/c5b4752)) +* **monitoring:** add support for server monitoring to `Server` ([30a394d](https://github.com/mongodb-js/mongodb-core/commit/30a394d)) +* **op-compressed:** add support for OP_COMPRESSED to new sdam impl ([8deec9b](https://github.com/mongodb-js/mongodb-core/commit/8deec9b)) +* **retryableWrites:** adding more support for retries ([d4c1597](https://github.com/mongodb-js/mongodb-core/commit/d4c1597)) +* **sdam-monitoring:** add basic monitoring for new Topology type ([bb0c522](https://github.com/mongodb-js/mongodb-core/commit/bb0c522)) +* **server:** add `command` support to new server class ([d9a8c05](https://github.com/mongodb-js/mongodb-core/commit/d9a8c05)) +* **server-selection:** add basic support for server selection ([ccc5e1d](https://github.com/mongodb-js/mongodb-core/commit/ccc5e1d)) +* **topology:** introduce a single Topology type, and test runner ([f35d773](https://github.com/mongodb-js/mongodb-core/commit/f35d773)) +* **topology-description:** add helper method for server ownership ([2c64c75](https://github.com/mongodb-js/mongodb-core/commit/2c64c75)) +* **txns:** add initial transaction interface for sessions ([ed76be0](https://github.com/mongodb-js/mongodb-core/commit/ed76be0)) + + + + +# [3.1.0](https://github.com/mongodb-js/mongodb-core/compare/v3.0.6...v3.1.0) (2018-06-27) + + +### Bug Fixes + +* **auth:** prevent stalling on authentication when connected ([6b4ac89](https://github.com/mongodb-js/mongodb-core/commit/6b4ac89)) +* **cursor:** check for session presence independently ([7c76c62](https://github.com/mongodb-js/mongodb-core/commit/7c76c62)) +* **cursor:** check for sessions independently in core cursor ([cb5df28](https://github.com/mongodb-js/mongodb-core/commit/cb5df28)) +* **error:** attach command response to MongoWriteConcernError ([#322](https://github.com/mongodb-js/mongodb-core/issues/322)) ([24c5d06](https://github.com/mongodb-js/mongodb-core/commit/24c5d06)) +* **getmore-killcursor:** slaveOk shall not be included on these ([40fb2f4](https://github.com/mongodb-js/mongodb-core/commit/40fb2f4)) +* **kerberos:** loosen restrictions on kerberos versions ([c4add26](https://github.com/mongodb-js/mongodb-core/commit/c4add26)) +* **mongos:** use `incrementTransactionNumber` directly on session ([e230d54](https://github.com/mongodb-js/mongodb-core/commit/e230d54)) +* **pool:** ensure that lsid is sent in get requests to mongos ([ae820f6](https://github.com/mongodb-js/mongodb-core/commit/ae820f6)) +* **sdam:** we can't use Array.includes yet ([9c3b5ab](https://github.com/mongodb-js/mongodb-core/commit/9c3b5ab)) +* **sessions:** add `toBSON` method to `ClientSession` ([d95a4d1](https://github.com/mongodb-js/mongodb-core/commit/d95a4d1)) +* **sessions:** never send `endSessions` from a `ClientSession` ([05ffe82](https://github.com/mongodb-js/mongodb-core/commit/05ffe82)) +* **topology-description:** we can't use Object.values yet ([91df350](https://github.com/mongodb-js/mongodb-core/commit/91df350)) +* **transactions:** do not send txnNumber for non-write commands ([#308](https://github.com/mongodb-js/mongodb-core/issues/308)) ([eb67b1a](https://github.com/mongodb-js/mongodb-core/commit/eb67b1a)) +* **wireprotocol:** only send bypassDocumentValidation if true ([a81678b](https://github.com/mongodb-js/mongodb-core/commit/a81678b)) + + +### Features + +* **auth:** adds saslprep and SCRAM-SHA-256 ([506c087](https://github.com/mongodb-js/mongodb-core/commit/506c087)) +* **cursor:** implement cursor for new sdam implementation ([f289226](https://github.com/mongodb-js/mongodb-core/commit/f289226)) +* **cursor:** store operation time from initial query ([55e761e](https://github.com/mongodb-js/mongodb-core/commit/55e761e)) +* **error:** add more specific error type for write concern errors ([347c5d7](https://github.com/mongodb-js/mongodb-core/commit/347c5d7)) +* **Error:** adding error metadata field ([33be560](https://github.com/mongodb-js/mongodb-core/commit/33be560)) +* **kerberos:** expose warning for kerberos mismatch versions ([efc0e43](https://github.com/mongodb-js/mongodb-core/commit/efc0e43)) +* **max-staleness:** properly support a max staleness reducer ([d9c5c16](https://github.com/mongodb-js/mongodb-core/commit/d9c5c16)) +* **MongoTimeoutError:** add common class for timeout events ([c5b4752](https://github.com/mongodb-js/mongodb-core/commit/c5b4752)) +* **op-compressed:** add support for OP_COMPRESSED to new sdam impl ([8deec9b](https://github.com/mongodb-js/mongodb-core/commit/8deec9b)) +* **retryableWrites:** adding more support for retries ([d4c1597](https://github.com/mongodb-js/mongodb-core/commit/d4c1597)) +* **sdam-monitoring:** add basic monitoring for new Topology type ([bb0c522](https://github.com/mongodb-js/mongodb-core/commit/bb0c522)) +* **server:** add `command` support to new server class ([d9a8c05](https://github.com/mongodb-js/mongodb-core/commit/d9a8c05)) +* **server-selection:** add basic support for server selection ([ccc5e1d](https://github.com/mongodb-js/mongodb-core/commit/ccc5e1d)) +* **topology:** introduce a single Topology type, and test runner ([f35d773](https://github.com/mongodb-js/mongodb-core/commit/f35d773)) +* **topology-description:** add helper method for server ownership ([2c64c75](https://github.com/mongodb-js/mongodb-core/commit/2c64c75)) +* **txns:** add initial transaction interface for sessions ([ed76be0](https://github.com/mongodb-js/mongodb-core/commit/ed76be0)) + + + + +## [3.0.6](https://github.com/mongodb-js/mongodb-core/compare/v3.0.5...v3.0.6) (2018-04-09) + + +### Bug Fixes + +* **2.6-protocol:** kill cursor callback is called by pool now ([65f2bf7](https://github.com/mongodb-js/mongodb-core/commit/65f2bf7)) +* **evergreen:** change name to id ([9303e12](https://github.com/mongodb-js/mongodb-core/commit/9303e12)) +* **evergreen:** change nvm path to local ([e42ea5b](https://github.com/mongodb-js/mongodb-core/commit/e42ea5b)) +* **evergreen:** pass in flag through npm scripts ([85708dd](https://github.com/mongodb-js/mongodb-core/commit/85708dd)) +* **pool:** ensure noResponse callback is only called if cb exists ([5281605](https://github.com/mongodb-js/mongodb-core/commit/5281605)) +* **replset:** only remove primary if primary is there ([1acd288](https://github.com/mongodb-js/mongodb-core/commit/1acd288)) +* **test-environments:** ensure all servers run on separate ports ([b63e5d8](https://github.com/mongodb-js/mongodb-core/commit/b63e5d8)) +* **uri_parser:** support a default database on mongodb+srv uris ([be01ffe](https://github.com/mongodb-js/mongodb-core/commit/be01ffe)) + + +### Features + +* **apm:** add events for command monitoring support in core ([37dce9c](https://github.com/mongodb-js/mongodb-core/commit/37dce9c)) +* **evergreen:** add evergreen config based on drivers skeleton ([b71da99](https://github.com/mongodb-js/mongodb-core/commit/b71da99)) +* **evergreen:** use evergreen flag when running tests ([55dff3b](https://github.com/mongodb-js/mongodb-core/commit/55dff3b)) + + + + +## [3.0.5](https://github.com/mongodb-js/mongodb-core/compare/v3.0.4...v3.0.5) (2018-03-14) + + +### Features + +* **sessions:** adding implicit cursor session support ([1607321](https://github.com/mongodb-js/mongodb-core/commit/1607321)) + + + + +## [3.0.4](https://github.com/mongodb-js/mongodb-core/compare/v3.0.3...v3.0.4) (2018-03-05) + + +### Bug Fixes + +* **connection:** ensure socket options are applied to ssl sockets ([e5ff927](https://github.com/mongodb-js/mongodb-core/commit/e5ff927)) + + + + +## [3.0.3](https://github.com/mongodb-js/mongodb-core/compare/v3.0.2...v3.0.3) (2018-02-23) + + +### Bug Fixes + +* **connection:** make pool not try to reconnect forever when reconnectTries = 0 ([#275](https://github.com/mongodb-js/mongodb-core/issues/275)) ([2d3fa98](https://github.com/mongodb-js/mongodb-core/commit/2d3fa98)), closes [Automattic/mongoose#6028](https://github.com/Automattic/mongoose/issues/6028) +* **retryableWrites:** only remove primary after retry ([#274](https://github.com/mongodb-js/mongodb-core/issues/274)) ([7ac171e](https://github.com/mongodb-js/mongodb-core/commit/7ac171e)) +* **sessions:** actually allow ending of sessions ([2b81bb6](https://github.com/mongodb-js/mongodb-core/commit/2b81bb6)) +* **uri-parser:** do not use `hasOwnProperty` to detect ssl ([69d16c7](https://github.com/mongodb-js/mongodb-core/commit/69d16c7)) + + +### Features + +* **sessions:** adding endAllPooledSessions helper method ([d7804ed](https://github.com/mongodb-js/mongodb-core/commit/d7804ed)) + + + + +## [3.0.2](https://github.com/mongodb-js/mongodb-core/compare/v3.0.1...v3.0.2) (2018-01-29) + + +### Bug Fixes + +* **cursor:** check for autoReconnect option only for single server ([645d6df](https://github.com/mongodb-js/mongodb-core/commit/645d6df)) + + +### Features + +* **mongodb+srv:** add support for mongodb+srv to the uri parser ([19b42ce](https://github.com/mongodb-js/mongodb-core/commit/19b42ce)) +* **uri-parser:** add initial implementation of uri parser for core ([8f797a7](https://github.com/mongodb-js/mongodb-core/commit/8f797a7)) +* **uri-parser:** expose the connection string parser as api ([fdeca2f](https://github.com/mongodb-js/mongodb-core/commit/fdeca2f)) + + + + +## [3.0.1](https://github.com/mongodb-js/mongodb-core/compare/v3.0.0...v3.0.1) (2017-12-24) + + +### Bug Fixes + +* **connection:** correct erroneous use of `this` in helper method ([06b9388](https://github.com/mongodb-js/mongodb-core/commit/06b9388)) + + + + +# [3.0.0](https://github.com/christkv/mongodb-core/compare/v3.0.0-rc0...v3.0.0) (2017-12-23) + + +### Bug Fixes + +* **connection:** ensure connection cleanup before fallback retry ([de62615](https://github.com/christkv/mongodb-core/commit/de62615)) +* **mock-server:** expose potential errors in message handlers ([65dcca4](https://github.com/christkv/mongodb-core/commit/65dcca4)) +* **mongos:** remove listener on destroy event ([243e942](https://github.com/christkv/mongodb-core/commit/243e942)), closes [#257](https://github.com/christkv/mongodb-core/issues/257) +* **sdam:** more explicit wire protocol error message ([6d6d19a](https://github.com/christkv/mongodb-core/commit/6d6d19a)) +* **secondaries:** fixes connection with secondary readPreference ([#258](https://github.com/christkv/mongodb-core/issues/258)) ([0060ad7](https://github.com/christkv/mongodb-core/commit/0060ad7)) +* **sessions:** ensure that we ignore session details from arbiters ([de0105c](https://github.com/christkv/mongodb-core/commit/de0105c)) +* **sharded-tests:** add `shardsvr` cmdline opt, wait for async fns ([867b080](https://github.com/christkv/mongodb-core/commit/867b080)) + + +### Features + +* **connection:** attempt both ipv6 and ipv4 when no family entered ([#260](https://github.com/christkv/mongodb-core/issues/260)) ([107bae5](https://github.com/christkv/mongodb-core/commit/107bae5)) + + + + +# 3.0.0-rc0 (2017-12-05) + + +### Bug Fixes + +* **auth-plain:** only use BSON -after- requiring it ([4934adf](https://github.com/christkv/mongodb-core/commit/4934adf)) +* **auth-scram:** cache the ScramSHA1 salted passwords up to 200 entries ([31ef03a](https://github.com/christkv/mongodb-core/commit/31ef03a)) +* **client-session:** don't report errors for endSessions commands ([c34eaf5](https://github.com/christkv/mongodb-core/commit/c34eaf5)) +* **connection:** default `family` to undefined rather than 4 ([c1b5e04](https://github.com/christkv/mongodb-core/commit/c1b5e04)) +* **connection:** fixing leak in 3.0.0 ([#235](https://github.com/christkv/mongodb-core/issues/235)) ([fc669c0](https://github.com/christkv/mongodb-core/commit/fc669c0)) +* **cursor:** avoid waiting for reconnect if reconnect disabled ([43e9b23](https://github.com/christkv/mongodb-core/commit/43e9b23)) +* **cursor:** callback with server response on `_find` ([6999459](https://github.com/christkv/mongodb-core/commit/6999459)) +* **errors:** export MongoError and MongoNetworkError at top-level ([972064a](https://github.com/christkv/mongodb-core/commit/972064a)) +* **errors:** throw MongoNetworkError from more places ([2cec239](https://github.com/christkv/mongodb-core/commit/2cec239)) +* **errors:** use subclassing for MongoNetworkError ([a132830](https://github.com/christkv/mongodb-core/commit/a132830)) +* **errors:** use util.inherits() and protect edge case ([c953246](https://github.com/christkv/mongodb-core/commit/c953246)) +* **mocha_server_tests:** rename confusing variable to fix tests ([a9fbae2](https://github.com/christkv/mongodb-core/commit/a9fbae2)) +* **mock-tests:** ensure all servers are properly cleaned up ([5dafc86](https://github.com/christkv/mongodb-core/commit/5dafc86)) +* **package:** upgrade mongodb-test-runner with bug fix ([5b2e99e](https://github.com/christkv/mongodb-core/commit/5b2e99e)) +* **pool:** check topology exists before verifying session support ([0aa146d](https://github.com/christkv/mongodb-core/commit/0aa146d)) +* **pool:** ensure inUse and connecting queues are cleared on reauth ([aa2840d](https://github.com/christkv/mongodb-core/commit/aa2840d)) +* **pool:** ensure that errors are propagated on force destroy ([8f8ad56](https://github.com/christkv/mongodb-core/commit/8f8ad56)) +* **pool:** ensure workItem is not null before accessing properties ([2143963](https://github.com/christkv/mongodb-core/commit/2143963)) +* **pool_tests:** remove .only ([8172137](https://github.com/christkv/mongodb-core/commit/8172137)) +* **retryable-writes:** don't increment `txnNumber` on retries ([e7c2242](https://github.com/christkv/mongodb-core/commit/e7c2242)) +* **retryable-writes:** network errors are retryable, inverted logic ([2727551](https://github.com/christkv/mongodb-core/commit/2727551)) +* **scram:** cache salted data, not the original data ([0cbe95f](https://github.com/christkv/mongodb-core/commit/0cbe95f)) +* **SDAM:** emit SDAM events on close and reconnect ([3451ff0](https://github.com/christkv/mongodb-core/commit/3451ff0)) +* **server:** avoid waiting for reconnect if reconnect disabled ([611a352](https://github.com/christkv/mongodb-core/commit/611a352)) +* **server:** correct minor typo in porting 2.x patch ([d92efec](https://github.com/christkv/mongodb-core/commit/d92efec)) +* **server_tests:** change 'this' to 'self' in some server tests ([992d9e9](https://github.com/christkv/mongodb-core/commit/992d9e9)) +* **server_tests:** fix errors in broken test ([1602e4d](https://github.com/christkv/mongodb-core/commit/1602e4d)) +* **server-session-pool:** don't add expired sessions to the pool ([8f48b89](https://github.com/christkv/mongodb-core/commit/8f48b89)) +* **server-session-pool:** ensure the queue is LIFO ([ac68e76](https://github.com/christkv/mongodb-core/commit/ac68e76)) +* **utils:** don't throw if no snappy ([55bf2ad](https://github.com/christkv/mongodb-core/commit/55bf2ad)) +* **wire-protocol:** 2.6 killCursor should not way for reply ([7337d91](https://github.com/christkv/mongodb-core/commit/7337d91)) + + +### Features + +* **cluster-time:** ensure clusterTime makes it to outgoing commands ([e700b79](https://github.com/christkv/mongodb-core/commit/e700b79)) +* **cluster-time:** track incoming cluster time gossiping ([c910706](https://github.com/christkv/mongodb-core/commit/c910706)) +* **compression:** implement wire protocol compression support ([2356ffb](https://github.com/christkv/mongodb-core/commit/2356ffb)) +* **connection-spy:** add class for monitoring active connections ([6dd6db3](https://github.com/christkv/mongodb-core/commit/6dd6db3)) +* **errors:** create MongoNetworkError ([df12740](https://github.com/christkv/mongodb-core/commit/df12740)) +* **inital-cluster-time:** allow session to define initia value ([e3a1c8b](https://github.com/christkv/mongodb-core/commit/e3a1c8b)) +* **mock:** support a means of consistently cleaning up mock servers ([ab3b70b](https://github.com/christkv/mongodb-core/commit/ab3b70b)) +* **mock-server:** add the ability to set a message handler ([9a8b815](https://github.com/christkv/mongodb-core/commit/9a8b815)) +* **operation-time:** track operationTime in relevant sessions ([8d512f1](https://github.com/christkv/mongodb-core/commit/8d512f1)) +* **pool:** introduce the concept of a minimum pool size ([b01b1f8](https://github.com/christkv/mongodb-core/commit/b01b1f8)) +* **replset:** more verbose replica set errors emission ([6d5eccd](https://github.com/christkv/mongodb-core/commit/6d5eccd)) +* **retryable-writes:** add mongos support for retryable writes ([7778067](https://github.com/christkv/mongodb-core/commit/7778067)) +* **retryable-writes:** initial support on replicasets ([73ac688](https://github.com/christkv/mongodb-core/commit/73ac688)) +* **retryable-writes:** retry on "not master" stepdown errors ([028aec7](https://github.com/christkv/mongodb-core/commit/028aec7)) +* **server-check:** reintroduce server version check ([486aace](https://github.com/christkv/mongodb-core/commit/486aace)) +* **server-session-pool:** implement session pool per spect ([a1d5b22](https://github.com/christkv/mongodb-core/commit/a1d5b22)) +* **session:** allow `session` options to be passed to write cmds ([5da75e4](https://github.com/christkv/mongodb-core/commit/5da75e4)) +* **sessions:** add equality operator to ease readability ([6510d7d](https://github.com/christkv/mongodb-core/commit/6510d7d)) +* **sessions:** export all sessions types on the top level ([35265b3](https://github.com/christkv/mongodb-core/commit/35265b3)) +* **sessions:** support sessions with cursors with find/getMore ([a016602](https://github.com/christkv/mongodb-core/commit/a016602)) +* **sessions:** track `logicalSessionTimeoutMinutes` for sessions ([11865bf](https://github.com/christkv/mongodb-core/commit/11865bf)) +* **ssl:** adding ssl options ciphers and ecdhCurve ([c839d5c](https://github.com/christkv/mongodb-core/commit/c839d5c)) +* **test/:** convert server_tests, undefined_tests, replset_tests, replset_state_tests, and repleset_server_selection_tests to run with mongodb-test-runner ([3a7c5fd](https://github.com/christkv/mongodb-core/commit/3a7c5fd)) + + +2.1.16 2017-10-11 +----------------- +* avoid waiting for reconnect if reconnect disabled in Server topology +* avoid waiting for reconnect if reconnect disabled in Cursor +* NODE-990 cache the ScramSHA1 salted passwords up to 200 entries +* NODE-1153 ensure that errors are propagated on force destroy +* NODE-1153 ensure inUse and connecting queues are cleared on reauth + +2.1.15 2017-08-08 +----------------- +* Emit SDAM events on close and reconnect + +2.1.14 2017-07-07 +----------------- +* NODE-1073 updates scram.js hi() algorithm to utilize crypto.pbkdf2Sync() +* NODE-1049 only include primary server if there are no secondary servers for + readPrefrence secondaryPreferred +* moved `assign` polyfill to shared utils, replace usage of `extend` in tests + +2.1.13 2017-06-19 +----------------- +* NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. +* Use actual server type in standalone SDAM events. + +2.1.12 2017-06-02 +----------------- +* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. +* Minor fix to report the correct state on error. +* NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). +* Fix require_optional loading of bson-ext. +* Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. +* NODE-999 SDAM fixes for Mongos and single Server event emitting. +* NODE-1014 Set socketTimeout to default to 360 seconds. +* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. + +2.1.11 2017-05-22 +----------------- +* NODE-987 Clear out old intervalIds on when calling topologyMonitor. +* NODE-987 Moved filtering to pingServer method and added test case. +* Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). +* NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interva. + +2.1.10 2017-04-18 +----------------- +* NODE-981 delegate auth to replset/mongos if inTopology is set. +* NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. +* Remove dynamic require (Issue #175, https://github.com/tellnes). +* NODE-696 Handle interrupted error for createIndexes. +* Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. +* NODE-966 promoteValues not being promoted correctly to getMore. +* Merged in fix for flushing out monitoring operations. + +2.1.9 2017-03-17 +---------------- +* Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. +* Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. +* Ensure SSL error propegates better for Replset connections when there is a SSL validation error. +* NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. +* NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. + +2.1.8 2017-02-13 +---------------- +* NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. +* NODE-927 fixes issue where authentication was performed against arbiter instances. +* NODE-915 Normalize all host names to avoid comparison issues. +* Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. + +2.1.7 2017-01-24 +---------------- +* NODE-919 ReplicaSet connection does not close immediately (Issue #156). +* NODE-901 Fixed bug when normalizing host names. +* NODE-909 Fixed readPreference issue caused by direct connection to primary. +* NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. + +2.1.6 2017-01-13 +---------------- +* NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. + +2.1.5 2017-01-11 +---------------- +* updated bson and bson-ext dependencies to 1.0.4 to work past early node 4.x.x version having a broken Buffer.from implementation. + +2.1.4 2017-01-03 +---------------- +* updated bson and bson-ext dependencies to 1.0.3 due to util.inspect issue with ObjectId optimizations. + +2.1.3 2017-01-03 +---------------- +* Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining +* Moved replicaset monitoring away from serial mode and to parallel mode. +* updated bson and bson-ext dependencies to 1.0.2. + +2.1.2 2016-12-10 +---------------- +* Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. +* Emit reconnect event in primary joining when in connected status for a replicaset. + +2.1.1 2016-12-08 +---------------- +* Updated bson library to 1.0.1. +* Added optional support for bson-ext 1.0.1. + +2.1.0 2016-12-05 +---------------- +* Updated bson library to 1.0.0. +* Added optional support for bson-ext 1.0.0. +* Expose property parserType allowing for identification of currently configured parser. + +2.0.14 2016-11-29 +----------------- +* Updated bson library to 0.5.7. +* Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). +* Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). +* Only check isConnected against availableConnections (Issue #142). +* NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. +* Set default servername to host is not passed through for sni. +* Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). +* NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. +* NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. +* NODE-850 Update Max Staleness implementation. +* NODE-849 username no longer required for MONGODB-X509 auth. +* NODE-848 BSON Regex flags must be alphabetically ordered. +* NODE-846 Create notice for all third party libraries. +* NODE-843 Executing bulk operations overwrites write concern parameter. +* NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. +* NODE-840 Resync CRUD spec tests. +* Unescapable while(true) loop (Issue #152). + +2.0.13 2016-10-21 +----------------- +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). +* Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). +* Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). +* NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). + +2.0.12 2016-09-15 +----------------- +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. + +2.0.11 2016-08-29 +----------------- +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propagated in same fashion as promoteValues and promoteLongs + +2.0.10 2016-08-23 +----------------- +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.0.9 2016-08-19 +---------------- +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.0.8 2016-08-16 +---------------- +* Allow execution of store operations indepent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Wrap callback in nextTick to ensure exceptions are thrown correctly. + +2.0.7 2016-07-28 +---------------- +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. +* Initial max staleness implementation for ReplSet and Mongos for 3.4 support. +* Added handling of collation for 3.4 support. + +2.0.6 2016-07-19 +---------------- +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.0.5 2016-07-15 +---------------- +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.0.4 2016-07-11 +----------------- +* Updated bson to version 0.5.1. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.0.3 2016-07-08 +----------------- +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. + +2.0.2 2016-07-06 +----------------- +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.0.1 2016-07-05 +----------------- +* Added missing logout method on mongos proxy topology. +* Fixed logger error serialization issue. +* Documentation fixes. + +2.0.0 2016-07-05 +----------------- +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. + +1.3.21 2016-05-30 +----------------- +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +1.3.20 2016-05-25 +----------------- +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +1.3.19 2016-05-17 +----------------- +- Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +- Set keepAlive to false by default to work around bug in node.js for Windows XP and Windows 2003. +- Ensure replicaset topology destroy is never called by SDAM. +- Ensure all paths are correctly returned on inspectServer in replset. + +1.3.18 2016-04-27 +----------------- +- Hardened cursor connection handling for getMore and killCursor to ensure mid operation connection kill does not throw null exception. +- Fixes for Node 6.0 support. + +1.3.17 2016-04-26 +----------------- +- Added improved handling of reconnect when topology is a single server. +- Added better handling of $query queries passed down for 3.2 or higher. +- Introduced getServerFrom method to topologies to let cursor grab a new pool for getMore and killCursors commands and not use connection pipelining. +- NODE-693 Move authentication to be after ismaster call to avoid authenticating against arbiters. + +1.3.16 2016-04-07 +----------------- +- Only call unref on destroy if it exists to ensure proper working destroy method on early node v0.10.x versions. + +1.3.15 2016-04-06 +----------------- +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +1.3.14 2016-04-01 +----------------- +- Ensure server inquireServerState exits immediately on server.destroy call. +- Refactored readPreference handling in 2.4, 2.6 and 3.2 wire protocol handling. + +1.3.13 2016-03-30 +----------------- +- Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +1.3.12 2016-03-29 +----------------- +- Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. + +1.3.11 2016-03-29 +----------------- +- isConnected method for mongos uses same selection code as getServer. +- Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +1.3.10 2016-03-22 +----------------- +- SDAM Monitoring emits diff for Replicasets to simplify detecting the state changes. +- SDAM Monitoring correctly emits Mongos as serverDescriptionEvent. + +1.3.9 2016-03-20 +---------------- +- Removed monitoring exclusive connection, should resolve timeouts and reconnects on idle replicasets where haInteval > socketTimeout. + +1.3.8 2016-03-18 +---------------- +- Implements the SDAM monitoring specification. +- Fix issue where cursor would error out and not be buffered when primary is not connected. + +1.3.7 2016-03-16 +---------------- +- Fixed issue with replicasetInquirer where it could stop performing monitoring if there was no servers available. + +1.3.6 2016-03-15 +---------------- +- Fixed raise condition where multiple replicasetInquirer operations could be started in parallel creating redundant connections. + +1.3.5 2016-03-14 +---------------- +- Handle rogue SSL exceptions (Issue #85, https://github.com/durran). + +1.3.4 2016-03-14 +---------------- +- Added unref options on server, replicaset and mongos (Issue #81, https://github.com/allevo) +- cursorNotFound flag always false (Issue #83, https://github.com/xgfd) +- refactor of events emission of fullsetup and all events (Issue #84, https://github.com/xizhibei) + +1.3.3 2016-03-08 +---------------- +- Added support for promoteLongs option for command function. +- Return connection if no callback available +- Emit connect event when server reconnects after initial connection failed (Issue #76, https://github.com/vkarpov15) +- Introduced optional monitoringSocketTimeout option to allow better control of SDAM monitoring timeouts. +- Made monitoringSocketTimeout default to 30000 if no connectionTimeout value specified or if set to 0. +- Fixed issue where tailable cursor would not retry even though cursor was still alive. +- Disabled exhaust flag support to avoid issues where users could easily write code that would cause memory to run out. +- Handle the case where the first command result document returns an empty list of documents but a live cursor. +- Allow passing down off CANONICALIZE_HOST_NAME and SERVICE_REALM options for kerberos. + +1.3.2 2016-02-09 +---------------- +- Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +- Ensure RequestId can never be larger than Max Number integer size. + +1.3.1 2016-02-05 +---------------- +- Removed annoying missing Kerberos error (NODE-654). + +1.3.0 2016-02-03 +---------------- +- Added raw support for the command function on topologies. +- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +- NODE-638, Cannot authenticate database user with utf-8 password. +- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +- Switched to using Array.push instead of concat for use cases of a lot of documents. +- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +- Added peer optional dependencies support using require_optional module. + +1.2.32 2016-01-12 +----------------- +- Bumped bson to V0.4.21 to allow using minor optimizations. + +1.2.31 2016-01-04 +----------------- +- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +1.2.30 2015-12-23 +----------------- +- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +1.2.29 2015-12-17 +----------------- +- Correctly emit close event when calling destroy on server topology. + +1.2.28 2015-12-13 +----------------- +- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. + +1.2.27 2015-12-13 +----------------- +- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). +- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). +- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). +- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. + +1.2.26 2015-11-23 +----------------- +- Converted test suite to use mongodb-topology-manager. +- Upgraded bson library to V0.4.20. +- Minor fixes for 3.2 readPreferences. + +1.2.25 2015-11-23 +----------------- +- Correctly error out when passed a seedlist of non-valid server members. + +1.2.24 2015-11-20 +----------------- +- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). +- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + +1.2.23 2015-11-16 +----------------- +- ismaster runs against admin.$cmd instead of system.$cmd. + +1.2.22 2015-11-16 +----------------- +- Fixes to handle getMore command errors for MongoDB 3.2 +- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +1.2.21 2015-11-07 +----------------- +- Hardened the checking for replicaset equality checks. +- OpReplay flag correctly set on Wire protocol query. +- Mongos load balancing added, introduced localThresholdMS to control the feature. +- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +1.2.20 2015-10-28 +----------------- +- Fixed bug in arbiter connection capping code. +- NODE-599 correctly handle arrays of server tags in order of priority. +- Fix for 2.6 wire protocol handler related to readPreference handling. +- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +1.2.19 2015-10-15 +----------------- +- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. +- Locked to bson 0.4.19. + +1.2.18 2015-10-15 +----------------- +- Minor 3.2 fix for handling readPreferences on sharded commands. +- Minor fixes to correctly pass APM specification test suite. + +1.2.17 2015-10-08 +----------------- +- Connections to arbiters only maintain a single connection. + +1.2.15 2015-10-06 +----------------- +- Set slaveOk to true for getMore and killCursors commands. +- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). +- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). + +1.2.14 2015-09-28 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 2015-09-18 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 2015-09-08 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 2015-08-31 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 2015-08-14 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 2015-08-05 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 2015-07-24 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 2015-07-16 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 2015-07-14 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 2015-07-14 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 2015-07-07 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 2015-06-26 +----------------- +- Minor bug fixes. + +1.2.2 2015-06-22 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 2015-06-17 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 2015-06-17 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 2015-05-31 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 2015-05-20 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 2015-05-19 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 2015-05-18 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 2015-05-17 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 2015-05-12 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 2015-05-12 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 2015-05-06 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 2015-04-24 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 2015-04-22 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 2015-04-15 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 2015-04-10 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 2015-03-26 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 2015-03-24 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 2015-03-21 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 2015-03-17 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 2015-03-16 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 2015-03-06 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 2015-03-04 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 2015-02-26 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 2015-02-24 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 2015-02-16 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 2015-02-02 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 2015-31-01 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 2015-21-01 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 2015-09-12 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 2014-18-12 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 2014-18-12 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 2014-17-12 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 2014-17-12 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 2014-01-12 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 2014-20-11 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 2014-14-11 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 2014-29-10 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 2014-24-10 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 2014-21-10 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 2014-07-10 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 2014-07-10 +---------------- +- Dependency issue solved + +1.0.0 2014-07-10 +---------------- +- Initial release of mongodb-core diff --git a/node_modules/mongoose/node_modules/mongodb-core/LICENSE b/node_modules/mongoose/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb-core/README.md b/node_modules/mongoose/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..d8b9edd --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/README.md @@ -0,0 +1,228 @@ +[![Build Status](https://secure.travis-ci.org/mongodb-js/mongodb-core.png)](http://travis-ci.org/mongodb-js/mongodb-core) +[![Coverage Status](https://coveralls.io/repos/github/mongodb-js/mongodb-core/badge.svg?branch=1.3)](https://coveralls.io/github/mongodb-js/mongodb-core?branch=1.3) + +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/mongodb-js/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/node_modules/mongoose/node_modules/mongodb-core/index.js b/node_modules/mongoose/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..a542d79 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/index.js @@ -0,0 +1,48 @@ +'use strict'; + +var BSON = require('bson'); +var require_optional = require('require_optional'); +const EJSON = require('./lib/utils').retrieveEJSON(); + +try { + // Attempt to grab the native BSON parser + var BSONNative = require_optional('bson-ext'); + // If we got the native parser, use it instead of the + // Javascript one + if (BSONNative) { + BSON = BSONNative; + } +} catch (err) {} // eslint-disable-line + +module.exports = { + // Errors + MongoError: require('./lib/error').MongoError, + MongoNetworkError: require('./lib/error').MongoNetworkError, + MongoParseError: require('./lib/error').MongoParseError, + MongoTimeoutError: require('./lib/error').MongoTimeoutError, + MongoWriteConcernError: require('./lib/error').MongoWriteConcernError, + mongoErrorContextSymbol: require('./lib/error').mongoErrorContextSymbol, + // Core + Connection: require('./lib/connection/connection'), + Server: require('./lib/topologies/server'), + ReplSet: require('./lib/topologies/replset'), + Mongos: require('./lib/topologies/mongos'), + Logger: require('./lib/connection/logger'), + Cursor: require('./lib/cursor'), + ReadPreference: require('./lib/topologies/read_preference'), + Sessions: require('./lib/sessions'), + BSON: BSON, + EJSON: EJSON, + // Raw operations + Query: require('./lib/connection/commands').Query, + // Auth mechanisms + defaultAuthProviders: require('./lib/auth/defaultAuthProviders').defaultAuthProviders, + MongoCR: require('./lib/auth/mongocr'), + X509: require('./lib/auth/x509'), + Plain: require('./lib/auth/plain'), + GSSAPI: require('./lib/auth/gssapi'), + ScramSHA1: require('./lib/auth/scram').ScramSHA1, + ScramSHA256: require('./lib/auth/scram').ScramSHA256, + // Utilities + parseConnectionString: require('./lib/uri_parser') +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js new file mode 100644 index 0000000..fc5f4c2 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js @@ -0,0 +1,29 @@ +'use strict'; + +const MongoCR = require('./mongocr'); +const X509 = require('./x509'); +const Plain = require('./plain'); +const GSSAPI = require('./gssapi'); +const SSPI = require('./sspi'); +const ScramSHA1 = require('./scram').ScramSHA1; +const ScramSHA256 = require('./scram').ScramSHA256; + +/** + * Returns the default authentication providers. + * + * @param {BSON} bson Bson definition + * @returns {Object} a mapping of auth names to auth types + */ +function defaultAuthProviders(bson) { + return { + mongocr: new MongoCR(bson), + x509: new X509(bson), + plain: new Plain(bson), + gssapi: new GSSAPI(bson), + sspi: new SSPI(bson), + 'scram-sha-1': new ScramSHA1(bson), + 'scram-sha-256': new ScramSHA256(bson) + }; +} + +module.exports = { defaultAuthProviders }; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/gssapi.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..cfaab74 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,381 @@ +'use strict'; + +const f = require('util').format; +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const retrieveKerberos = require('../utils').retrieveKerberos; + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + let kerberos; + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + + // TODO: remove this once we fix URI parsing + var gssapiServiceName = options['gssapiservicename'] || options['gssapiServiceName'] || 'mongodb'; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize( + self, + kerberos.processes.MongoAuthProcess, + db, + username, + password, + db, + gssapiServiceName, + server, + connection, + options, + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +// +// Initialize step +var GSSAPIInitialize = function( + self, + MongoAuthProcess, + db, + username, + password, + authdb, + gssapiServiceName, + server, + connection, + options, + callback +) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + // Perform initialization + mongo_auth_process.init(username, password, function(err) { + if (err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if (err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + server, + connection, + callback + ); + }); + }); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + server, + connection, + callback +) { + // Build the sasl start command + var command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload: payload, + autoAuthorize: 1 + }; + + // Write the commmand on the connection + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if (err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback + ); + }); + } + ); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback +) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + // Write the commmand on the connection + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (err) return callback(err, false); + var doc = r.result; + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if (err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback + ); + }); + } + ); +}; + +var MongoDBGSSAPIThirdStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback +) { + // Build final command + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (err) return callback(err, false); + mongo_auth_process.transition(null, function(err) { + if (err) return callback(err, null); + callback(null, r); + }); + } + ); +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +GSSAPI.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + authStore[i].options, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/mongocr.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..3f6a36c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,214 @@ +'use strict'; + +var f = require('util').format, + crypto = require('crypto'), + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var executeMongoCR = function(connection) { + // Write the commmand on the connection + server( + connection, + new Query( + self.bson, + f('%s.$cmd', db), + { + getnonce: 1 + }, + { + numberToSkip: 0, + numberToReturn: 1 + } + ), + function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if (err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + // Execute command + // Write the commmand on the connection + server( + connection, + new Query( + self.bson, + f('%s.$cmd', db), + { + authenticate: 1, + user: username, + nonce: nonce, + key: key + }, + { + numberToSkip: 0, + numberToReturn: 1 + } + ), + function(err, r) { + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + executeMongoCR(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +MongoCR.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/plain.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..deaea59 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,183 @@ +'use strict'; + +var f = require('util').format, + retrieveBSON = require('../connection/utils').retrieveBSON, + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError; + +var BSON = retrieveBSON(), + Binary = BSON.Binary; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Create payload + var payload = new Binary(f('\x00%s\x00%s', username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + // Let's start the process + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +Plain.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..719c580 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,442 @@ +'use strict'; + +var f = require('util').format, + crypto = require('crypto'), + retrieveBSON = require('../connection/utils').retrieveBSON, + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError, + Buffer = require('safe-buffer').Buffer; + +let saslprep; + +try { + saslprep = require('saslprep'); +} catch (e) { + // don't do anything; +} + +var BSON = retrieveBSON(), + Binary = BSON.Binary; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +var id = 0; + +/** + * Creates a new ScramSHA authentication mechanism + * @class + * @return {ScramSHA} A cursor instance + */ +var ScramSHA = function(bson, cryptoMethod) { + this.bson = bson; + this.authStore = []; + this.id = id++; + this.cryptoMethod = cryptoMethod || 'sha1'; +}; + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for (var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +}; + +var passwordDigest = function(username, password) { + if (typeof username !== 'string') throw new MongoError('username must be a string'); + if (typeof password !== 'string') throw new MongoError('password must be a string'); + if (password.length === 0) throw new MongoError('password cannot be empty'); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + return md5.digest('hex'); +}; + +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) a = Buffer.from(a); + if (!Buffer.isBuffer(b)) b = Buffer.from(b); + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method, text) { + return crypto + .createHash(method) + .update(text) + .digest(); +} + +function HMAC(method, key, text) { + return crypto + .createHmac(method, key) + .update(text) + .digest(); +} + +var _hiCache = {}; +var _hiCacheCount = 0; +var _hiCachePurge = function() { + _hiCache = {}; + _hiCacheCount = 0; +}; + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] !== undefined) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + const cryptoMethod = this.cryptoMethod; + let mechanism = 'SCRAM-SHA-1'; + let processedPassword; + + if (cryptoMethod === 'sha256') { + mechanism = 'SCRAM-SHA-256'; + + let saslprepFn = (server.s && server.s.saslprep) || saslprep; + + if (saslprepFn) { + processedPassword = saslprepFn(password); + } else { + console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); + processedPassword = password; + } + } else { + processedPassword = passwordDigest(username, password); + } + + // Execute MongoCR + var executeScram = function(connection) { + // Clean up the user + username = username.replace('=', '=3D').replace(',', '=2C'); + + // Create a random nonce + var nonce = crypto.randomBytes(24).toString('base64'); + // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + const firstBare = Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce, 'utf8') + ]); + + // Build command structure + var cmd = { + saslStart: 1, + mechanism: mechanism, + payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), + autoAuthorize: 1 + }; + + // Handle the error + var handleError = function(err, r) { + if (err) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; + return false; + } else if (r.result['$err']) { + errorObject = r.result; + return false; + } else if (r.result['errmsg']) { + errorObject = r.result; + return false; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true; + }; + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if (_count === 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if (_count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using scram')); + return callback(errorObject, false); + } + }; + + var handleEnd = function(_err, _r) { + // Handle any error + handleError(_err, _r); + // Adjust the number of connections + count = count - 1; + // Execute the finish + finish(count, numberOfValidConnections); + }; + + // Write the commmand on the connection + server( + connection, + new Query(self.bson, f('%s.$cmd', db), cmd, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + // Do we have an error, handle it + if (handleError(err, r) === false) { + count = count - 1; + + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using scram')); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.payload.value()); + + // Unpack dictionary + var iterations = parseInt(dict.i, 10); + var salt = dict.s; + var rnonce = dict.r; + + // Set up start of proof + var withoutProof = f('c=biws,r=%s', rnonce); + var saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + if (iterations && iterations < 4096) { + const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); + return callback(error, false); + } + + // Create the client key + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + + // Create the stored key + const storedKey = H(cryptoMethod, clientKey); + + // Create the authentication message + const authMessage = [ + firstBare, + r.result.payload.value().toString('base64'), + withoutProof + ].join(','); + + // Create client signature + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + + // Create client proof + const clientProof = f('p=%s', xor(clientKey, clientSignature)); + + // Create client final + const clientFinal = [withoutProof, clientProof].join(','); + + // Create continue message + const cmd = { + saslContinue: 1, + conversationId: r.result.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + // + // Execute sasl continue + // Write the commmand on the connection + server( + connection, + new Query(self.bson, f('%s.$cmd', db), cmd, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (r && r.result.done === false) { + var cmd = { + saslContinue: 1, + conversationId: r.result.conversationId, + payload: Buffer.alloc(0) + }; + + // Write the commmand on the connection + server( + connection, + new Query(self.bson, f('%s.$cmd', db), cmd, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + handleEnd(err, r); + } + ); + } else { + handleEnd(err, r); + } + } + ); + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + executeScram(_connection); + }); + }; + + // For each connection we need to authenticate + while (connections.length > 0) { + _execute(connections.shift()); + } +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +ScramSHA.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + // No connections + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +class ScramSHA1 extends ScramSHA { + constructor(bson) { + super(bson, 'sha1'); + } +} + +class ScramSHA256 extends ScramSHA { + constructor(bson) { + super(bson, 'sha256'); + } +} + +module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/sspi.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..61ff48d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,262 @@ +'use strict'; + +const f = require('util').format; +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const retrieveKerberos = require('../utils').retrieveKerberos; + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + let kerberos; + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate( + self, + kerberos.processes.MongoAuthProcess, + username, + password, + gssapiServiceName, + server, + connection, + options, + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r && typeof r === 'object' && r.result['$err']) { + errorObject = r.result; + } else if (r && typeof r === 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +function SSIPAuthenticate( + self, + MongoAuthProcess, + username, + password, + gssapiServiceName, + server, + connection, + options, + callback +) { + const authProcess = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + function authCommand(command, authCb) { + const query = new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }); + + server(connection, query, authCb); + } + + authProcess.init(username, password, err => { + if (err) return callback(err, false); + + authProcess.transition('', (err, payload) => { + if (err) return callback(err, false); + + const command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; + + authCommand(command, (err, result) => { + if (err) return callback(err, false); + const doc = result.result; + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, result) => { + if (err) return callback(err, false); + const doc = result.result; + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, response) => { + if (err) return callback(err, false); + + authProcess.transition(null, err => { + if (err) return callback(err, null); + callback(null, response); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +SSPI.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + authStore[i].options, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/auth/x509.js b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..e7c4bd8 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,179 @@ +'use strict'; + +var f = require('util').format, + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1, + mechanism: 'MONGODB-X509' + }; + + // Add username if specified + if (username) { + command.user = username; + } + + // Let's start the process + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +X509.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/apm.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/apm.js new file mode 100644 index 0000000..8cf1903 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/apm.js @@ -0,0 +1,228 @@ +'use strict'; +const KillCursor = require('../connection/commands').KillCursor; +const GetMore = require('../connection/commands').GetMore; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +// helper methods +const extractCommandName = command => Object.keys(command)[0]; +const namespace = command => command.ns; +const databaseName = command => command.ns.split('.')[0]; +const collectionName = command => command.ns.split('.')[1]; +const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; +const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); + +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldsSelector: 'projection' +}; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; + +/** + * Extract the actual command from the query, possibly upconverting if it's a legacy + * format + * + * @param {Object} command the command + */ +const extractCommand = command => { + if (command instanceof GetMore) { + return { + getMore: command.cursorId, + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: command.cursorIds + }; + } + + if (command.query && command.query.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // upconvert legacy command + result = Object.assign({}, command.query.$query); + } else { + // upconvert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (typeof command.query[key] !== 'undefined') + result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) result[key] = command[key]; + }); + + if (typeof command.pre32Limit !== 'undefined') { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + + return result; + } + + return command.query ? command.query : command; +}; + +const extractReply = (command, reply) => { + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + nextBatch: reply.message.documents + } + }; + } + + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + // is this a legacy find command? + if (command.query && typeof command.query.$query !== 'undefined') { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + firstBatch: reply.message.documents + } + }; + } + + return reply.result; +}; + +/** An event indicating the start of a given command */ +class CommandStartedEvent { + /** + * Create a started event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + */ + constructor(pool, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + // NOTE: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + Object.assign(this, { + command: cmd, + databaseName: databaseName(command), + commandName, + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the success of a given command */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {Object} reply the reply for this command from the server + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + reply: maybeRedact(commandName, extractReply(command, reply)), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the failure of a given command */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {MongoError|Object} error the generated error or a server error response + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + failure: maybeRedact(commandName, error), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +module.exports = { + CommandStartedEvent, + CommandSucceededEvent, + CommandFailedEvent +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/command_result.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/command_result.js new file mode 100644 index 0000000..be4eb52 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/command_result.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection, message) { + this.result = result; + this.connection = connection; + this.message = message; +}; + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +}; + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +}; + +module.exports = CommandResult; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/commands.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..0547a75 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,546 @@ +'use strict'; + +var retrieveBSON = require('./utils').retrieveBSON; +var BSON = retrieveBSON(); +var Long = BSON.Long; +const MongoError = require('../error').MongoError; +const Buffer = require('safe-buffer').Buffer; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var opcodes = require('../wireprotocol/shared').opcodes; + +// Query flags +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 1; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if (ns == null) throw new Error('ns must be specified for query'); + if (query == null) throw new Error('query must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + throw new Error('namespace cannot contain a null character'); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +}; + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +}; + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(self.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; + header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; + header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; + header[index] = opcodes.OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +}; + +Query.getRequestId = function() { + return ++_requestId; +}; + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; + _buffer[index] = opcodes.OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +}; + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + var index = 0; + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +}; + +var Response = function(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; +}; + +Response.prototype.isParsed = function() { + return this.parsed; +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + var promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + var promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + var promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; + var bsonSize, _options; + + // Set up the options + _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // + // Single document and documentsReturnedIn set + // + if (this.numberReturned === 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + if (doc instanceof Error) { + throw doc; + } + + if (doc.errmsg) { + throw new MongoError(doc.errmsg); + } + + if (!doc.cursor) { + throw new MongoError('Cursor not found'); + } + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = + typeof doc.cursor.id === 'number' ? Long.fromNumber(doc.cursor.id) : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true; + return; + } + + // + // Parse Body + // + for (var i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +}; + +module.exports = { + Query: Query, + GetMore: GetMore, + Response: Response, + KillCursor: KillCursor +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..71d461a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,805 @@ +'use strict'; + +var inherits = require('util').inherits, + EventEmitter = require('events').EventEmitter, + net = require('net'), + tls = require('tls'), + crypto = require('crypto'), + f = require('util').format, + debugOptions = require('./utils').debugOptions, + parseHeader = require('../wireprotocol/shared').parseHeader, + decompress = require('../wireprotocol/compression').decompress, + Response = require('./commands').Response, + MongoNetworkError = require('../error').MongoNetworkError, + Logger = require('./logger'), + OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED, + MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE, + Buffer = require('safe-buffer').Buffer; + +var _id = 0; +var debugFields = [ + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'socketTimeout', + 'singleBufferSerializtion', + 'ssl', + 'ca', + 'crl', + 'cert', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'checkServerIdentity' +]; + +var connectionAccountingSpy = undefined; +var connectionAccounting = false; +var connections = {}; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.family=null] IP version for DNS lookup, passed down to Node's [`dns.lookup()` function](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). If set to `6`, will only look for ipv6 addresses. + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(messageHandler, options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if (!options.bson) throw new Error('must pass in valid bson parser'); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || 1024 * 1024 * 16 * 4; + // Debug information + if (this.logger.isDebug()) + this.logger.debug( + f( + 'creating connection %s with options [%s]', + this.id, + JSON.stringify(debugOptions(debugFields, options)) + ) + ); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.family = typeof options.family === 'number' ? options.family : void 0; + this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; + this.noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; + this.connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + + // Is the keepAliveInitialDelay > socketTimeout set it to half of socketTimeout + if (this.keepAliveInitialDelay > this.socketTimeout) { + this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); + } + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('/') !== -1; + + // Serialize commands using function + this.singleBufferSerializtion = + typeof options.singleBufferSerializtion === 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.crl = options.crl || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ciphers = options.ciphers || null; + this.ecdhCurve = options.ecdhCurve || null; + this.ssl = typeof options.ssl === 'boolean' ? options.ssl : false; + this.rejectUnauthorized = + typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; + this.checkServerIdentity = + typeof options.checkServerIdentity === 'boolean' || + typeof options.checkServerIdentity === 'function' + ? options.checkServerIdentity + : true; + + // If ssl not enabled + if (!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false + }; + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); + + // All operations in flight on the connection + this.workItems = []; +}; + +inherits(Connection, EventEmitter); + +Connection.prototype.setSocketTimeout = function(value) { + if (this.connection) { + this.connection.setTimeout(value); + } +}; + +Connection.prototype.resetSocketTimeout = function() { + if (this.connection) { + this.connection.setTimeout(this.socketTimeout); + } +}; + +Connection.enableConnectionAccounting = function(spy) { + if (spy) { + connectionAccountingSpy = spy; + } + + connectionAccounting = true; + connections = {}; +}; + +Connection.disableConnectionAccounting = function() { + connectionAccounting = false; + connectionAccountingSpy = undefined; +}; + +Connection.connections = function() { + return connections; +}; + +function deleteConnection(id) { + // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) + delete connections[id]; + + if (connectionAccountingSpy) { + connectionAccountingSpy.deleteConnection(id); + } +} + +function addConnection(id, connection) { + // console.log("=== added connection " + id + " :: " + connection.port) + connections[id] = connection; + + if (connectionAccountingSpy) { + connectionAccountingSpy.addConnection(id, connection); + } +} + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + if (connectionAccounting) deleteConnection(self.id); + // Debug information + if (self.logger.isDebug()) + self.logger.debug( + f( + 'connection %s for [%s:%s] errored out with [%s]', + self.id, + self.host, + self.port, + JSON.stringify(err) + ) + ); + // Emit the error + if (self.listeners('error').length > 0) self.emit('error', new MongoNetworkError(err), self); + }; +}; + +var timeoutHandler = function(self) { + return function() { + if (connectionAccounting) deleteConnection(self.id); + // Debug information + if (self.logger.isDebug()) + self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit( + 'timeout', + new MongoNetworkError(f('connection %s to %s:%s timed out', self.id, self.host, self.port)), + self + ); + }; +}; + +var closeHandler = function(self) { + return function(hadError) { + if (connectionAccounting) deleteConnection(self.id); + // Debug information + if (self.logger.isDebug()) + self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + + // Emit close event + if (!hadError) { + self.emit( + 'close', + new MongoNetworkError(f('connection %s to %s:%s closed', self.id, self.host, self.port)), + self + ); + } + }; +}; + +// Handle a message once it is received +var emitMessageHandler = function(self, message) { + var msgHeader = parseHeader(message); + if (msgHeader.opCode === OP_COMPRESSED) { + msgHeader.fromCompressed = true; + var index = MESSAGE_HEADER_SIZE; + msgHeader.opCode = message.readInt32LE(index); + index += 4; + msgHeader.length = message.readInt32LE(index); + index += 4; + var compressorID = message[index]; + index++; + decompress(compressorID, message.slice(index), function(err, decompressedMsgBody) { + if (err) { + throw err; + } + if (decompressedMsgBody.length !== msgHeader.length) { + throw new Error( + 'Decompressing a compressed message from the server failed. The message is corrupt.' + ); + } + self.messageHandler( + new Response(self.bson, message, msgHeader, decompressedMsgBody, self.responseOptions), + self + ); + }); + } else { + self.messageHandler( + new Response( + self.bson, + message, + msgHeader, + message.slice(MESSAGE_HEADER_SIZE), + self.responseOptions + ), + self + ); + } +}; + +var dataHandler = function(self) { + return function(data) { + // Parse until we are done with the data + while (data.length > 0) { + // If we still have bytes to read on the current message + if (self.bytesRead > 0 && self.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; + // Check if the current chunk contains the rest of the message + if (remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(self.buffer, self.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + self.bytesRead = self.bytesRead + data.length; + + // Reset state of buffer + data = Buffer.alloc(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + try { + var emitBuffer = self.buffer; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + + emitMessageHandler(self, emitBuffer); + } catch (err) { + var errorObject = { + err: 'socketHandler', + trace: err, + bin: self.buffer, + parseState: { + sizeOfMessage: self.sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer + } + }; + // We got a parse Error fire it off then keep going + self.emit('parseError', errorObject, self); + } + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if (self.stubBuffer != null && self.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if (self.stubBuffer.length + data.length > 4) { + // Prepad the data + var newData = Buffer.alloc(self.stubBuffer.length + data.length); + self.stubBuffer.copy(newData, 0); + data.copy(newData, self.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + } else { + // Add the the bytes to the stub buffer + var newStubBuffer = Buffer.alloc(self.stubBuffer.length + data.length); + // Copy existing stub buffer + self.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, self.stubBuffer.length); + // Exit parsing loop + data = Buffer.alloc(0); + } + } else { + if (data.length > 4) { + // Retrieve the message size + // var sizeOfMessage = data.readUInt32LE(0); + var sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); + // If we have a negative sizeOfMessage emit error and return + if (sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + errorObject = { + err: 'socketHandler', + trace: '', + bin: self.buffer, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer + } + }; + // We got a parse Error fire it off then keep going + self.emit('parseError', errorObject, self); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if ( + sizeOfMessage > 4 && + sizeOfMessage < self.maxBsonMessageSize && + sizeOfMessage > data.length + ) { + self.buffer = Buffer.alloc(sizeOfMessage); + // Copy all the data into the buffer + data.copy(self.buffer, 0); + // Update bytes read + self.bytesRead = data.length; + // Update sizeOfMessage + self.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + self.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else if ( + sizeOfMessage > 4 && + sizeOfMessage < self.maxBsonMessageSize && + sizeOfMessage === data.length + ) { + try { + emitBuffer = data; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + // Emit the message + emitMessageHandler(self, emitBuffer); + } catch (err) { + self.emit('parseError', err, self); + } + } else if (sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + errorObject = { + err: 'socketHandler', + trace: null, + bin: data, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: 0, + buffer: null, + stubBuffer: null + } + }; + // We got a parse Error fire it off then keep going + self.emit('parseError', errorObject, self); + + // Clear out the state of the parser + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else { + emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + emitMessageHandler(self, emitBuffer); + } + } else { + // Create a buffer that contains the space for the non-complete message + self.stubBuffer = Buffer.alloc(data.length); + // Copy the data to the stub buffer + data.copy(self.stubBuffer, 0); + // Exit parsing loop + data = Buffer.alloc(0); + } + } + } + } + }; +}; + +// List of socket level valid ssl options +var legalSslSocketOptions = [ + 'pfx', + 'key', + 'passphrase', + 'cert', + 'ca', + 'ciphers', + 'NPNProtocols', + 'ALPNProtocols', + 'servername', + 'ecdhCurve', + 'secureProtocol', + 'secureContext', + 'session', + 'minDHSize' +]; + +function merge(options1, options2) { + // Merge in any allowed ssl options + for (var name in options2) { + if (options2[name] != null && legalSslSocketOptions.indexOf(name) !== -1) { + options1[name] = options2[name]; + } + } +} + +function makeSSLConnection(self, _options) { + let sslOptions = { + socket: self.connection, + rejectUnauthorized: self.rejectUnauthorized + }; + + // Merge in options + merge(sslOptions, self.options); + merge(sslOptions, _options); + + // Set options for ssl + if (self.ca) sslOptions.ca = self.ca; + if (self.crl) sslOptions.crl = self.crl; + if (self.cert) sslOptions.cert = self.cert; + if (self.key) sslOptions.key = self.key; + if (self.passphrase) sslOptions.passphrase = self.passphrase; + + // Override checkServerIdentity behavior + if (self.checkServerIdentity === false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + sslOptions.checkServerIdentity = function() { + return undefined; + }; + } else if (typeof self.checkServerIdentity === 'function') { + sslOptions.checkServerIdentity = self.checkServerIdentity; + } + + // Set default sni servername to be the same as host + if (sslOptions.servername == null) { + sslOptions.servername = self.host; + } + + // Attempt SSL connection + const connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if (connection.authorizationError && self.rejectUnauthorized) { + return self.emit('error', connection.authorizationError, self, { ssl: true }); + } + + // Set socket timeout instead of connection timeout + connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + + // Set the options for the connection + connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + connection.setTimeout(self.connectionTimeout); + connection.setNoDelay(self.noDelay); + + return connection; +} + +function makeUnsecureConnection(self, family) { + // Create new connection instance + let connection_options; + if (self.domainSocket) { + connection_options = { path: self.host }; + } else { + connection_options = { port: self.port, host: self.host }; + connection_options.family = family; + } + + const connection = net.createConnection(connection_options); + + // Set the options for the connection + connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + connection.setTimeout(self.connectionTimeout); + connection.setNoDelay(self.noDelay); + + connection.once('connect', function() { + // Set socket timeout instead of connection timeout + connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + + return connection; +} + +function doConnect(self, family, _options, _errorHandler) { + self.connection = self.ssl + ? makeSSLConnection(self, _options) + : makeUnsecureConnection(self, family); + + // Add handlers for events + self.connection.once('error', _errorHandler); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + _options = _options || {}; + // Set the connections + if (connectionAccounting) addConnection(this.id, this); + // Check if we are overriding the promoteLongs + if (typeof _options.promoteLongs === 'boolean') { + this.responseOptions.promoteLongs = _options.promoteLongs; + this.responseOptions.promoteValues = _options.promoteValues; + this.responseOptions.promoteBuffers = _options.promoteBuffers; + } + + const _errorHandler = errorHandler(this); + + if (this.family !== void 0) { + return doConnect(this, this.family, _options, _errorHandler); + } + + return doConnect(this, 6, _options, err => { + if (this.logger.isDebug()) { + this.logger.debug( + f( + 'connection %s for [%s:%s] errored out with [%s]', + this.id, + this.host, + this.port, + JSON.stringify(err) + ) + ); + } + + // clean up existing event handlers + this.connection.removeAllListeners('error'); + this.connection.removeAllListeners('timeout'); + this.connection.removeAllListeners('close'); + this.connection.removeAllListeners('data'); + this.connection = undefined; + + return doConnect(this, 4, _options, _errorHandler); + }); +}; + +/** + * Unref this connection + * @method + * @return {boolean} + */ +Connection.prototype.unref = function() { + if (this.connection) this.connection.unref(); + else { + var self = this; + this.once('connect', function() { + self.connection.unref(); + }); + } +}; + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + // Set the connections + if (connectionAccounting) deleteConnection(this.id); + if (this.connection) { + // Catch posssible exception thrown by node 0.10.x + try { + this.connection.end(); + } catch (err) {} // eslint-disable-line + // Destroy connection + this.connection.destroy(); + } + + this.destroyed = true; +}; + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + var i; + // Debug Log + if (this.logger.isDebug()) { + if (!Array.isArray(buffer)) { + this.logger.debug( + f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port) + ); + } else { + for (i = 0; i < buffer.length; i++) + this.logger.debug( + f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port) + ); + } + } + + // Double check that the connection is not destroyed + if (this.connection.destroyed === false) { + // Write out the command + if (!Array.isArray(buffer)) { + this.connection.write(buffer, 'binary'); + return true; + } + + // Iterate over all buffers and write them in order to the socket + for (i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); + return true; + } + + // Connection is destroyed return write failed + return false; +}; + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return '' + this.id; +}; + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return { id: this.id, host: this.host, port: this.port }; +}; + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if (this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/logger.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..eb11e43 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,246 @@ +'use strict'; + +var f = require('util').format, + MongoError = require('../error').MongoError; + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if (!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + this.className = className; + + // Current logger + if (options.logger) { + currentLogger = options.logger; + } else if (currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if (filteredClasses[this.className] == null) classFilters[this.className] = true; +}; + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}; + +/** + * Log a message at the warn level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +(Logger.prototype.warn = function(message, object) { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + var state = { + type: 'warn', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}), + /** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.info = function(message, object) { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.error = function(message, object) { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Is the logger set at info level + * @method + * @return {boolean} + */ + (Logger.prototype.isInfo = function() { + return level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isError = function() { + return level === 'error' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isWarn = function() { + return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at debug level + * @method + * @return {boolean} + */ + (Logger.prototype.isDebug = function() { + return level === 'debug'; + }); + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +}; + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +}; + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); + currentLogger = logger; +}; + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +}; + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { + throw new Error(f('%s is an illegal logging level', _level)); + } + + level = _level; +}; + +module.exports = Logger; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..02458be --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,1657 @@ +'use strict'; + +const inherits = require('util').inherits; +const EventEmitter = require('events').EventEmitter; +const Connection = require('./connection'); +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const MongoWriteConcernError = require('../error').MongoWriteConcernError; +const Logger = require('./logger'); +const f = require('util').format; +const Query = require('./commands').Query; +const CommandResult = require('./command_result'); +const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; +const opcodes = require('../wireprotocol/shared').opcodes; +const compress = require('../wireprotocol/compression').compress; +const compressorIDs = require('../wireprotocol/compression').compressorIDs; +const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; +const resolveClusterTime = require('../topologies/shared').resolveClusterTime; +const apm = require('./apm'); +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; +const Buffer = require('safe-buffer').Buffer; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +function hasSessionSupport(topology) { + if (topology == null) return false; + return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; +} + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Max server connection pool size + * @param {number} [options.minSize=0] Minimum server connection pool size + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(topology, options) { + // Add event listener + EventEmitter.call(this); + + // Store topology for later use + this.topology = topology; + + // Add the options + this.options = Object.assign( + { + // Host and port settings + host: 'localhost', + port: 27017, + // Pool default max size + size: 5, + // Pool default min size + minSize: 0, + // socket settings + connectionTimeout: 30000, + socketTimeout: 360000, + keepAlive: true, + keepAliveInitialDelay: 300000, + noDelay: true, + // SSL Settings + ssl: false, + checkServerIdentity: true, + ca: null, + crl: null, + cert: null, + key: null, + passPhrase: null, + rejectUnauthorized: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + // Reconnection options + reconnect: true, + reconnectInterval: 1000, + reconnectTries: 30, + // Enable domains + domainsEnabled: false + }, + options + ); + + // Identification information + this.id = _id++; + // Current reconnect retries + this.retriesLeft = this.options.reconnectTries; + this.reconnectId = null; + // No bson parser passed in + if ( + !options.bson || + (options.bson && + (typeof options.bson.serialize !== 'function' || + typeof options.bson.deserialize !== 'function')) + ) { + throw new Error('must pass in valid bson parser'); + } + + // Logger instance + this.logger = Logger('Pool', options); + // Pool state + this.state = DISCONNECTED; + // Connections + this.availableConnections = []; + this.inUseConnections = []; + this.connectingConnections = []; + // Currently executing + this.executing = false; + // Operation work queue + this.queue = []; + + // All the authProviders + this.authProviders = options.authProviders || defaultAuthProviders(options.bson); + + // Contains the reconnect connection + this.reconnectConnection = null; + + // Are we currently authenticating + this.authenticating = false; + this.loggingout = false; + this.nonAuthenticatedConnections = []; + this.authenticatingTimestamp = null; + // Number of consecutive timeouts caught + this.numberOfConsecutiveTimeouts = 0; + // Current pool Index + this.connectionIndex = 0; +}; + +inherits(Pool, EventEmitter); + +Object.defineProperty(Pool.prototype, 'size', { + enumerable: true, + get: function() { + return this.options.size; + } +}); + +Object.defineProperty(Pool.prototype, 'minSize', { + enumerable: true, + get: function() { + return this.options.minSize; + } +}); + +Object.defineProperty(Pool.prototype, 'connectionTimeout', { + enumerable: true, + get: function() { + return this.options.connectionTimeout; + } +}); + +Object.defineProperty(Pool.prototype, 'socketTimeout', { + enumerable: true, + get: function() { + return this.options.socketTimeout; + } +}); + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING], + destroying: [DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.emit('stateChanged', self.state, newState); + self.state = newState; + } else { + self.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +function authenticate(pool, auth, connection, cb) { + if (auth[0] === undefined) return cb(null); + // We need to authenticate the server + var mechanism = auth[0]; + var db = auth[1]; + // Validate if the mechanism exists + if (!pool.authProviders[mechanism]) { + throw new MongoError(f('authMechanism %s not supported', mechanism)); + } + + // Get the provider + var provider = pool.authProviders[mechanism]; + + // Authenticate using the provided mechanism + provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb])); +} + +// The write function used by the authentication mechanism (bypasses external) +function write(self) { + return function(connection, command, callback) { + // Get the raw buffer + // Ensure we stop auth if pool was destroyed + if (self.state === DESTROYED || self.state === DESTROYING) { + return callback(new MongoError('pool destroyed')); + } + + // Set the connection workItem callback + connection.workItems.push({ + cb: callback, + command: true, + requestId: command.requestId + }); + + // Write the buffer out to the connection + connection.write(command.toBin()); + }; +} + +function reauthenticate(pool, connection, cb) { + // Authenticate + function authenticateAgainstProvider(pool, connection, providers, cb) { + // Finished re-authenticating against providers + if (providers.length === 0) return cb(); + // Get the provider name + var provider = pool.authProviders[providers.pop()]; + + // Auth provider + provider.reauthenticate(write(pool), [connection], function(err) { + // We got an error return immediately + if (err) return cb(err); + // Continue authenticating the connection + authenticateAgainstProvider(pool, connection, providers, cb); + }); + } + + // Start re-authenticating process + authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb); +} + +function connectionFailureHandler(self, event) { + return function(err) { + if (this._connectionFailHandled) return; + this._connectionFailHandled = true; + // Destroy the connection + this.destroy(); + + // Remove the connection + removeConnection(self, this); + + // Flush all work Items on this connection + while (this.workItems.length > 0) { + var workItem = this.workItems.shift(); + if (workItem.cb) workItem.cb(err); + } + + // Did we catch a timeout, increment the numberOfConsecutiveTimeouts + if (event === 'timeout') { + self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1; + + // Have we timed out more than reconnectTries in a row ? + // Force close the pool as we are trying to connect to tcp sink hole + if (self.numberOfConsecutiveTimeouts > self.options.reconnectTries) { + self.numberOfConsecutiveTimeouts = 0; + // Destroy all connections and pool + self.destroy(true); + // Emit close event + return self.emit('close', self); + } + } + + // No more socket available propegate the event + if (self.socketCount() === 0) { + if (self.state !== DESTROYED && self.state !== DESTROYING) { + stateTransition(self, DISCONNECTED); + } + + // Do not emit error events, they are always close events + // do not trigger the low level error handler in node + event = event === 'error' ? 'close' : event; + self.emit(event, err); + } + + // Start reconnection attempts + if (!self.reconnectId && self.options.reconnect) { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + + // Do we need to do anything to maintain the minimum pool size + const totalConnections = + self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length; + + if (totalConnections < self.minSize) { + _createConnection(self); + } + }; +} + +function attemptReconnect(self) { + return function() { + self.emit('attemptReconnect', self); + if (self.state === DESTROYED || self.state === DESTROYING) return; + + // We are connected do not try again + if (self.isConnected()) { + self.reconnectId = null; + return; + } + + // If we have failure schedule a retry + function _connectionFailureHandler(self) { + return function() { + if (this._connectionFailHandled) return; + this._connectionFailHandled = true; + // Destroy the connection + this.destroy(); + // Count down the number of reconnects + self.retriesLeft = self.retriesLeft - 1; + // How many retries are left + if (self.retriesLeft <= 0) { + // Destroy the instance + self.destroy(); + // Emit close event + self.emit( + 'reconnectFailed', + new MongoNetworkError( + f( + 'failed to reconnect after %s attempts with interval %s ms', + self.options.reconnectTries, + self.options.reconnectInterval + ) + ) + ); + } else { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + }; + } + + // Got a connect handler + function _connectHandler(self) { + return function() { + // Assign + var connection = this; + + // Pool destroyed stop the connection + if (self.state === DESTROYED || self.state === DESTROYING) { + return connection.destroy(); + } + + // Clear out all handlers + handlers.forEach(function(event) { + connection.removeAllListeners(event); + }); + + // Reset reconnect id + self.reconnectId = null; + + // Apply pool connection handlers + connection.on('error', connectionFailureHandler(self, 'error')); + connection.on('close', connectionFailureHandler(self, 'close')); + connection.on('timeout', connectionFailureHandler(self, 'timeout')); + connection.on('parseError', connectionFailureHandler(self, 'parseError')); + + // Apply any auth to the connection + reauthenticate(self, this, function() { + // Reset retries + self.retriesLeft = self.options.reconnectTries; + // Push to available connections + self.availableConnections.push(connection); + // Set the reconnectConnection to null + self.reconnectConnection = null; + // Emit reconnect event + self.emit('reconnect', self); + // Trigger execute to start everything up again + _execute(self)(); + }); + }; + } + + // Create a connection + self.reconnectConnection = new Connection(messageHandler(self), self.options); + // Add handlers + self.reconnectConnection.on('close', _connectionFailureHandler(self, 'close')); + self.reconnectConnection.on('error', _connectionFailureHandler(self, 'error')); + self.reconnectConnection.on('timeout', _connectionFailureHandler(self, 'timeout')); + self.reconnectConnection.on('parseError', _connectionFailureHandler(self, 'parseError')); + // On connection + self.reconnectConnection.on('connect', _connectHandler(self)); + // Attempt connection + self.reconnectConnection.connect(); + }; +} + +function moveConnectionBetween(connection, from, to) { + var index = from.indexOf(connection); + // Move the connection from connecting to available + if (index !== -1) { + from.splice(index, 1); + to.push(connection); + } +} + +function messageHandler(self) { + return function(message, connection) { + // workItem to execute + var workItem = null; + + // Locate the workItem + for (var i = 0; i < connection.workItems.length; i++) { + if (connection.workItems[i].requestId === message.responseTo) { + // Get the callback + workItem = connection.workItems[i]; + // Remove from list of workItems + connection.workItems.splice(i, 1); + } + } + + // Reset timeout counter + self.numberOfConsecutiveTimeouts = 0; + + // Reset the connection timeout if we modified it for + // this operation + if (workItem && workItem.socketTimeout) { + connection.resetSocketTimeout(); + } + + // Log if debug enabled + if (self.logger.isDebug()) { + self.logger.debug( + f( + 'message [%s] received from %s:%s', + message.raw.toString('hex'), + self.options.host, + self.options.port + ) + ); + } + + // Authenticate any straggler connections + function authenticateStragglers(self, connection, callback) { + // Get any non authenticated connections + var connections = self.nonAuthenticatedConnections.slice(0); + var nonAuthenticatedConnections = self.nonAuthenticatedConnections; + self.nonAuthenticatedConnections = []; + + // Establish if the connection need to be authenticated + // Add to authentication list if + // 1. we were in an authentication process when the operation was executed + // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened + if ( + connection.workItems.length === 1 && + (connection.workItems[0].authenticating === true || + (typeof connection.workItems[0].authenticatingTimestamp === 'number' && + connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) + ) { + // Add connection to the list + connections.push(connection); + } + + // No connections need to be re-authenticated + if (connections.length === 0) { + // Release the connection back to the pool + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + // Finish + return callback(); + } + + // Apply re-authentication to all connections before releasing back to pool + var connectionCount = connections.length; + // Authenticate all connections + for (var i = 0; i < connectionCount; i++) { + reauthenticate(self, connections[i], function() { + connectionCount = connectionCount - 1; + + if (connectionCount === 0) { + // Put non authenticated connections in available connections + self.availableConnections = self.availableConnections.concat( + nonAuthenticatedConnections + ); + // Release the connection back to the pool + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + // Return + callback(); + } + }); + } + } + + function handleOperationCallback(self, cb, err, result) { + // No domain enabled + if (!self.options.domainsEnabled) { + return process.nextTick(function() { + return cb(err, result); + }); + } + + // Domain enabled just call the callback + cb(err, result); + } + + authenticateStragglers(self, connection, function() { + // Keep executing, ensure current message handler does not stop execution + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + + // Time to dispatch the message if we have a callback + if (workItem && !workItem.immediateRelease) { + try { + // Parse the message according to the provided options + message.parse(workItem); + } catch (err) { + return handleOperationCallback(self, workItem.cb, new MongoError(err)); + } + + // Look for clusterTime, and operationTime and update them if necessary + if (message.documents[0]) { + if (message.documents[0].$clusterTime) { + const $clusterTime = message.documents[0].$clusterTime; + self.topology.clusterTime = $clusterTime; + + if (workItem.session != null) { + resolveClusterTime(workItem.session, $clusterTime); + } + } + + if ( + message.documents[0].operationTime && + workItem.session && + workItem.session.supports.causalConsistency + ) { + workItem.session.advanceOperationTime(message.documents[0].operationTime); + } + } + + // Establish if we have an error + if (workItem.command && message.documents[0]) { + const responseDoc = message.documents[0]; + if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { + return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); + } + + if (responseDoc.writeConcernError) { + const err = + responseDoc.ok === 1 + ? new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc) + : new MongoWriteConcernError(responseDoc.writeConcernError); + return handleOperationCallback(self, workItem.cb, err); + } + } + + // Add the connection details + message.hashedName = connection.hashedName; + + // Return the documents + handleOperationCallback( + self, + workItem.cb, + null, + new CommandResult( + workItem.fullResult ? message : message.documents[0], + connection, + message + ) + ); + } + }); + }; +} + +/** + * Return the total socket count in the pool. + * @method + * @return {Number} The number of socket available. + */ +Pool.prototype.socketCount = function() { + return this.availableConnections.length + this.inUseConnections.length; + // + this.connectingConnections.length; +}; + +/** + * Return all pool connections + * @method + * @return {Connection[]} The pool connections + */ +Pool.prototype.allConnections = function() { + return this.availableConnections.concat(this.inUseConnections).concat(this.connectingConnections); +}; + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + return this.allConnections()[0]; +}; + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // We are in a destroyed state + if (this.state === DESTROYED || this.state === DESTROYING) { + return false; + } + + // Get connections + var connections = this.availableConnections.concat(this.inUseConnections); + + // Check if we have any connected connections + for (var i = 0; i < connections.length; i++) { + if (connections[i].isConnected()) return true; + } + + // Might be authenticating, but we are still connected + if (connections.length === 0 && this.authenticating) { + return true; + } + + // Not connected + return false; +}; + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state === DESTROYED || this.state === DESTROYING; +}; + +/** + * Is the pool in a disconnected state + * @method + * @return {boolean} + */ +Pool.prototype.isDisconnected = function() { + return this.state === DISCONNECTED; +}; + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function() { + if (this.state !== DISCONNECTED) { + throw new MongoError('connection in unlawful state ' + this.state); + } + + var self = this; + // Transition to connecting state + stateTransition(this, CONNECTING); + // Create an array of the arguments + var args = Array.prototype.slice.call(arguments, 0); + // Create a connection + var connection = new Connection(messageHandler(self), this.options); + // Add to list of connections + this.connectingConnections.push(connection); + // Add listeners to the connection + connection.once('connect', function(connection) { + if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); + + // If we are in a topology, delegate the auth to it + // This is to avoid issues where we would auth against an + // arbiter + if (self.options.inTopology) { + // Set connected mode + stateTransition(self, CONNECTED); + + // Move the active connection + moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); + + // Emit the connect event + return self.emit('connect', self); + } + + // Apply any store credentials + reauthenticate(self, connection, function(err) { + if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); + + // We have an error emit it + if (err) { + // Destroy the pool + self.destroy(); + // Emit the error + return self.emit('error', err); + } + + // Authenticate + authenticate(self, args, connection, function(err) { + if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); + + // We have an error emit it + if (err) { + // Destroy the pool + self.destroy(); + // Emit the error + return self.emit('error', err); + } + // Set connected mode + stateTransition(self, CONNECTED); + + // Move the active connection + moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); + + // if we have a minPoolSize, create a connection + if (self.minSize) { + for (let i = 0; i < self.minSize; i++) _createConnection(self); + } + + // Emit the connect event + self.emit('connect', self); + }); + }); + }); + + // Add error handlers + connection.once('error', connectionFailureHandler(this, 'error')); + connection.once('close', connectionFailureHandler(this, 'close')); + connection.once('timeout', connectionFailureHandler(this, 'timeout')); + connection.once('parseError', connectionFailureHandler(this, 'parseError')); + + try { + connection.connect(); + } catch (err) { + // SSL or something threw on connect + process.nextTick(function() { + self.emit('error', err); + }); + } +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.auth = function(mechanism) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + + // If we don't have the mechanism fail + if (self.authProviders[mechanism] == null && mechanism !== 'default') { + throw new MongoError(f('auth provider %s does not exist', mechanism)); + } + + // Signal that we are authenticating a new set of credentials + this.authenticating = true; + this.authenticatingTimestamp = new Date().getTime(); + + // Authenticate all live connections + function authenticateLiveConnections(self, args, cb) { + // Get the current viable connections + var connections = self.allConnections(); + // Allow nothing else to use the connections while we authenticate them + self.availableConnections = []; + self.inUseConnections = []; + self.connectingConnections = []; + + var connectionsCount = connections.length; + var error = null; + // No connections available, return + if (connectionsCount === 0) { + self.authenticating = false; + return callback(null); + } + + // Authenticate the connections + for (var i = 0; i < connections.length; i++) { + authenticate(self, args, connections[i], function(err, result) { + connectionsCount = connectionsCount - 1; + + // Store the error + if (err) error = err; + + // Processed all connections + if (connectionsCount === 0) { + // Auth finished + self.authenticating = false; + // Add the connections back to available connections + self.availableConnections = self.availableConnections.concat(connections); + // We had an error, return it + if (error) { + // Log the error + if (self.logger.isError()) { + self.logger.error( + f( + '[%s] failed to authenticate against server %s:%s', + self.id, + self.options.host, + self.options.port + ) + ); + } + + return cb(error, result); + } + cb(null, result); + } + }); + } + } + + // Wait for a logout in process to happen + function waitForLogout(self, cb) { + if (!self.loggingout) return cb(); + setTimeout(function() { + waitForLogout(self, cb); + }, 1); + } + + // Wait for loggout to finish + waitForLogout(self, function() { + // Authenticate all live connections + authenticateLiveConnections(self, args, function(err, result) { + // Credentials correctly stored in auth provider if successful + // Any new connections will now reauthenticate correctly + self.authenticating = false; + // Return after authentication connections + callback(err, result); + }); + }); +}; + +/** + * Logout all users against a database + * @method + * @param {string} dbName The database name + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.logout = function(dbName, callback) { + var self = this; + if (typeof dbName !== 'string') { + throw new MongoError('logout method requires a db name as first argument'); + } + + if (typeof callback !== 'function') { + throw new MongoError('logout method requires a callback'); + } + + // Indicate logout in process + this.loggingout = true; + + // Get all relevant connections + var connections = self.availableConnections.concat(self.inUseConnections); + var count = connections.length; + // Store any error + var error = null; + + // Send logout command over all the connections + for (var i = 0; i < connections.length; i++) { + write(self)( + connections[i], + new Query( + this.options.bson, + f('%s.$cmd', dbName), + { logout: 1 }, + { numberToSkip: 0, numberToReturn: 1 } + ), + function(err) { + count = count - 1; + if (err) error = err; + + if (count === 0) { + self.loggingout = false; + callback(error); + } + } + ); + } +}; + +/** + * Unref the pool + * @method + */ +Pool.prototype.unref = function() { + // Get all the known connections + var connections = this.availableConnections + .concat(this.inUseConnections) + .concat(this.connectingConnections); + connections.forEach(function(c) { + c.unref(); + }); +}; + +// Events +var events = ['error', 'close', 'timeout', 'parseError', 'connect']; + +// Destroy the connections +function destroy(self, connections) { + // Destroy all connections + connections.forEach(function(c) { + // Remove all listeners + for (var i = 0; i < events.length; i++) { + c.removeAllListeners(events[i]); + } + // Destroy connection + c.destroy(); + }); + + // Zero out all connections + self.inUseConnections = []; + self.availableConnections = []; + self.nonAuthenticatedConnections = []; + self.connectingConnections = []; + + // Set state to destroyed + stateTransition(self, DESTROYED); +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function(force) { + var self = this; + // Do not try again if the pool is already dead + if (this.state === DESTROYED || self.state === DESTROYING) return; + // Set state to destroyed + stateTransition(this, DESTROYING); + + // Are we force closing + if (force) { + // Get all the known connections + var connections = self.availableConnections + .concat(self.inUseConnections) + .concat(self.nonAuthenticatedConnections) + .concat(self.connectingConnections); + + // Flush any remaining work items with + // an error + while (self.queue.length > 0) { + var workItem = self.queue.shift(); + if (typeof workItem.cb === 'function') { + workItem.cb(new MongoError('Pool was force destroyed')); + } + } + + // Destroy the topology + return destroy(self, connections); + } + + // Clear out the reconnect if set + if (this.reconnectId) { + clearTimeout(this.reconnectId); + } + + // If we have a reconnect connection running, close + // immediately + if (this.reconnectConnection) { + this.reconnectConnection.destroy(); + } + + // Wait for the operations to drain before we close the pool + function checkStatus() { + flushMonitoringOperations(self.queue); + + if (self.queue.length === 0) { + // Get all the known connections + var connections = self.availableConnections + .concat(self.inUseConnections) + .concat(self.nonAuthenticatedConnections) + .concat(self.connectingConnections); + + // Check if we have any in flight operations + for (var i = 0; i < connections.length; i++) { + // There is an operation still in flight, reschedule a + // check waiting for it to drain + if (connections[i].workItems.length > 0) { + return setTimeout(checkStatus, 1); + } + } + + destroy(self, connections); + // } else if (self.queue.length > 0 && !this.reconnectId) { + } else { + // Ensure we empty the queue + _execute(self)(); + // Set timeout + setTimeout(checkStatus, 1); + } + } + + // Initiate drain of operations + checkStatus(); +}; + +// Prepare the buffer that Pool.prototype.write() uses to send to the server +var serializeCommands = function(self, commands, result, callback) { + // Base case when there are no more commands to serialize + if (commands.length === 0) return callback(null, result); + + // Pop off the zeroth command and serialize it + var thisCommand = commands.shift(); + var originalCommandBuffer = thisCommand.toBin(); + + // Check whether we and the server have agreed to use a compressor + if (self.options.agreedCompressor && !hasUncompressibleCommands(thisCommand)) { + // Transform originalCommandBuffer into OP_COMPRESSED + var concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); + var messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + var originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress(self, messageToBeCompressed, function(err, compressedMessage) { + if (err) return callback(err, null); + + // Create the msgHeader of OP_COMPRESSED + var msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + 9 + compressedMessage.length, 0); // messageLength + msgHeader.writeInt32LE(thisCommand.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + var compressionDetails = Buffer.alloc(9); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID + + // Push the concatenation of the OP_COMPRESSED message onto results + result.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + + // Continue recursing through the commands array + serializeCommands(self, commands, result, callback); + }); + } else { + // Push the serialization of the command onto results + result.push(originalCommandBuffer); + + // Continue recursing through the commands array + serializeCommands(self, commands, result, callback); + } +}; + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(commands, options, cb) { + var self = this; + // Ensure we have a callback + if (typeof options === 'function') { + cb = options; + } + + // Always have options + options = options || {}; + + // We need to have a callback function unless the message returns no response + if (!(typeof cb === 'function') && !options.noResponse) { + throw new MongoError('write method must provide a callback'); + } + + // Pool was destroyed error out + if (this.state === DESTROYED || this.state === DESTROYING) { + // Callback with an error + if (cb) { + try { + cb(new MongoError('pool destroyed')); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + } + + return; + } + + if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { + // if we have a domain bind to it + var oldCb = cb; + cb = process.domain.bind(function() { + // v8 - argumentsToArray one-liner + var args = new Array(arguments.length); + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + // bounce off event loop so domain switch takes place + process.nextTick(function() { + oldCb.apply(null, args); + }); + }); + } + + // Do we have an operation + var operation = { + cb: cb, + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + fullResult: false + }; + + // Set the options for the parsing + operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; + operation.promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : true; + operation.promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; + operation.raw = typeof options.raw === 'boolean' ? options.raw : false; + operation.immediateRelease = + typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; + operation.documentsReturnedIn = options.documentsReturnedIn; + operation.command = typeof options.command === 'boolean' ? options.command : false; + operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; + operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; + operation.session = options.session || null; + + // Optional per operation socketTimeout + operation.socketTimeout = options.socketTimeout; + operation.monitoring = options.monitoring; + // Custom socket Timeout + if (options.socketTimeout) { + operation.socketTimeout = options.socketTimeout; + } + + // Ensure commands is an array + if (!Array.isArray(commands)) { + commands = [commands]; + } + + // Get the requestId + operation.requestId = commands[commands.length - 1].requestId; + + if (hasSessionSupport(this.topology)) { + let sessionOptions = {}; + if (this.topology.clusterTime) { + sessionOptions = { $clusterTime: this.topology.clusterTime }; + } + + if (operation.session) { + // TODO: reenable when sessions development is complete + // if (operation.session.topology !== this.topology) { + // return cb( + // new MongoError('Sessions may only be used with the client they were created from') + // ); + // } + + if (operation.session.hasEnded) { + return cb(new MongoError('Use of expired sessions is not permitted')); + } + + if ( + operation.session.clusterTime && + operation.session.clusterTime.clusterTime.greaterThan( + sessionOptions.$clusterTime.clusterTime + ) + ) { + sessionOptions.$clusterTime = operation.session.clusterTime; + } + + sessionOptions.lsid = operation.session.id; + + // update the `lastUse` of the acquired ServerSession + operation.session.serverSession.lastUse = Date.now(); + } + + // decorate the commands with session-specific details + commands.forEach(command => { + if (command instanceof Query) { + if (command.query.$query) { + Object.assign(command.query.$query, sessionOptions); + } else { + Object.assign(command.query, sessionOptions); + } + } else { + Object.assign(command, sessionOptions); + } + }); + } + + // If command monitoring is enabled we need to modify the callback here + if (self.options.monitorCommands) { + // NOTE: there is only ever a single command, for some legacy reason I am unaware of we + // treat this as a potential array of commands + const command = commands[0]; + this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); + + operation.started = process.hrtime(); + operation.cb = (err, reply) => { + if (err) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, err, operation.started) + ); + } else { + if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, reply.result, operation.started) + ); + } else { + self.emit( + 'commandSucceeded', + new apm.CommandSucceededEvent(this, command, reply, operation.started) + ); + } + } + + if (typeof cb === 'function') cb(err, reply); + }; + } + + // Prepare the operation buffer + serializeCommands(self, commands, [], function(err, serializedCommands) { + if (err) throw err; + + // Set the operation's buffer to the serialization of the commands + operation.buffer = serializedCommands; + + // If we have a monitoring operation schedule as the very first operation + // Otherwise add to back of queue + if (options.monitoring) { + self.queue.unshift(operation); + } else { + self.queue.push(operation); + } + + // Attempt to execute the operation + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + }); +}; + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +var hasUncompressibleCommands = function(command) { + return uncompressibleCommands.some(function(cmd) { + return command.query.hasOwnProperty(cmd); + }); +}; + +// Remove connection method +function remove(connection, connections) { + for (var i = 0; i < connections.length; i++) { + if (connections[i] === connection) { + connections.splice(i, 1); + return true; + } + } +} + +function removeConnection(self, connection) { + if (remove(connection, self.availableConnections)) return; + if (remove(connection, self.inUseConnections)) return; + if (remove(connection, self.connectingConnections)) return; + if (remove(connection, self.nonAuthenticatedConnections)) return; +} + +// All event handlers +var handlers = ['close', 'message', 'error', 'timeout', 'parseError', 'connect']; + +function _createConnection(self) { + if (self.state === DESTROYED || self.state === DESTROYING) { + return; + } + var connection = new Connection(messageHandler(self), self.options); + + // Push the connection + self.connectingConnections.push(connection); + + // Handle any errors + var tempErrorHandler = function(_connection) { + return function() { + // Destroy the connection + _connection.destroy(); + // Remove the connection from the connectingConnections list + removeConnection(self, _connection); + // Start reconnection attempts + if (!self.reconnectId && self.options.reconnect) { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + }; + }; + + // Handle successful connection + var tempConnectHandler = function(_connection) { + return function() { + // Destroyed state return + if (self.state === DESTROYED || self.state === DESTROYING) { + // Remove the connection from the list + removeConnection(self, _connection); + return _connection.destroy(); + } + + // Destroy all event emitters + handlers.forEach(function(e) { + _connection.removeAllListeners(e); + }); + + // Add the final handlers + _connection.once('close', connectionFailureHandler(self, 'close')); + _connection.once('error', connectionFailureHandler(self, 'error')); + _connection.once('timeout', connectionFailureHandler(self, 'timeout')); + _connection.once('parseError', connectionFailureHandler(self, 'parseError')); + + // Signal + reauthenticate(self, _connection, function(err) { + if (self.state === DESTROYED || self.state === DESTROYING) { + return _connection.destroy(); + } + // Remove the connection from the connectingConnections list + removeConnection(self, _connection); + + // Handle error + if (err) { + return _connection.destroy(); + } + + // If we are c at the moment + // Do not automatially put in available connections + // As we need to apply the credentials first + if (self.authenticating) { + self.nonAuthenticatedConnections.push(_connection); + } else { + // Push to available + self.availableConnections.push(_connection); + // Execute any work waiting + _execute(self)(); + } + }); + }; + }; + + // Add all handlers + connection.once('close', tempErrorHandler(connection)); + connection.once('error', tempErrorHandler(connection)); + connection.once('timeout', tempErrorHandler(connection)); + connection.once('parseError', tempErrorHandler(connection)); + connection.once('connect', tempConnectHandler(connection)); + + // Start connection + connection.connect(); +} + +function flushMonitoringOperations(queue) { + for (var i = 0; i < queue.length; i++) { + if (queue[i].monitoring) { + var workItem = queue[i]; + queue.splice(i, 1); + workItem.cb( + new MongoError({ message: 'no connection available for monitoring', driver: true }) + ); + } + } +} + +function _execute(self) { + return function() { + if (self.state === DESTROYED) return; + // Already executing, skip + if (self.executing) return; + // Set pool as executing + self.executing = true; + + // Wait for auth to clear before continuing + function waitForAuth(cb) { + if (!self.authenticating) return cb(); + // Wait for a milisecond and try again + setTimeout(function() { + waitForAuth(cb); + }, 1); + } + + // Block on any auth in process + waitForAuth(function() { + // New pool connections are in progress, wait them to finish + // before executing any more operation to ensure distribution of + // operations + if (self.connectingConnections.length > 0) { + return; + } + + // As long as we have available connections + // eslint-disable-next-line + while (true) { + // Total availble connections + var totalConnections = + self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length; + + // No available connections available, flush any monitoring ops + if (self.availableConnections.length === 0) { + // Flush any monitoring operations + flushMonitoringOperations(self.queue); + break; + } + + // No queue break + if (self.queue.length === 0) { + break; + } + + // Get a connection + var connection = null; + + // Locate all connections that have no work + var connections = []; + // Get a list of all connections + for (var i = 0; i < self.availableConnections.length; i++) { + if (self.availableConnections[i].workItems.length === 0) { + connections.push(self.availableConnections[i]); + } + } + + // No connection found that has no work on it, just pick one for pipelining + if (connections.length === 0) { + connection = + self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + } else { + connection = connections[self.connectionIndex++ % connections.length]; + } + + // Is the connection connected + if (connection.isConnected()) { + // Get the next work item + var workItem = self.queue.shift(); + + // If we are monitoring we need to use a connection that is not + // running another operation to avoid socket timeout changes + // affecting an existing operation + if (workItem.monitoring) { + var foundValidConnection = false; + + for (i = 0; i < self.availableConnections.length; i++) { + // If the connection is connected + // And there are no pending workItems on it + // Then we can safely use it for monitoring. + if ( + self.availableConnections[i].isConnected() && + self.availableConnections[i].workItems.length === 0 + ) { + foundValidConnection = true; + connection = self.availableConnections[i]; + break; + } + } + + // No safe connection found, attempt to grow the connections + // if possible and break from the loop + if (!foundValidConnection) { + // Put workItem back on the queue + self.queue.unshift(workItem); + + // Attempt to grow the pool if it's not yet maxsize + if (totalConnections < self.options.size && self.queue.length > 0) { + // Create a new connection + _createConnection(self); + } + + // Re-execute the operation + setTimeout(function() { + _execute(self)(); + }, 10); + + break; + } + } + + // Don't execute operation until we have a full pool + if (totalConnections < self.options.size) { + // Connection has work items, then put it back on the queue + // and create a new connection + if (connection.workItems.length > 0) { + // Lets put the workItem back on the list + self.queue.unshift(workItem); + // Create a new connection + _createConnection(self); + // Break from the loop + break; + } + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // Set current status of authentication process + workItem.authenticating = self.authenticating; + workItem.authenticatingTimestamp = self.authenticatingTimestamp; + + // If we are monitoring take the connection of the availableConnections + if (workItem.monitoring) { + moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); + } + + // Track the executing commands on the mongo server + // as long as there is an expected response + if (!workItem.noResponse) { + connection.workItems.push(workItem); + } + + // We have a custom socketTimeout + if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { + connection.setSocketTimeout(workItem.socketTimeout); + } + + // Capture if write was successful + var writeSuccessful = true; + + // Put operation on the wire + if (Array.isArray(buffer)) { + for (i = 0; i < buffer.length; i++) { + writeSuccessful = connection.write(buffer[i]); + } + } else { + writeSuccessful = connection.write(buffer); + } + + // if the command is designated noResponse, call the callback immeditely + if (workItem.noResponse && typeof workItem.cb === 'function') { + workItem.cb(null, null); + } + + if (writeSuccessful && workItem.immediateRelease && self.authenticating) { + removeConnection(self, connection); + self.nonAuthenticatedConnections.push(connection); + } else if (writeSuccessful === false) { + // If write not successful put back on queue + self.queue.unshift(workItem); + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + } + } else { + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + } + } + }); + + self.executing = false; + }; +} + +// Make execution loop available for testing +Pool._execute = _execute; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * A server reconnect event, used to verify that pool reconnected. + * + * @event Pool#reconnect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +/** + * The driver attempted to reconnect + * + * @event Pool#attemptReconnect + * @type {Pool} + */ + +/** + * The driver exhausted all reconnect attempts + * + * @event Pool#reconnectFailed + * @type {Pool} + */ + +module.exports = Pool; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/connection/utils.js b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..e2d8dff --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,113 @@ +'use strict'; + +var f = require('util').format, + require_optional = require('require_optional'); + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable: true, + set: function(value) { + if (typeof value !== 'boolean') throw new Error(f('%s required a boolean', prop.name)); + // Flip the bit to 1 + if (value === true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if (value === false && (values.flags & flag) === flag) values.flags ^= flag; + prop.value = value; + }, + get: function() { + return prop.value; + } + }); +}; + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable: true, + get: function() { + // Not parsed yet, parse it + if (values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if (typeof func === 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for (var name in fObj) tObj[name] = fObj[name]; + return tObj; +}; + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var retrieveBSON = function() { + var BSON = require('bson'); + BSON.native = false; + + try { + var optionalBSON = require_optional('bson-ext'); + if (optionalBSON) { + optionalBSON.native = true; + return optionalBSON; + } + } catch (err) {} // eslint-disable-line + + return BSON; +}; + +// Throw an error if an attempt to use Snappy is made when Snappy is not installed +var noSnappyWarning = function() { + throw new Error( + 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' + ); +}; + +// Facilitate loading Snappy optionally +var retrieveSnappy = function() { + var snappy = null; + try { + snappy = require_optional('snappy'); + } catch (error) {} // eslint-disable-line + if (!snappy) { + snappy = { + compress: noSnappyWarning, + uncompress: noSnappyWarning, + compressSync: noSnappyWarning, + uncompressSync: noSnappyWarning + }; + } + return snappy; +}; + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.debugOptions = debugOptions; +exports.retrieveBSON = retrieveBSON; +exports.retrieveSnappy = retrieveSnappy; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js b/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..032fae6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,766 @@ +'use strict'; + +const Logger = require('./connection/logger'); +const retrieveBSON = require('./connection/utils').retrieveBSON; +const MongoError = require('./error').MongoError; +const MongoNetworkError = require('./error').MongoNetworkError; +const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; +const f = require('util').format; +const collationNotSupported = require('./utils').collationNotSupported; + +const BSON = retrieveBSON(); +const Long = BSON.Long; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null, + cmd: cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms, + raw: options.raw || (cmd && cmd.raw) + }; + + if (typeof options.session === 'object') { + this.cursorState.session = options.session; + } + + // Add promoteLong to cursor state + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.cursorState.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.cursorState.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.cursorState.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if (cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } +}; + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +}; + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +}; + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +}; + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +}; + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +}; + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +}; + +Cursor.prototype._endSession = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.cursorState.session; + + if (session && (options.force || session.owner === this)) { + this.cursorState.session = undefined; + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + return false; +}; + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +}; + +// Internal methods +Cursor.prototype._getmore = function(callback) { + if (this.logger.isDebug()) + this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query))); + + // Set the current batchSize + var batchSize = this.cursorState.batchSize; + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + batchSize > this.cursorState.limit + ) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + this.server.wireProtocolHandler.getMore( + this.server, + this.ns, + this.cursorState, + batchSize, + this.options, + callback + ); +}; + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +}; + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead === true; +}; + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed === true; +}; + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified === true; +}; + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +}; + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice( + this.cursorState.cursorIndex, + this.cursorState.cursorIndex + length + ); + + // Transform the doc with passed in transformation method if provided + if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { + // Transform all the elements + for (var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + elements.length > this.cursorState.limit + ) { + elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +}; + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if ( + this.cursorState.cursorId == null || + this.cursorState.cursorId.isZero() || + this.cursorState.init === false + ) { + if (callback) callback(null, null); + return; + } + + this.server.wireProtocolHandler.killCursor(this.server, this.ns, this.cursorState, callback); +}; + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if (this.cursorState.init) { + if (!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +}; + +/** + * Validate if the pool is dead and return error + */ +var isConnectionDead = function(self, callback) { + if (self.pool && self.pool.isDestroyed()) { + self.cursorState.killed = true; + const err = new MongoNetworkError( + f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port) + ); + _setCursorNotifiedImpl(self, () => callback(err)); + return true; + } + + return false; +}; + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if (self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.killed = true; + setCursorNotified(self, callback); + return true; + } + + return false; +}; + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if (self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +}; + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if (self.cursorState.killed) { + setCursorNotified(self, callback); + return true; + } + + return false; +}; + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + setCursorNotified(self, callback); +}; + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); +}; + +var _setCursorNotifiedImpl = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + if (self._endSession) { + return self._endSession(undefined, () => callback()); + } + return callback(); +}; + +var nextFunction = function(self, callback) { + // We have notified about it + if (self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if (!self.cursorState.init) { + return initializeCursor(self, callback); + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if ( + self.cursorState.cursorIndex === self.cursorState.documents.length && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if (self.topology.isDestroyed()) + return callback( + new MongoNetworkError('connection destroyed, not possible to instantiate cursor') + ); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if (isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc, connection) { + if (err) { + if (err instanceof MongoError) { + err[mongoErrorContextSymbol].isGetMore = true; + } + + return handleCallback(callback, err); + } + + if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { + self._endSession(); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + self.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + return nextFunction(self, callback); + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + setCursorDeadAndNotified(self, callback); + } else { + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }); + } + + // Transform the doc with passed in transformation method if provided + if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +}; + +function initializeCursor(cursor, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!cursor.topology.isConnected(cursor.options)) { + // Only need this for single server, because repl sets and mongos + // will always continue trying to reconnect + if (cursor.topology._type === 'server' && !cursor.topology.s.options.reconnect) { + // Reconnect is disabled, so we'll never reconnect + return callback(new MongoError('no connection available')); + } + + if (cursor.disconnectHandler != null) { + if (cursor.topology.isDestroyed()) { + // Topology was destroyed, so don't try to wait for it to reconnect + return callback(new MongoError('Topology was destroyed')); + } + + return cursor.disconnectHandler.addObjectAndMethod( + 'cursor', + cursor, + 'next', + [callback], + callback + ); + } + } + + return cursor.topology.selectServer(cursor.options, (err, server) => { + if (err) { + const disconnectHandler = cursor.disconnectHandler; + if (disconnectHandler != null) { + return disconnectHandler.addObjectAndMethod('cursor', cursor, 'next', [callback], callback); + } + + return callback(err); + } + + cursor.server = server; + cursor.cursorState.init = true; + if (collationNotSupported(cursor.server, cursor.cmd)) { + return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + } + + function done() { + if ( + cursor.cursorState.cursorId && + cursor.cursorState.cursorId.isZero() && + cursor._endSession + ) { + cursor._endSession(); + } + + if ( + cursor.cursorState.documents.length === 0 && + cursor.cursorState.cursorId && + cursor.cursorState.cursorId.isZero() && + !cursor.cmd.tailable && + !cursor.cmd.awaitData + ) { + return setCursorNotified(cursor, callback); + } + + nextFunction(cursor, callback); + } + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + const queryCallback = (err, r) => { + if (err) return callback(err); + + const result = r.message; + if (result.queryFailure) { + return callback(new MongoError(result.documents[0]), null); + } + + // Check if we have a command cursor + if ( + Array.isArray(result.documents) && + result.documents.length === 1 && + (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && + (typeof result.documents[0].cursor !== 'string' || + result.documents[0]['$err'] || + result.documents[0]['errmsg'] || + Array.isArray(result.documents[0].result)) + ) { + // We have an error document, return the error + if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { + return callback(new MongoError(result.documents[0]), null); + } + + // We have a cursor document + if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if (result.documents[0].cursor.ns) { + cursor.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; + cursor.cursorState.operationTime = result.documents[0].operationTime; + // If we have a firstBatch set it + if (Array.isArray(result.documents[0].cursor.firstBatch)) { + cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); + } + + // Return after processing command cursor + return done(result); + } + + if (Array.isArray(result.documents[0].result)) { + cursor.cursorState.documents = result.documents[0].result; + cursor.cursorState.cursorId = Long.ZERO; + return done(result); + } + } + + // Otherwise fall back to regular find path + cursor.cursorState.cursorId = result.cursorId; + cursor.cursorState.documents = result.documents; + cursor.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if ( + cursor.cursorState.transforms && + typeof cursor.cursorState.transforms.query === 'function' + ) { + cursor.cursorState.documents = cursor.cursorState.transforms.query(result); + } + + // Return callback + done(result); + }; + + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + if (cursor.cmd.find != null) { + cursor.server.wireProtocolHandler.query( + cursor.server, + cursor.ns, + cursor.cmd, + cursor.cursorState, + cursor.options, + queryCallback + ); + + return; + } + + cursor.query = cursor.server.wireProtocolHandler.command( + cursor.server, + cursor.ns, + cursor.cmd, + cursor.options, + queryCallback + ); + }); +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +}; + +module.exports = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/error.js b/node_modules/mongoose/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..c0d707c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,146 @@ +'use strict'; + +const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); + +/** + * Creates a new MongoError + * + * @augments Error + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + this.stack = message.stack; + } else { + if (typeof message === 'string') { + super(message); + } else { + super(message.message || message.errmsg || message.$err || 'n/a'); + for (var name in message) { + this[name] = message[name]; + } + } + + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'MongoError'; + this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; + } + + /** + * Creates a new MongoError object + * + * @param {Error|string|object} options The options used to create the error. + * @return {MongoError} A MongoError instance + * @deprecated Use `new MongoError()` instead. + */ + static create(options) { + return new MongoError(options); + } +} + +/** + * Creates a new MongoNetworkError + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoNetworkError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoNetworkError'; + + // This is added as part of the transactions specification + this.errorLabels = ['TransientTransactionError']; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + */ +class MongoParseError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoParseError'; + } +} + +/** + * An error signifying a timeout event + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + */ +class MongoTimeoutError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoTimeoutError'; + } +} + +/** + * An error thrown when the server reports a writeConcernError + * + * @param {Error|string|object} message The error message + * @param {object} result The result document (provided if ok: 1) + * @property {string} message The error message + * @property {object} [result] The result document (provided if ok: 1) + */ +class MongoWriteConcernError extends MongoError { + constructor(message, result) { + super(message); + this.name = 'MongoWriteConcernError'; + + if (result != null) { + this.result = result; + } + } +} + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + 6, // HostUnreachable + 7, // HostNotFound + 89, // NetworkTimeout + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 9001, // SocketException + 10107, // NotMaster + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13435, // NotMasterNoSlaveOk + 13436 // NotMasterOrSecondary +]); + +/** + * Determines whether an error is something the driver should attempt to retry + * + * @param {MongoError|Error} error + */ +function isRetryableError(error) { + return ( + RETRYABLE_ERROR_CODES.has(error.code) || + error instanceof MongoNetworkError || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +module.exports = { + MongoError, + MongoNetworkError, + MongoParseError, + MongoTimeoutError, + MongoWriteConcernError, + mongoErrorContextSymbol, + isRetryableError +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/cursor.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/cursor.js new file mode 100644 index 0000000..f52d7b6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/cursor.js @@ -0,0 +1,749 @@ +'use strict'; + +const Logger = require('../connection/logger'); +const BSON = require('../connection/utils').retrieveBSON(); +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const mongoErrorContextSymbol = require('../error').mongoErrorContextSymbol; +const Long = BSON.Long; +const deprecate = require('util').deprecate; +const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; +const ReadPreference = require('../topologies/read_preference'); + +/** + * Handle callback (including any exceptions thrown) + */ +function handleCallback(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +} + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * An internal class that embodies a cursor on MongoDB, allowing for iteration over the + * results returned from a query. + * + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +class Cursor { + /** + * Create a cursor + * + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + */ + constructor(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.s = { + cursorId: null, + cmd: cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms + }; + + if (typeof options.session === 'object') { + this.s.session = options.session; + } + + // Add promoteLong to cursor state + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.s.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.s.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.s.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.s.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.s.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.s.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.s.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.s.cursorId = Long.fromNumber(cmd); + this.s.lastCursorId = this.s.cursorId; + } else if (cmd instanceof Long) { + this.s.cursorId = cmd; + this.s.lastCursorId = cmd; + } + } + + setCursorBatchSize(value) { + this.s.batchSize = value; + } + + cursorBatchSize() { + return this.s.batchSize; + } + + setCursorLimit(value) { + this.s.limit = value; + } + + cursorLimit() { + return this.s.limit; + } + + setCursorSkip(value) { + this.s.skip = value; + } + + cursorSkip() { + return this.s.skip; + } + + _endSession(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.s.session; + if (session && (options.force || session.owner === this)) { + this.s.session = undefined; + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + + return false; + } + + /** + * Clone the cursor + * @method + * @return {Cursor} + */ + clone() { + return this.topology.cursor(this.ns, this.cmd, this.options); + } + + /** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ + isDead() { + return this.s.dead === true; + } + + /** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ + isKilled() { + return this.s.killed === true; + } + + /** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ + isNotified() { + return this.s.notified === true; + } + + /** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ + bufferedCount() { + return this.s.documents.length - this.s.cursorIndex; + } + + /** + * Kill the cursor + * + * @param {resultCallback} callback A callback function + */ + kill(callback) { + // Set cursor to dead + this.s.dead = true; + this.s.killed = true; + // Remove documents + this.s.documents = []; + + // If no cursor id just return + if (this.s.cursorId == null || this.s.cursorId.isZero() || this.s.init === false) { + if (callback) callback(null, null); + return; + } + + // Default pool + const pool = this.s.server.s.pool; + + // Execute command + this.s.server.s.wireProtocolHandler.killCursor(this.bson, this.ns, this.s, pool, callback); + } + + /** + * Resets the cursor + */ + rewind() { + if (this.s.init) { + if (!this.s.dead) { + this.kill(); + } + + this.s.currentLimit = 0; + this.s.init = false; + this.s.dead = false; + this.s.killed = false; + this.s.notified = false; + this.s.documents = []; + this.s.cursorId = null; + this.s.cursorIndex = 0; + } + } + + /** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ + readBufferedDocuments(number) { + const unreadDocumentsLength = this.s.documents.length - this.s.cursorIndex; + const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + let elements = this.s.documents.slice(this.s.cursorIndex, this.s.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if (this.s.transforms && typeof this.s.transforms.doc === 'function') { + // Transform all the elements + for (let i = 0; i < elements.length; i++) { + elements[i] = this.s.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if (this.s.limit > 0 && this.s.currentLimit + elements.length > this.s.limit) { + elements = elements.slice(0, this.s.limit - this.s.currentLimit); + this.kill(); + } + + // Adjust current limit + this.s.currentLimit = this.s.currentLimit + elements.length; + this.s.cursorIndex = this.s.cursorIndex + elements.length; + + // Return elements + return elements; + } + + /** + * Retrieve the next document from the cursor + * + * @param {resultCallback} callback A callback function + */ + next(callback) { + nextFunction(this, callback); + } +} + +Cursor.prototype._find = deprecate( + callback => _find(this, callback), + '_find() is deprecated, please stop using it' +); + +Cursor.prototype._getmore = deprecate( + callback => _getmore(this, callback), + '_getmore() is deprecated, please stop using it' +); + +function _getmore(cursor, callback) { + if (cursor.logger.isDebug()) { + cursor.logger.debug(`schedule getMore call for query [${JSON.stringify(cursor.query)}]`); + } + + // Determine if it's a raw query + const raw = cursor.options.raw || cursor.cmd.raw; + + // Set the current batchSize + let batchSize = cursor.s.batchSize; + if (cursor.s.limit > 0 && cursor.s.currentLimit + batchSize > cursor.s.limit) { + batchSize = cursor.s.limit - cursor.s.currentLimit; + } + + // Default pool + const pool = cursor.s.server.s.pool; + + // We have a wire protocol handler + cursor.s.server.s.wireProtocolHandler.getMore( + cursor.bson, + cursor.ns, + cursor.s, + batchSize, + raw, + pool, + cursor.options, + callback + ); +} + +function _find(cursor, callback) { + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + const queryCallback = (err, r) => { + if (err) return callback(err); + + // Get the raw message + const result = r.message; + + // Query failure bit set + if (result.queryFailure) { + return callback(new MongoError(result.documents[0]), null); + } + + // Check if we have a command cursor + if ( + Array.isArray(result.documents) && + result.documents.length === 1 && + (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && + (result.documents[0].cursor !== 'string' || + result.documents[0]['$err'] || + result.documents[0]['errmsg'] || + Array.isArray(result.documents[0].result)) + ) { + // We have a an error document return the error + if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { + return callback(new MongoError(result.documents[0]), null); + } + + // We have a cursor document + if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { + const id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if (result.documents[0].cursor.ns) { + cursor.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursor.s.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + cursor.s.lastCursorId = cursor.s.cursorId; + // If we have a firstBatch set it + if (Array.isArray(result.documents[0].cursor.firstBatch)) { + cursor.s.documents = result.documents[0].cursor.firstBatch; + } + + // Return after processing command cursor + return callback(null, result); + } + + if (Array.isArray(result.documents[0].result)) { + cursor.s.documents = result.documents[0].result; + cursor.s.cursorId = Long.ZERO; + return callback(null, result); + } + } + + // Otherwise fall back to regular find path + cursor.s.cursorId = result.cursorId; + cursor.s.documents = result.documents; + cursor.s.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if (cursor.s.transforms && typeof cursor.s.transforms.query === 'function') { + cursor.s.documents = cursor.s.transforms.query(result); + } + + // Return callback + callback(null, result); + }; + + // Options passed to the pool + const queryOptions = {}; + + // If we have a raw query decorate the function + if (cursor.options.raw || cursor.cmd.raw) { + queryOptions.raw = cursor.options.raw || cursor.cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if (typeof cursor.query.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = cursor.query.documentsReturnedIn; + } + + // Add promote Long value if defined + if (typeof cursor.s.promoteLongs === 'boolean') { + queryOptions.promoteLongs = cursor.s.promoteLongs; + } + + // Add promote values if defined + if (typeof cursor.s.promoteValues === 'boolean') { + queryOptions.promoteValues = cursor.s.promoteValues; + } + + // Add promote values if defined + if (typeof cursor.s.promoteBuffers === 'boolean') { + queryOptions.promoteBuffers = cursor.s.promoteBuffers; + } + + if (typeof cursor.s.session === 'object') { + queryOptions.session = cursor.s.session; + } + + // Write the initial command out + cursor.s.server.s.pool.write(cursor.query, queryOptions, queryCallback); +} + +/** + * Validate if the pool is dead and return error + */ +function isConnectionDead(cursor, callback) { + if (cursor.pool && cursor.pool.isDestroyed()) { + cursor.s.killed = true; + const err = new MongoNetworkError( + `connection to host ${cursor.pool.host}:${cursor.pool.port} was destroyed` + ); + _setCursorNotifiedImpl(cursor, () => callback(err)); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +function isCursorDeadButNotkilled(cursor, callback) { + // Cursor is dead but not marked killed, return null + if (cursor.s.dead && !cursor.s.killed) { + cursor.s.killed = true; + setCursorNotified(cursor, callback); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +function isCursorDeadAndKilled(cursor, callback) { + if (cursor.s.dead && cursor.s.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +function isCursorKilled(cursor, callback) { + if (cursor.s.killed) { + setCursorNotified(cursor, callback); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +function setCursorDeadAndNotified(cursor, callback) { + cursor.s.dead = true; + setCursorNotified(cursor, callback); +} + +/** + * Mark cursor as being notified + */ +function setCursorNotified(cursor, callback) { + _setCursorNotifiedImpl(cursor, () => handleCallback(callback, null, null)); +} + +function _setCursorNotifiedImpl(cursor, callback) { + cursor.s.notified = true; + cursor.s.documents = []; + cursor.s.cursorIndex = 0; + if (cursor._endSession) { + return cursor._endSession(undefined, () => callback()); + } + return callback(); +} + +function initializeCursorAndRetryNext(cursor, callback) { + cursor.topology.selectServer( + readPreferenceServerSelector(cursor.options.readPreference || ReadPreference.primary), + (err, server) => { + if (err) { + callback(err, null); + return; + } + + cursor.s.server = server; + cursor.s.init = true; + + // check if server supports collation + // NOTE: this should be a part of the selection predicate! + if (cursor.cmd && cursor.cmd.collation && cursor.server.description.maxWireVersion < 5) { + callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + return; + } + + try { + cursor.query = cursor.s.server.s.wireProtocolHandler.command( + cursor.bson, + cursor.ns, + cursor.cmd, + cursor.s, + cursor.topology, + cursor.options + ); + + nextFunction(cursor, callback); + } catch (err) { + callback(err); + return; + } + } + ); +} + +function nextFunction(cursor, callback) { + // We have notified about it + if (cursor.s.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(cursor, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(cursor, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(cursor, callback)) return; + + // We have just started the cursor + if (!cursor.s.init) { + return initializeCursorAndRetryNext(cursor, callback); + } + + // If we don't have a cursorId execute the first query + if (cursor.s.cursorId == null) { + // Check if pool is dead and return if not possible to + // execute the query against the db + if (isConnectionDead(cursor, callback)) return; + + // query, cmd, options, s, callback + return _find(cursor, function(err) { + if (err) return handleCallback(callback, err, null); + + if (cursor.s.cursorId && cursor.s.cursorId.isZero() && cursor._endSession) { + cursor._endSession(); + } + + if ( + cursor.s.documents.length === 0 && + cursor.s.cursorId && + cursor.s.cursorId.isZero() && + !cursor.cmd.tailable && + !cursor.cmd.awaitData + ) { + return setCursorNotified(cursor, callback); + } + + nextFunction(cursor, callback); + }); + } + + if (cursor.s.documents.length === cursor.s.cursorIndex && Long.ZERO.equals(cursor.s.cursorId)) { + setCursorDeadAndNotified(cursor, callback); + return; + } + + if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { + // Ensure we kill the cursor on the server + cursor.kill(); + // Set cursor in dead and notified state + setCursorDeadAndNotified(cursor, callback); + return; + } + + if ( + cursor.s.documents.length === cursor.s.cursorIndex && + cursor.cmd.tailable && + Long.ZERO.equals(cursor.s.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: cursor.cmd.tailable, + awaitData: cursor.cmd.awaitData + }) + ); + } + + if (cursor.s.cursorIndex === cursor.s.documents.length && !Long.ZERO.equals(cursor.s.cursorId)) { + // Ensure an empty cursor state + cursor.s.documents = []; + cursor.s.cursorIndex = 0; + + // Check if connection is dead and return if not possible to + if (isConnectionDead(cursor, callback)) return; + + // Execute the next get more + return _getmore(cursor, function(err, doc, connection) { + if (err) { + if (err instanceof MongoError) { + err[mongoErrorContextSymbol].isGetMore = true; + } + + return handleCallback(callback, err); + } + + if (cursor.s.cursorId && cursor.s.cursorId.isZero() && cursor._endSession) { + cursor._endSession(); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + cursor.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + cursor.s.documents.length === 0 && + cursor.cmd.tailable && + Long.ZERO.equals(cursor.s.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: cursor.cmd.tailable, + awaitData: cursor.cmd.awaitData + }) + ); + } else if ( + cursor.s.documents.length === 0 && + cursor.cmd.tailable && + !Long.ZERO.equals(cursor.s.cursorId) + ) { + return nextFunction(cursor, callback); + } + + if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { + return setCursorDeadAndNotified(cursor, callback); + } + + nextFunction(cursor, callback); + }); + } + + if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { + // Ensure we kill the cursor on the server + cursor.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(cursor, callback); + } + + // Increment the current cursor limit + cursor.s.currentLimit += 1; + + // Get the document + let doc = cursor.s.documents[cursor.s.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + cursor.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(cursor, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }); + } + + // Transform the doc with passed in transformation method if provided + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + doc = cursor.s.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); +} + +module.exports = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/monitoring.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/monitoring.js new file mode 100644 index 0000000..dbd6b9f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/monitoring.js @@ -0,0 +1,217 @@ +'use strict'; + +const ServerDescription = require('./server_description').ServerDescription; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +/** + * Published when server description changes, but does NOT include changes to the RTT. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {ServerDescription} previousDescription The previous server description + * @property {ServerDescription} newDescription The new server description + */ +class ServerDescriptionChangedEvent { + constructor(topologyId, address, previousDescription, newDescription) { + Object.assign(this, { topologyId, address, previousDescription, newDescription }); + } +} + +/** + * Published when server is initialized. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + */ +class ServerOpeningEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when server is closed. + * + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {Object} topologyId A unique identifier for the topology + */ +class ServerClosedEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when topology description changes. + * + * @property {Object} topologyId + * @property {TopologyDescription} previousDescription The old topology description + * @property {TopologyDescription} newDescription The new topology description + */ +class TopologyDescriptionChangedEvent { + constructor(topologyId, previousDescription, newDescription) { + Object.assign(this, { topologyId, previousDescription, newDescription }); + } +} + +/** + * Published when topology is initialized. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyOpeningEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Published when topology is closed. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyClosedEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Fired when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @property {Object} connectionId The connection id for the command + */ +class ServerHeartbeatStartedEvent { + constructor(connectionId) { + Object.assign(this, { connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster succeeds. + * + * @param {Number} duration The execution time of the event in ms + * @param {Object} reply The command reply + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatSucceededEvent { + constructor(duration, reply, connectionId) { + Object.assign(this, { duration, reply, connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * + * @param {Number} duration The execution time of the event in ms + * @param {MongoError|Object} failure The command failure + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatFailedEvent { + constructor(duration, failure, connectionId) { + Object.assign(this, { duration, failure, connectionId }); + } +} + +/** + * Performs a server check as described by the SDAM spec. + * + * NOTE: This method automatically reschedules itself, so that there is always an active + * monitoring process + * + * @param {Server} server The server to monitor + */ +function monitorServer(server) { + // executes a single check of a server + const checkServer = callback => { + let start = process.hrtime(); + + // emit a signal indicating we have started the heartbeat + server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); + + server.command( + 'admin.$cmd', + { ismaster: true }, + { + monitoring: true, + socketTimeout: server.s.options.connectionTimeout || 2000 + }, + function(err, result) { + let duration = calculateDurationInMs(start); + + if (err) { + server.emit( + 'serverHeartbeatFailed', + new ServerHeartbeatFailedEvent(duration, err, server.name) + ); + + return callback(err, null); + } + + const isMaster = result.result; + server.emit( + 'serverHeartbeatSucceded', + new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) + ); + + return callback(null, isMaster); + } + ); + }; + + const successHandler = isMaster => { + server.s.monitoring = false; + + // emit an event indicating that our description has changed + server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); + + // schedule the next monitoring process + server.s.monitorId = setTimeout( + () => monitorServer(server), + server.s.options.heartbeatFrequencyMS + ); + }; + + // run the actual monitoring loop + server.s.monitoring = true; + checkServer((err, isMaster) => { + if (!err) { + successHandler(isMaster); + return; + } + + // According to the SDAM specification's "Network error during server check" section, if + // an ismaster call fails we reset the server's pool. If a server was once connected, + // change its type to `Unknown` only after retrying once. + + // TODO: we need to reset the pool here + + return checkServer((err, isMaster) => { + if (err) { + server.s.monitoring = false; + + // revert to `Unknown` by emitting a default description with no isMaster + server.emit('descriptionReceived', new ServerDescription(server.description.address)); + + // do not reschedule monitoring in this case + return; + } + + successHandler(isMaster); + }); + }); +} + +module.exports = { + ServerDescriptionChangedEvent, + ServerOpeningEvent, + ServerClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyClosedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent, + monitorServer +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server.js new file mode 100644 index 0000000..57b28ed --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server.js @@ -0,0 +1,411 @@ +'use strict'; +const EventEmitter = require('events'); +const MongoError = require('../error').MongoError; +const Pool = require('../connection/pool'); +const relayEvents = require('../utils').relayEvents; +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const Query = require('../connection/commands').Query; +const TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'); +const ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'); +const BSON = require('../connection/utils').retrieveBSON(); +const createClientInfo = require('../topologies/shared').createClientInfo; +const Logger = require('../connection/logger'); +const ServerDescription = require('./server_description').ServerDescription; +const ReadPreference = require('../topologies/read_preference'); +const monitorServer = require('./monitoring').monitorServer; + +/** + * + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + */ +class Server extends EventEmitter { + /** + * Create a server + * + * @param {ServerDescription} description + * @param {Object} options + */ + constructor(description, options) { + super(); + + this.s = { + // the server description + description, + // a saved copy of the incoming options + options, + // the server logger + logger: Logger('Server', options), + // the bson parser + bson: options.bson || new BSON(), + // client metadata for the initial handshake + clientInfo: createClientInfo(options), + // state variable to determine if there is an active server check in progress + monitoring: false, + // the connection pool + pool: null + }; + } + + get description() { + return this.s.description; + } + + get name() { + return this.s.description.address; + } + + /** + * Initiate server connect + * + * @param {Array} [options.auth] Array of auth options to apply on connect + */ + connect(options) { + options = options || {}; + + // do not allow connect to be called on anything that's not disconnected + if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { + throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); + } + + // create a pool + this.s.pool = new Pool(this, Object.assign(this.s.options, options, { bson: this.s.bson })); + + // Set up listeners + this.s.pool.on('connect', connectEventHandler(this)); + this.s.pool.on('close', closeEventHandler(this)); + + // this.s.pool.on('error', errorEventHandler(this)); + // this.s.pool.on('timeout', timeoutEventHandler(this)); + // this.s.pool.on('parseError', errorEventHandler(this)); + // this.s.pool.on('reconnect', reconnectEventHandler(this)); + // this.s.pool.on('reconnectFailed', errorEventHandler(this)); + + // relay all command monitoring events + relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // If auth settings have been provided, use them + if (options.auth) { + this.s.pool.connect.apply(this.s.pool, options.auth); + return; + } + + this.s.pool.connect(); + } + + /** + * Destroy the server connection + * + * @param {Boolean} [options.emitClose=false] Emit close event on destroy + * @param {Boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {Boolean} [options.force=false] Force destroy the pool + */ + destroy(callback) { + if (typeof callback === 'function') { + callback(null, null); + } + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + monitor() { + if (this.s.monitoring) return; + if (this.s.monitorId) clearTimeout(this.s.monitorId); + monitorServer(this); + } + + /** + * Execute a command + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + const error = basicReadValidations(this, options); + if (error) { + return callback(error, null); + } + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (this.s.logger.isDebug()) { + this.s.logger.debug( + `executing command [${JSON.stringify({ ns, cmd, options })}] against ${this.name}` + ); + } + + // Check if we have collation support + if (this.description.maxWireVersion < 5 && cmd.collation) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + // Create the query object + const query = this.s.wireProtocolHandler.command(this, ns, cmd, {}, options); + // Set slave OK of the query + query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; + + // write options + const writeOptions = { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + command: true, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, + requestId: query.requestId, + socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null, + session: options.session || null + }; + + // write the operation to the pool + this.s.pool.write(query, writeOptions, callback); + } + + /** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); + } +} + +function basicWriteValidations(server) { + if (!server.s.pool) { + return new MongoError('server instance is not connected'); + } + + if (server.s.pool.isDestroyed()) { + return new MongoError('server instance pool was destroyed'); + } + + return null; +} + +function basicReadValidations(server, options) { + const error = basicWriteValidations(server, options); + if (error) { + return error; + } + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + return new MongoError('readPreference must be an instance of ReadPreference'); + } +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const server = args.server; + const op = args.op; + const ns = args.ns; + const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; + + const error = basicWriteValidations(server, options); + if (error) { + callback(error, null); + return; + } + + // Check if we have collation support + if (server.description.maxWireVersion < 5 && options.collation) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + // Execute write + return server.s.wireProtocolHandler[op](server.s.pool, ns, server.s.bson, ops, options, callback); +} + +function saslSupportedMechs(options) { + if (!options) { + return {}; + } + + const authArray = options.auth || []; + const authMechanism = authArray[0] || options.authMechanism; + const authSource = authArray[1] || options.authSource || options.dbName || 'admin'; + const user = authArray[2] || options.user; + + if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { + return {}; + } + + if (!user) { + return {}; + } + + return { saslSupportedMechs: `${authSource}.${user}` }; +} + +function extractIsMasterError(err, result) { + if (err) return err; + if (result && result.result && result.result.ok === 0) { + return new MongoError(result.result); + } +} + +function executeServerHandshake(server, callback) { + // construct an `ismaster` query + const compressors = + server.s.options.compression && server.s.options.compression.compressors + ? server.s.options.compression.compressors + : []; + + const queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + const query = new Query( + server.s.bson, + 'admin.$cmd', + Object.assign( + { ismaster: true, client: server.s.clientInfo, compression: compressors }, + saslSupportedMechs(server.s.options) + ), + queryOptions + ); + + // execute the query + server.s.pool.write( + query, + { socketTimeout: server.s.options.connectionTimeout || 2000 }, + callback + ); +} + +function configureWireProtocolHandler(ismaster) { + // 3.2 wire protocol handler + if (ismaster.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(); + } + + // default to 2.6 wire protocol handler + return new TwoSixWireProtocolSupport(); +} + +function connectEventHandler(server) { + return function() { + // log information of received information if in info mode + // if (server.s.logger.isInfo()) { + // var object = err instanceof MongoError ? JSON.stringify(err) : {}; + // server.s.logger.info(`server ${server.name} fired event ${event} out with message ${object}`); + // } + + // begin initial server handshake + const start = process.hrtime(); + executeServerHandshake(server, (err, response) => { + // Set initial lastIsMasterMS - is this needed? + server.s.lastIsMasterMS = calculateDurationInMs(start); + + const serverError = extractIsMasterError(err, response); + if (serverError) { + server.emit('error', serverError); + return; + } + + // extract the ismaster from the server response + const isMaster = response.result; + + // compression negotation + if (isMaster && isMaster.compression) { + const localCompressionInfo = server.s.options.compression; + const localCompressors = localCompressionInfo.compressors; + for (var i = 0; i < localCompressors.length; i++) { + if (isMaster.compression.indexOf(localCompressors[i]) > -1) { + server.s.pool.options.agreedCompressor = localCompressors[i]; + break; + } + } + + if (localCompressionInfo.zlibCompressionLevel) { + server.s.pool.options.zlibCompressionLevel = localCompressionInfo.zlibCompressionLevel; + } + } + + // configure the wire protocol handler + server.s.wireProtocolHandler = configureWireProtocolHandler(isMaster); + + // log the connection event if requested + if (server.s.logger.isInfo()) { + server.s.logger.info( + `server ${server.name} connected with ismaster [${JSON.stringify(isMaster)}]` + ); + } + + // emit an event indicating that our description has changed + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, isMaster) + ); + + // emit a connect event + server.emit('connect', isMaster); + }); + }; +} + +function closeEventHandler(server) { + return function() { + server.emit('close'); + }; +} + +module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_description.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_description.js new file mode 100644 index 0000000..558b8cf --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_description.js @@ -0,0 +1,141 @@ +'use strict'; + +// An enumeration of server types we know about +const ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos +]); + +const ISMASTER_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'me', + 'hosts', + 'passives', + 'arbiters', + 'tags', + 'setName', + 'setVersion', + 'electionId', + 'primary', + 'logicalSessionTimeoutMinutes' +]; + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + */ +class ServerDescription { + /** + * Create a ServerDescription + * @param {String} address The address of the server + * @param {Object} [ismaster] An optional ismaster response for this server + * @param {Object} [options] Optional settings + * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) + */ + constructor(address, ismaster, options) { + options = options || {}; + ismaster = Object.assign( + { + minWireVersion: 0, + maxWireVersion: 0, + hosts: [], + passives: [], + arbiters: [], + tags: [] + }, + ismaster + ); + + this.address = address; + this.error = null; + this.roundTripTime = options.roundTripTime || 0; + this.lastUpdateTime = Date.now(); + this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; + this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; + this.type = parseServerType(ismaster); + + // direct mappings + ISMASTER_FIELDS.forEach(field => { + if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; + }); + + // normalize case for hosts + this.hosts = this.hosts.map(host => host.toLowerCase()); + this.passives = this.passives.map(host => host.toLowerCase()); + this.arbiters = this.arbiters.map(host => host.toLowerCase()); + } + + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** + * @return {Boolean} Is this server available for reads + */ + get isReadable() { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** + * @return {Boolean} Is this server available for writes + */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } +} + +/** + * Parses an `ismaster` message and determines the server type + * + * @param {Object} ismaster The `ismaster` message to parse + * @return {ServerType} + */ +function parseServerType(ismaster) { + if (!ismaster || !ismaster.ok) { + return ServerType.Unknown; + } + + if (ismaster.isreplicaset) { + return ServerType.RSGhost; + } + + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (ismaster.setName) { + if (ismaster.hidden) { + return ServerType.RSOther; + } else if (ismaster.ismaster) { + return ServerType.RSPrimary; + } else if (ismaster.secondary) { + return ServerType.RSSecondary; + } else if (ismaster.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +module.exports = { + ServerDescription, + ServerType +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_selectors.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_selectors.js new file mode 100644 index 0000000..d082170 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/server_selectors.js @@ -0,0 +1,206 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const TopologyType = require('./topology_description').TopologyType; +const ReadPreference = require('../topologies/read_preference'); +const MongoError = require('../error').MongoError; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +function writableServerSelector() { + return function(topologyDescription, servers) { + return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); + }; +} + +// reducers +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoError( + `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary = servers.filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); + return servers.reduce((result, server) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } + + return servers; +} + +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +function tagSetReducer(readPreference, servers) { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, []); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce( + (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server) { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server) { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server) { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server) { + return server.type !== ServerType.Unknown; +} + +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new TypeError('Invalid read preference specified'); + } + + return function(topologyDescription, servers) { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) + ) { + throw new MongoError( + `Minimum wire version '${ + readPreference.minWireVersion + }' required, but found '${commonWireVersion}'` + ); + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + if (readPreference.mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (readPreference.mode === ReadPreference.SECONDARY) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } else if (readPreference.mode === ReadPreference.NEAREST) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(nearestFilter); + } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { + const result = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + + return result.length === 0 ? servers.filter(primaryFilter) : result; + } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } + }; +} + +module.exports = { + writableServerSelector, + readPreferenceServerSelector +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology.js new file mode 100644 index 0000000..bb43925 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology.js @@ -0,0 +1,666 @@ +'use strict'; +const EventEmitter = require('events'); +const ServerDescription = require('./server_description').ServerDescription; +const TopologyDescription = require('./topology_description').TopologyDescription; +const TopologyType = require('./topology_description').TopologyType; +const monitoring = require('./monitoring'); +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const MongoTimeoutError = require('../error').MongoTimeoutError; +const MongoNetworkError = require('../error').MongoNetworkError; +const Server = require('./server'); +const relayEvents = require('../utils').relayEvents; +const ReadPreference = require('../topologies/read_preference'); +const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; +const writableServerSelector = require('./server_selectors').writableServerSelector; +const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; +const Cursor = require('./cursor'); +const deprecate = require('util').deprecate; +const BSON = require('../connection/utils').retrieveBSON(); +const createCompressionInfo = require('../topologies/shared').createCompressionInfo; + +// Global state +let globalTopologyCounter = 0; + +// Constants +const TOPOLOGY_DEFAULTS = { + localThresholdMS: 15, + serverSelectionTimeoutMS: 10000, + heartbeatFrequencyMS: 30000, + minHeartbeatIntervalMS: 500 +}; + +/** + * A container of server instances representing a connection to a MongoDB topology. + * + * @fires Topology#serverOpening + * @fires Topology#serverClosed + * @fires Topology#serverDescriptionChanged + * @fires Topology#topologyOpening + * @fires Topology#topologyClosed + * @fires Topology#topologyDescriptionChanged + * @fires Topology#serverHeartbeatStarted + * @fires Topology#serverHeartbeatSucceeded + * @fires Topology#serverHeartbeatFailed + */ +class Topology extends EventEmitter { + /** + * Create a topology + * + * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to + * @param {Object} [options] Optional settings + * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled + */ + constructor(seedlist, options) { + super(); + if (typeof options === 'undefined') { + options = seedlist; + seedlist = []; + + // this is for legacy single server constructor support + if (options.host) { + seedlist.push({ host: options.host, port: options.port }); + } + } + + seedlist = seedlist || []; + options = Object.assign({}, TOPOLOGY_DEFAULTS, options); + + const topologyType = topologyTypeFromSeedlist(seedlist, options); + const topologyId = globalTopologyCounter++; + const serverDescriptions = seedlist.reduce((result, seed) => { + const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; + result.set(address, new ServerDescription(address)); + return result; + }, new Map()); + + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options: Object.assign({}, options), + // initial seedlist of servers to connect to + seedlist: seedlist, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + null, + null, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, + // allow users to override the cursor factory + Cursor: options.cursorFactory || Cursor, + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]) + }; + + // amend options for server instance creation + this.s.options.compression = { compressors: createCompressionInfo(options) }; + } + + /** + * @return A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + + /** + * All raw connections + * @method + * @return {Connection[]} + */ + connections() { + return Array.from(this.s.servers.values()).reduce((result, server) => { + return result.concat(server.s.pool.allConnections()); + }, []); + } + + /** + * Initiate server connect + * + * @param {Object} [options] Optional settings + * @param {Array} [options.auth=null] Array of auth options to apply on connect + */ + connect(/* options */) { + // emit SDAM monitoring events + this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + connectServers(this, Array.from(this.s.description.servers.values())); + this.s.connected = true; + } + + /** + * Close this topology + */ + close(callback) { + // destroy all child servers + this.s.servers.forEach(server => server.destroy()); + + // emit an event for close + this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); + + this.s.connected = false; + + if (typeof callback === 'function') { + callback(null, null); + } + } + + /** + * Selects a server according to the selection predicate provided + * + * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window + * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + selectServers( + this, + selector, + options.serverSelectionTimeoutMS, + process.hrtime(), + (err, servers) => { + if (err) return callback(err, null); + callback(null, randomSelection(servers)); + } + ); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param {object} serverDescription The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + + // emit monitoring events for this change + this.emit( + 'serverDescriptionChanged', + new monitoring.ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + this.s.description.servers.get(serverDescription.address) + ) + ); + + // update server list from updated descriptions + updateServers(this, serverDescription); + + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + /** + * Authenticate using a specified mechanism + * + * @param {String} mechanism The auth mechanism used for authentication + * @param {String} db The db we are authenticating against + * @param {Object} options Optional settings for the authenticating mechanism + * @param {authResultCallback} callback A callback function + */ + auth(mechanism, db, options, callback) { + callback(null, null); + } + + /** + * Logout from a database + * + * @param {String} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ + logout(db, callback) { + callback(null, null); + } + + // Basic operation support. Eventually this should be moved into command construction + // during the command refactor. + + /** + * Insert one or more documents + * + * @param {String} ns The full qualified namespace for this operation + * @param {Array} ops An array of documents to insert + * @param {Boolean} [options.ordered=true] Execute in order or out of order + * @param {Object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * + * @param {string} ns The fully qualified namespace for this operation + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); + } + + /** + * Execute a command + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + const readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + this.selectServer(readPreferenceServerSelector(readPreference), (err, server) => { + if (err) { + callback(err, null); + return; + } + + server.command(ns, cmd, options, callback); + }); + } + + /** + * Create a new cursor + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ + cursor(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + const CursorClass = options.cursorFactory || this.s.Cursor; + + return new CursorClass(this.s.bson, ns, cmd, options, topology, this.s.options); + } +} + +// legacy aliases +Topology.prototype.destroy = deprecate( + Topology.prototype.close, + 'destroy() is deprecated, please use close() instead' +); + +function topologyTypeFromSeedlist(seedlist, options) { + if (seedlist.length === 1 && !options.replicaSet) return TopologyType.Single; + if (options.replicaSet) return TopologyType.ReplicaSetNoPrimary; + return TopologyType.Unknown; +} + +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} + +/** + * Selects servers using the provided selector + * + * @private + * @param {Topology} topology The topology to select servers from + * @param {function} selector The actual predicate used for selecting servers + * @param {Number} timeout The max time we are willing wait for selection + * @param {Number} start A high precision timestamp for the start of the selection process + * @param {function} callback The callback used to convey errors or the resultant servers + */ +function selectServers(topology, selector, timeout, start, callback) { + const serverDescriptions = Array.from(topology.description.servers.values()); + let descriptions; + + try { + descriptions = selector + ? selector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + return callback(e, null); + } + + if (descriptions.length) { + const servers = descriptions.map(description => topology.s.servers.get(description.address)); + return callback(null, servers); + } + + const duration = calculateDurationInMs(start); + if (duration >= timeout) { + return callback(new MongoTimeoutError(`Server selection timed out after ${timeout} ms`)); + } + + const retrySelection = () => { + // ensure all server monitors attempt monitoring immediately + topology.s.servers.forEach(server => server.monitor()); + + const iterationTimer = setTimeout(() => { + callback(new MongoTimeoutError('Server selection timed out due to monitoring')); + }, topology.s.minHeartbeatIntervalMS); + + topology.once('topologyDescriptionChanged', () => { + // successful iteration, clear the check timer + clearTimeout(iterationTimer); + + // topology description has changed due to monitoring, reattempt server selection + selectServers(topology, selector, timeout, start, callback); + }); + }; + + // ensure we are connected + if (!topology.s.connected) { + topology.connect(); + + // we want to make sure we're still within the requested timeout window + const failToConnectTimer = setTimeout(() => { + callback(new MongoTimeoutError('Server selection timed out waiting to connect')); + }, timeout - duration); + + topology.once('connect', () => { + clearTimeout(failToConnectTimer); + retrySelection(); + }); + + return; + } + + retrySelection(); +} + +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param {Topology} topology The topology responsible for the servers + * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect + */ +function connectServers(topology, serverDescriptions) { + topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { + // publish an open event for each ServerDescription created + topology.emit( + 'serverOpening', + new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options); + relayEvents(server, topology, [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed' + ]); + + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + server.on('connect', serverConnectEventHandler(server, topology)); + servers.set(serverDescription.address, server); + server.connect(); + return servers; + }, new Map()); +} + +function updateServers(topology, currentServerDescription) { + // update the internal server's description + if (topology.s.servers.has(currentServerDescription.address)) { + const server = topology.s.servers.get(currentServerDescription.address); + server.s.description = currentServerDescription; + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + topology.emit( + 'serverOpening', + new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options); + relayEvents(server, topology, [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed' + ]); + + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + server.on('connect', serverConnectEventHandler(server, topology)); + topology.s.servers.set(serverDescription.address, server); + server.connect(); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + server.destroy(() => + topology.emit('serverClosed', new monitoring.ServerClosedEvent(topology.s.id, serverAddress)) + ); + } +} + +function serverConnectEventHandler(server, topology) { + return function(/* ismaster */) { + topology.emit('connect', topology); + }; +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const topology = args.topology; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + const willRetryWrite = + !args.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(topology) && + !options.session.inTransaction(); + + topology.selectServer(writableServerSelector(), (err, server) => { + if (err) { + callback(err, null); + return; + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!(err instanceof MongoNetworkError) && !err.message.match(/not master/)) { + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // execute the write operation + server[op](ns, ops, options, handler); + + // we need to increment the statement id if we're in a transaction + if (options.session && options.session.inTransaction()) { + options.session.incrementStatementId(ops.length); + } + }); +} + +/** + * A server opening SDAM monitoring event + * + * @event Topology#serverOpening + * @type {ServerOpeningEvent} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Topology#serverClosed + * @type {ServerClosedEvent} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Topology#serverDescriptionChanged + * @type {ServerDescriptionChangedEvent} + */ + +/** + * A topology open SDAM event + * + * @event Topology#topologyOpening + * @type {TopologyOpeningEvent} + */ + +/** + * A topology closed SDAM event + * + * @event Topology#topologyClosed + * @type {TopologyClosedEvent} + */ + +/** + * A topology structure SDAM change event + * + * @event Topology#topologyDescriptionChanged + * @type {TopologyDescriptionChangedEvent} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Topology#serverHeartbeatStarted + * @type {ServerHeartbeatStartedEvent} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Topology#serverHeartbeatFailed + * @type {ServerHearbeatFailedEvent} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Topology#serverHeartbeatSucceeded + * @type {ServerHeartbeatSucceededEvent} + */ + +module.exports = Topology; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology_description.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology_description.js new file mode 100644 index 0000000..cd4f8fe --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sdam/topology_description.js @@ -0,0 +1,364 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const ServerDescription = require('./server_description').ServerDescription; +const ReadPreference = require('../topologies/read_preference'); + +// contstants related to compatability checks +const MIN_SUPPORTED_SERVER_VERSION = '2.6'; +const MIN_SUPPORTED_WIRE_VERSION = 2; +const MAX_SUPPORTED_WIRE_VERSION = 5; + +// An enumeration of topology types we know about +const TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +// Representation of a deployment of servers +class TopologyDescription { + /** + * Create a TopologyDescription + * + * @param {string} topologyType + * @param {Map} serverDescriptions the a map of address to ServerDescription + * @param {string} setName + * @param {number} maxSetVersion + * @param {ObjectId} maxElectionId + */ + constructor(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, options) { + options = options || {}; + + // TODO: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType || TopologyType.Unknown; + this.setName = setName || null; + this.maxSetVersion = maxSetVersion || null; + this.maxElectionId = maxElectionId || null; + this.servers = serverDescriptions || new Map(); + this.stale = false; + this.compatible = true; + this.compatibilityError = null; + this.logicalSessionTimeoutMinutes = null; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; + this.localThresholdMS = options.localThresholdMS || 0; + this.options = options; + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ + serverDescription.minWireVersion + }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION}.`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ + serverDescription.maxWireVersion + }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); + this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { + if (server.logicalSessionTimeoutMinutes == null) return null; + if (result == null) return server.logicalSessionTimeoutMinutes; + return Math.min(result, server.logicalSessionTimeoutMinutes); + }, null); + } + + /** + * @returns The minimum reported wire version of all known servers + */ + get commonWireVersion() { + return Array.from(this.servers.values()) + .filter(server => server.type !== ServerType.Unknown) + .reduce( + (min, server) => + min == null ? server.maxWireVersion : Math.min(min, server.maxWireVersion), + null + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * + * @param {ServerDescription} serverDescription + */ + update(serverDescription) { + const address = serverDescription.address; + // NOTE: there are a number of prime targets for refactoring here + // once we support destructuring assignments + + // potentially mutated values + let topologyType = this.type; + let setName = this.setName; + let maxSetVersion = this.maxSetVersion; + let maxElectionId = this.maxElectionId; + + const serverType = serverDescription.type; + let serverDescriptions = new Map(this.servers); + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + this.options + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); + (topologyType = result[0]), (setName = result[1]); + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + setName, + serverDescription + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + this.options + ); + } + + /** + * Determines if the topology has a readable server available. See the table in the + * following section for behaviour rules. + * + * @param {ReadPreference} [readPreference] An optional read preference for determining if a readable server is present + * @return {Boolean} Whether there is a readable server in this topology + */ + hasReadableServer(/* readPreference */) { + // To be implemented when server selection is implemented + } + + /** + * Determines if the topology has a writable server available. See the table in the + * following section for behaviour rules. + * + * @return {Boolean} Whether there is a writable server in this topology + */ + hasWritableServer() { + return this.hasReadableServer(ReadPreference.primary); + } + + /** + * Determines if the topology has a definition for the provided address + * + * @param {String} address + * @return {Boolean} Whether the topology knows about this server + */ + hasServer(address) { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType) { + if (serverType === ServerType.Mongos) return TopologyType.Sharded; + if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; + return TopologyType.ReplicaSetNoPrimary; +} + +function updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId +) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; + const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; + if (serverDescription.setVersion != null && electionIdOID != null) { + if (maxSetVersion != null && maxElectionIdOID != null) { + if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const address of serverDescriptions.keys()) { + const server = serverDescriptions.get(address); + + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { + if (setName == null) { + throw new TypeError('setName is required'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { + let topologyType = TopologyType.ReplicaSetNoPrimary; + + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions) { + for (const addr of serverDescriptions.keys()) { + if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} + +module.exports = { + TopologyType, + TopologyDescription +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/sessions.js b/node_modules/mongoose/node_modules/mongodb-core/lib/sessions.js new file mode 100644 index 0000000..429c06e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/sessions.js @@ -0,0 +1,459 @@ +'use strict'; + +const retrieveBSON = require('./connection/utils').retrieveBSON; +const EventEmitter = require('events'); +const BSON = retrieveBSON(); +const Binary = BSON.Binary; +const uuidV4 = require('./utils').uuidV4; +const MongoError = require('./error').MongoError; +const isRetryableError = require('././error').isRetryableError; +const MongoNetworkError = require('./error').MongoNetworkError; +const MongoWriteConcernError = require('./error').MongoWriteConcernError; +const Transaction = require('./transactions').Transaction; +const TxnState = require('./transactions').TxnState; + +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new MongoError('Cannot use a session that has ended'); + if (typeof callback === 'function') { + callback(error, null); + return false; + } + + throw error; + } + + return true; +} + +/** + * Options to pass when creating a Client Session + * @typedef {Object} SessionOptions + * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session + * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. + */ + +/** + * A BSON document reflecting the lsid of a {@link ClientSession} + * @typedef {Object} SessionId + */ + +/** + * A class representing a client session on the server + * WARNING: not meant to be instantiated directly. + * @class + * @hideconstructor + */ +class ClientSession extends EventEmitter { + /** + * Create a client session. + * WARNING: not meant to be instantiated directly + * + * @param {Topology} topology The current client's topology (Internal Class) + * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) + * @param {SessionOptions} [options] Optional settings + * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + + if (topology == null) { + throw new Error('ClientSession requires a topology'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + throw new Error('ClientSession requires a ServerSessionPool'); + } + + options = options || {}; + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.serverSession = sessionPool.acquire(); + this.clientOptions = clientOptions; + + this.supports = { + causalConsistency: + typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true + }; + + options = options || {}; + if (typeof options.initialClusterTime !== 'undefined') { + this.clusterTime = options.initialClusterTime; + } else { + this.clusterTime = null; + } + + this.operationTime = null; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** + * The server id associated with this session + * @type {SessionId} + */ + get id() { + return this.serverSession.id; + } + + /** + * Ends this session on the server + * + * @param {Object} [options] Optional settings. Currently reserved for future use + * @param {Function} [callback] Optional callback for completion of this operation + */ + endSession(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.hasEnded) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(); // pass in callback? + } + + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + + // spec indicates that we should ignore all errors for `endSessions` + if (typeof callback === 'function') callback(null, null); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Used to determine if this session equals another + * @param {ClientSession} session + * @return {boolean} true if the sessions are equal + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + */ + incrementTransactionNumber() { + this.serverSession.txnNumber++; + } + + /** + * @returns {boolean} whether this session is currently in a transaction or not + */ + inTransaction() { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param {TransactionOptions} options Options for the transaction + */ + startTransaction(options) { + assertAlive(this); + if (this.inTransaction()) { + throw new MongoError('Transaction already in progress'); + } + + // increment txnNumber + this.incrementTransactionNumber(); + + // create transaction state + this.transaction = new Transaction( + Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) + ); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + commitTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'commitTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'commitTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + abortTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'abortTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'abortTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + * @ignore + */ + toBSON() { + throw new Error('ClientSession cannot be serialized to BSON.'); + } +} + +function endTransaction(session, commandName, callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + + // handle any initial problematic cases + let txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + + // construct and send the command + const command = { [commandName]: 1 }; + + // apply a writeConcern if specified + if (session.transaction.options.writeConcern) { + Object.assign(command, { writeConcern: session.transaction.options.writeConcern }); + } else if (session.clientOptions && session.clientOptions.w) { + Object.assign(command, { writeConcern: { w: session.clientOptions.w } }); + } + + function commandHandler(e, r) { + if (commandName === 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + + if ( + e && + (e instanceof MongoNetworkError || + e instanceof MongoWriteConcernError || + isRetryableError(e)) + ) { + if (e.errorLabels) { + const idx = e.errorLabels.indexOf('TransientTransactionError'); + if (idx !== -1) { + e.errorLabels.splice(idx, 1); + } + } else { + e.errorLabels = []; + } + + e.errorLabels.push('UnknownTransactionCommitResult'); + } + } else { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + } + + callback(e, r); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + function transactionError(err) { + return commandName === 'commitTransaction' ? err : null; + } + + // send the command + session.topology.command('admin.$cmd', command, { session }, (err, reply) => { + if (err && isRetryableError(err)) { + return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => + commandHandler(transactionError(_err), _reply) + ); + } + + commandHandler(transactionError(err), reply); + }); +} + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @ignore + */ +class ServerSession { + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = Date.now(); + this.txnNumber = 0; + } + + /** + * Determines if the server session has timed out. + * @ignore + * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" + * @return {boolean} true if the session has timed out. + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @ignore + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new Error('ServerSessionPool requires a topology'); + } + + this.topology = topology; + this.sessions = []; + } + + /** + * Ends all sessions in the session pool. + * @ignore + */ + endAllPooledSessions() { + if (this.sessions.length) { + this.topology.endSessions(this.sessions.map(session => session.id)); + this.sessions = []; + } + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession + * is created. + * @ignore + * @returns {ServerSession} + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + return session; + } + } + + return new ServerSession(); + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * @ignore + * @param {ServerSession} session The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions[this.sessions.length - 1]; + if (session.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.unshift(session); + } + } +} + +module.exports = { + ClientSession, + ServerSession, + ServerSessionPool, + TxnState +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/node_modules/mongoose/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..22d0298 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,61 @@ +'use strict'; + +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results: [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: '' + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: 'fail', + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: '' + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/mongos.js b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..cd5110b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1504 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const BasicCursor = require('../cursor'); +const Logger = require('../connection/logger'); +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const clone = require('./shared').clone; +const diff = require('./shared').diff; +const cloneOptions = require('./shared').cloneOptions; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; +const BSON = retrieveBSON(); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#reconnect + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#failed + * @fires Mongos#fullsetup + * @fires Mongos#all + * @fires Mongos#serverHeartbeatStarted + * @fires Mongos#serverHeartbeatSucceeded + * @fires Mongos#serverHeartbeatFailed + * @fires Mongos#topologyOpening + * @fires Mongos#topologyClosed + * @fires Mongos#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Mongos = function(seedlist, options) { + options = options || {}; + + // Get replSet Id + this.id = id++; + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // Logger instance + logger: Logger('Mongos', options), + // Seedlist + seedlist: seedlist, + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // localThresholdMS + localThresholdMS: options.localThresholdMS || 15, + // Client info + clientInfo: createClientInfo(options), + // Authentication context + authenticationContexts: [] + }; + + // Set the client info + this.s.options.clientInfo = createClientInfo(options); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // All the authProviders + this.authProviders = options.authProviders || defaultAuthProviders(this.s.bson); + + // Disconnected state + this.state = DISCONNECTED; + + // Current proxies we are connecting to + this.connectingProxies = []; + // Currently connected proxies + this.connectedProxies = []; + // Disconnected proxies + this.disconnectedProxies = []; + // Are we authenticating + this.authenticating = false; + // Index of proxy to run operations against + this.index = 0; + // High availability timeout id + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + + // Description of the Replicaset + this.topologyDescription = { + topologyType: 'Unknown', + servers: [] + }; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; + + // Add event listener + EventEmitter.call(this); +}; + +inherits(Mongos, EventEmitter); +Object.assign(Mongos.prototype, SessionMixins); + +Object.defineProperty(Mongos.prototype, 'type', { + enumerable: true, + get: function() { + return 'mongos'; + } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; +function destroyServer(server, options) { + options = options || {}; + SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + server.destroy(options); +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +Mongos.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + const server = new Server( + Object.assign({}, self.s.options, x, options, { + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + relayEvents(server, self, ['serverDescriptionChanged']); + return server; + }); + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + + // Start all server connections + connectProxies(self, servers); +}; + +function handleEvent(self) { + return function() { + if (self.state === DESTROYED) return; + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Emit the left signal + self.emit('left', 'mongos', this); + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: this.name + }); + }; +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + + // Destroy the instance + if (self.state === DESTROYED) { + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + return this.destroy(); + } + + // Check the type of server + if (event === 'connect') { + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _this, function() { + // Get last known ismaster + self.ismaster = _this.lastIsMaster(); + + // Is this not a proxy, remove t + if (self.ismaster.msg === 'isdbgrid') { + // Add to the connectd list + for (var i = 0; i < self.connectedProxies.length; i++) { + if (self.connectedProxies[i].name === _this.name) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + _this.destroy(); + return self.emit('failed', _this); + } + } + + // Remove the handlers + for (i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Move from connecting proxies connected + moveServerFrom(self.connectingProxies, self.connectedProxies, _this); + // Emit the joined event + self.emit('joined', 'mongos', _this); + } else { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; + // We have a standalone server + if (!self.ismaster.hosts) { + message = 'expected mongos proxy, but found standalone mongod for server %s'; + } + + self.s.logger.warn(f(message, _this.name)); + } + + // This is not a mongos proxy, remove it completely + removeProxyFrom(self.connectingProxies, _this); + // Emit the left event + self.emit('left', 'server', _this); + // Emit failed event + self.emit('failed', _this); + } + }); + } else { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + // Emit the left event + self.emit('left', 'mongos', this); + // Emit failed event + self.emit('failed', this); + } + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Trigger topologyMonitor + if (self.connectingProxies.length === 0) { + // Emit connected if we are connected + if (self.connectedProxies.length > 0 && self.state === CONNECTING) { + // Set the state to connected + stateTransition(self, CONNECTED); + // Emit the connect event + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.disconnectedProxies.length === 0) { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + self.s.logger.warn( + f('no mongos proxies found in seed list, did you mean to connect to a replicaset') + ); + } + + // Emit the error that no proxies were found + return self.emit('error', new MongoError('no mongos proxies found in seed list')); + } + + // Topology monitor + topologyMonitor(self, { firstConnect: true }); + } + }; +} + +function connectProxies(self, servers) { + // Update connectingProxies + self.connectingProxies = self.connectingProxies.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.id, + address: server.name + }); + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +function pickProxy(self) { + // Get the currently connected Proxies + var connectedProxies = self.connectedProxies.slice(0); + + // Set lower bound + var lowerBoundLatency = Number.MAX_VALUE; + + // Determine the lower bound for the Proxies + for (var i = 0; i < connectedProxies.length; i++) { + if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { + lowerBoundLatency = connectedProxies[i].lastIsMasterMS; + } + } + + // Filter out the possible servers + connectedProxies = connectedProxies.filter(function(server) { + if ( + server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && + server.isConnected() + ) { + return true; + } + }); + + // We have no connectedProxies pick first of the connected ones + if (connectedProxies.length === 0) { + return self.connectedProxies[0]; + } + + // Get proxy + var proxy = connectedProxies[self.index % connectedProxies.length]; + // Update the index + self.index = (self.index + 1) % connectedProxies.length; + // Return the proxy + return proxy; +} + +function moveServerFrom(from, to, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } + + for (i = 0; i < to.length; i++) { + if (to[i].name === proxy.name) { + to.splice(i, 1); + } + } + + to.push(proxy); +} + +function removeProxyFrom(from, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } +} + +function reconnectProxies(self, proxies, callback) { + // Count lefts + var count = proxies.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return this.destroy(); + } + + if (event === 'connect' && !self.authenticating) { + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _self, function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return _self.destroy(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Move to the connected servers + moveServerFrom(self.connectingProxies, self.connectedProxies, _self); + // Emit topology Change + emitTopologyDescriptionChanged(self); + // Emit joined event + self.emit('joined', 'mongos', _self); + }); + } else { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + this.destroy(); + } + + // Are we done finish up callback + if (count === 0) { + callback(); + } + }; + }; + + // No new servers + if (count === 0) { + return callback(); + } + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.name.split(':')[0], + port: parseInt(_server.name.split(':')[1], 10), + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + destroyServer(_server); + removeProxyFrom(self.disconnectedProxies, _server); + + // Relay the server description change + relayEvents(server, self, ['serverDescriptionChanged']); + + // Emit opening server event + self.emit('serverOpening', { + topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, + address: server.name + }); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Connect to proxy + self.connectingProxies.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < proxies.length; i++) { + execute(proxies[i], i); + } +} + +function applyAuthenticationContexts(self, server, callback) { + if (self.s.authenticationContexts.length === 0) { + return callback(); + } + + // Copy contexts to ensure no modificiation in the middle of + // auth process. + var authContexts = self.s.authenticationContexts.slice(0); + + // Apply one of the contexts + function applyAuth(authContexts, server, callback) { + if (authContexts.length === 0) return callback(); + // Get the first auth context + var authContext = authContexts.shift(); + // Copy the params + var customAuthContext = authContext.slice(0); + // Push our callback handler + customAuthContext.push(function(/* err */) { + applyAuth(authContexts, server, callback); + }); + + // Attempt authentication + server.auth.apply(server, customAuthContext); + } + + // Apply all auth contexts + applyAuth(authContexts, server, callback); +} + +function topologyMonitor(self, options) { + options = options || {}; + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.isConnected() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } + + // Get the connectingServers + var proxies = self.connectedProxies.slice(0); + // Get the count + var count = proxies.length; + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + + // Execute ismaster + _server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // Move from connectingProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: _server.name + }); + // Move from connected proxies to disconnected proxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + _server.lastIsMasterMS = latencyMS; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: _server.name + }); + } + + cb(err, r); + } + ); + } + + // No proxies initiate monitor again + if (proxies.length === 0) { + // Emit close event if any listeners registered + if (self.listeners('close').length > 0 && self.state === CONNECTING) { + self.emit('error', new MongoError('no mongos proxy available')); + } else { + self.emit('close', self); + } + + // Attempt to connect to any unknown servers + return reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // Are we connected ? emit connect event + if (self.state === CONNECTING && options.firstConnect) { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.isConnected()) { + self.emit('reconnect', self); + } else if (!self.isConnected() && self.listeners('close').length > 0) { + self.emit('close', self); + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + + // Ping all servers + for (var i = 0; i < proxies.length; i++) { + pingServer(self, proxies[i], function() { + count = count - 1; + + if (count === 0) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // Attempt to connect to any unknown servers + reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Perform topology monitor + topologyMonitor(self); + }); + } + }); + } + }, self.s.haInterval); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Mongos.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + proxies.forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +Mongos.prototype.destroy = function(options) { + var self = this; + // Transition state + stateTransition(this, DESTROYED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + // Clear out authentication contexts + this.s.authenticationContexts = []; + + // Destroy all connecting servers + proxies.forEach(function(server) { + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: server.name + }); + + destroyServer(server, options); + + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, server); + }); + // Emit the final topology change + emitTopologyDescriptionChanged(self); + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.connectedProxies.length > 0; +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +// +// Operations +// + +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Pick a server + let server = pickProxy(self); + // No server found error out + if (!server) return callback(new MongoError('no mongos proxy available')); + + if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) { + // Execute the command + return server[op](ns, ops, options, callback); + } + + // increment and assign txnNumber + options.willRetryWrite = true; + options.session.incrementTransactionNumber(); + + server[op](ns, ops, options, (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + // Pick another server + server = pickProxy(self); + + // No server found error out with original error + if (!server || !isRetryableWritesSupported(server)) { + return callback(err); + } + + // rerun the operation + server[op](ns, ops, options, callback); + }); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'insert', ns, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'update', ns, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'remove', ns, ops, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Pick a proxy + var server = pickProxy(self); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // No server returned we had an error + if (server == null) { + return callback(new MongoError('no mongos proxy available')); + } + + // Cloned options + var clonedOptions = cloneOptions(options); + clonedOptions.topology = self; + + const willRetryWrite = + !options.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, clonedOptions, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, clonedOptions, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Mongos.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + var currentContextIndex = 0; + + // If we don't have the mechanism fail + if (this.authProviders[mechanism] == null && mechanism !== 'default') { + return callback(new MongoError(f('auth provider %s does not exist', mechanism))); + } + + // Are we already authenticating, throw + if (this.authenticating) { + return callback(new MongoError('authentication or logout allready in process')); + } + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!self.isConnected() && self.s.disconnectHandler != null) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } + + // Set to authenticating + this.authenticating = true; + // All errors + var errors = []; + + // Get all the servers + var servers = this.connectedProxies.slice(0); + // No servers return + if (servers.length === 0) { + this.authenticating = false; + callback(null, true); + } + + // Authenticate + function auth(server) { + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([ + function(err) { + count = count - 1; + // Save all the errors + if (err) errors.push({ name: server.name, err: err }); + // We are done + if (count === 0) { + // Auth is done + self.authenticating = false; + + // Return the auth error + if (errors.length) { + // Remove the entry from the stored authentication contexts + self.s.authenticationContexts.splice(currentContextIndex, 0); + // Return error + return callback( + new MongoError({ + message: 'authentication fail', + errors: errors + }), + false + ); + } + + // Successfully authenticated session + callback(null, self); + } + } + ]); + + // Execute the auth only against non arbiter servers + if (!server.lastIsMaster().arbiterOnly) { + server.auth.apply(server, finalArguments); + } + } + + // Save current context index + currentContextIndex = this.s.authenticationContexts.length; + // Store the auth context and return the last index + this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); + + // Get total count + var count = servers.length; + // Authenticate against all servers + while (servers.length > 0) { + auth(servers.shift()); + } +}; + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.logout = function(dbName, callback) { + var self = this; + // Are we authenticating or logging out, throw + if (this.authenticating) { + throw new MongoError('authentication or logout allready in process'); + } + + // Ensure no new members are processed while logging out + this.authenticating = true; + + // Remove from all auth providers (avoid any reaplication of the auth details) + var providers = Object.keys(this.authProviders); + for (var i = 0; i < providers.length; i++) { + this.authProviders[providers[i]].logout(dbName); + } + + // Now logout all the servers + var servers = this.connectedProxies.slice(0); + var count = servers.length; + if (count === 0) return callback(); + var errors = []; + + function logoutServer(_server, cb) { + _server.logout(dbName, function(err) { + if (err) errors.push({ name: _server.name, err: err }); + cb(); + }); + } + + // Execute logout on all server instances + for (i = 0; i < servers.length; i++) { + logoutServer(servers[i], function() { + count = count - 1; + + if (count === 0) { + // Do not block new operations + self.authenticating = false; + // If we have one or more errors + if (errors.length) + return callback( + new MongoError({ + message: f('logout failed against db %s', dbName), + errors: errors + }), + false + ); + + // No errors + callback(); + } + }); + } +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {function} callback + */ +Mongos.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = pickProxy(this); + if (this.s.debug) this.emit('pickedServer', null, server); + callback(null, server); +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + var connections = []; + + for (var i = 0; i < this.connectedProxies.length; i++) { + connections = connections.concat(this.connectedProxies[i].connections()); + } + + return connections; +}; + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + if (self.connectedProxies.length > 0) { + topology = 'Sharded'; + } + + // Generate description + var description = { + topologyType: topology, + servers: [] + }; + + // All proxies + var proxies = self.disconnectedProxies.concat(self.connectingProxies); + + // Add all the disconnected proxies + description.servers = description.servers.concat( + proxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Unknown'; + return description; + }) + ); + + // Add all the connected proxies + description.servers = description.servers.concat( + self.connectedProxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Mongos'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.topologyDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.topologyDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + if (diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + } + + // Set the new description + self.topologyDescription = description; + } +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A mongos reconnect event, used to verify that the mongos topology has reconnected + * + * @event Mongos#reconnect + * @type {Mongos} + */ + +/** + * A mongos fullsetup event, used to signal that all topology members have been contacted. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * A mongos all event, used to signal that all topology members have been contacted. + * + * @event Mongos#all + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event Mongos#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Mongos#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Mongos#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Mongos#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Mongos#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Mongos#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Mongos#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Mongos#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Mongos#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/read_preference.js b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..dda610c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,193 @@ +'use strict'; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @class + * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {array} tags The tags object + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. + * @return {ReadPreference} + * @example + * const ReplSet = require('mongodb-core').ReplSet, + * ReadPreference = require('mongodb-core').ReadPreference, + * assert = require('assert'); + * + * const server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * const cursor = server.cursor( + * 'db.test', + * { find: 'db.test', query: {} }, + * { readPreference: new ReadPreference('secondary') } + * ); + * + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +const ReadPreference = function(mode, tags, options) { + // TODO(major): tags MUST be an array of tagsets + if (tags && !Array.isArray(tags)) { + console.warn( + 'ReadPreference tags must be an array, this will change in the next major version' + ); + + if (typeof tags.maxStalenessSeconds !== 'undefined') { + // this is likely an options object + options = tags; + tags = undefined; + } else { + tags = [tags]; + } + } + + this.mode = mode; + this.tags = tags; + + options = options || {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new TypeError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY || this.mode === true) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new TypeError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + } +}; + +// Support the deprecated `preference` property introduced in the porcelain layer +Object.defineProperty(ReadPreference.prototype, 'preference', { + enumerable: true, + get: function() { + return this.mode; + } +}); + +/* + * Read preference mode constants + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest'; + +const VALID_MODES = [ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + true, + false, + null +]; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.isValid = function(mode) { + return VALID_MODES.indexOf(mode) !== -1; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.prototype.isValid = function(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); +}; + +const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * @method + * @return {boolean} + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.mode) !== -1; +}; + +/** + * Are the two read preference equal + * @method + * @param {ReadPreference} readPreference The read preference with which to check equality + * @return {boolean} True if the two ReadPreferences are equivalent + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.mode === this.mode; +}; + +/** + * Return JSON representation + * @method + * @return {Object} A JSON representation of the ReadPreference + */ +ReadPreference.prototype.toJSON = function() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + return readPreference; +}; + +/** + * Primary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset.js b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..dbb1604 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1724 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const ReadPreference = require('./read_preference'); +const BasicCursor = require('../cursor'); +const retrieveBSON = require('../connection/utils').retrieveBSON; +const Logger = require('../connection/logger'); +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const ReplSetState = require('./replset_state'); +const clone = require('./shared').clone; +const Timeout = require('./shared').Timeout; +const Interval = require('./shared').Interval; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; + +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; + +var BSON = retrieveBSON(); + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#failed + * @fires ReplSet#fullsetup + * @fires ReplSet#all + * @fires ReplSet#error + * @fires ReplSet#serverHeartbeatStarted + * @fires ReplSet#serverHeartbeatSucceeded + * @fires ReplSet#serverHeartbeatFailed + * @fires ReplSet#topologyOpening + * @fires ReplSet#topologyClosed + * @fires ReplSet#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); + // Validate list + if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); + // Validate entries + seedlist.forEach(function(e) { + if (typeof e.host !== 'string' || typeof e.port !== 'number') + throw new MongoError('seedlist entry must contain a host and port'); + }); + + // Add event listener + EventEmitter.call(this); + + // Get replSet Id + this.id = id++; + + // Get the localThresholdMS + var localThresholdMS = options.localThresholdMS || 15; + // Backward compatibility + if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; + + // Create a logger + var logger = Logger('ReplSet', options); + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // Logger instance + logger: logger, + // Seedlist + seedlist: seedlist, + // Replicaset state + replicaSetState: new ReplSetState({ + id: this.id, + setName: options.setName, + acceptableLatency: localThresholdMS, + heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, + logger: logger + }), + // Current servers we are connecting to + connectingServers: [], + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Minimum heartbeat frequency used if we detect a server close + minHeartbeatFrequencyMS: 500, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // Client info + clientInfo: createClientInfo(options), + // Authentication context + authenticationContexts: [] + }; + + // Add handler for topology change + this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { + self.emit('topologyDescriptionChanged', r); + }); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // All the authProviders + this.authProviders = options.authProviders || defaultAuthProviders(this.s.bson); + + // Add forwarding of events from state handler + var types = ['joined', 'left']; + types.forEach(function(x) { + self.s.replicaSetState.on(x, function(t, s) { + self.emit(x, t, s); + }); + }); + + // Connect stat + this.initialConnectState = { + connect: false, + fullsetup: false, + all: false + }; + + // Disconnected state + this.state = DISCONNECTED; + this.haTimeoutId = null; + // Are we authenticating + this.authenticating = false; + // Last ismaster + this.ismaster = null; + // Contains the intervalId + this.intervalIds = []; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; +}; + +inherits(ReplSet, EventEmitter); +Object.assign(ReplSet.prototype, SessionMixins); + +Object.defineProperty(ReplSet.prototype, 'type', { + enumerable: true, + get: function() { + return 'replset'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; + } +}); + +function rexecuteOperations(self) { + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary: true }); + } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary: true }); + } +} + +function connectNewServers(self, servers, callback) { + // Count lefts + var count = servers.length; + var error = null; + + // Handle events + var _handleEvent = function(self, event) { + return function(err) { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + if (event === 'connect' && !self.authenticating) { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _self.destroy({ force: true }); + } + + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _self, function() { + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _self.destroy({ force: true }); + } + + // Update the state + var result = self.s.replicaSetState.update(_self); + // Update the state with the new server + if (result) { + // Primary lastIsMaster store it + if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Enalbe the monitoring of the new server + monitorServer(_self.lastIsMaster().me, self, {}); + + // Rexecute any stalled operation + rexecuteOperations(self); + } else { + _self.destroy({ force: true }); + } + }); + } else if (event === 'connect' && self.authenticating) { + this.destroy({ force: true }); + } else if (event === 'error') { + error = err; + } + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Are we done finish up callback + if (count === 0) { + callback(error); + } + }; + }; + + // No new servers + if (count === 0) return callback(); + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.split(':')[0], + port: parseInt(_server.split(':')[1], 10), + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < servers.length; i++) { + execute(servers[i], i); + } +} + +// Ping the server +var pingServer = function(self, server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); + + // Execute ismaster + // Set the socketTimeout for a monitoring message to a low number + // Ensuring ismaster calls are timed out quickly + server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + server.destroy({ force: true }); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + // Set the last updatedTime + var hrTime = process.hrtime(); + // Calculate the last update time + server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: server.name + }); + + // Remove server from the state + self.s.replicaSetState.remove(server); + } else { + // Update the server ismaster + server.ismaster = r.result; + + // Check if we have a lastWriteDate convert it to MS + // and store on the server instance for later use + if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { + server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); + } + + // Do we have a brand new server + if (server.lastIsMasterMS === -1) { + server.lastIsMasterMS = latencyMS; + } else if (server.lastIsMasterMS) { + // After the first measurement, average RTT MUST be computed using an + // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. + // If the prior average is denoted old_rtt, then the new average (new_rtt) is + // computed from a new RTT measurement (x) using the following formula: + // alpha = 0.2 + // new_rtt = alpha * x + (1 - alpha) * old_rtt + server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; + } + + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: server.name + }); + } + + // Calculate the staleness for this server + self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); + + // Callback + cb(err, r); + } + ); +}; + +// Each server is monitored in parallel in their own timeout loop +var monitorServer = function(host, self, options) { + // If this is not the initial scan + // Is this server already being monitoried, then skip monitoring + if (!options.haInterval) { + for (var i = 0; i < self.intervalIds.length; i++) { + if (self.intervalIds[i].__host === host) { + return; + } + } + } + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + // Create the interval + var intervalId = new _process(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // clearInterval(intervalId); + intervalId.stop(); + return; + } + + // Do we already have server connection available for this host + var _server = self.s.replicaSetState.get(host); + + // Check if we have a known server connection and reuse + if (_server) { + // Ping the server + return pingServer(self, _server, function(err) { + if (err) { + // NOTE: should something happen here? + return; + } + + if (self.state === DESTROYED || self.state === UNREFERENCED) { + intervalId.stop(); + return; + } + + // Filter out all called intervaliIds + self.intervalIds = self.intervalIds.filter(function(intervalId) { + return intervalId.isRunning(); + }); + + // Initial sweep + if (_process === Timeout) { + if ( + self.state === CONNECTING && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + + // Start topology interval check + topologyMonitor(self, {}); + } + } else { + if ( + self.state === DISCONNECTED && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Emit connected sign + process.nextTick(function() { + self.emit('reconnect', self); + }); + } + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + }); + } + }, _haInterval); + + // Start the interval + intervalId.start(); + // Add the intervalId host name + intervalId.__host = host; + // Add the intervalId to our list of intervalIds + self.intervalIds.push(intervalId); +}; + +function topologyMonitor(self, options) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + options = options || {}; + + // Get the servers + var servers = Object.keys(self.s.replicaSetState.set); + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + if (_process === Timeout) { + return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { + // Don't emit errors if the connection was already + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no primary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no secondary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } + + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + }); + } else { + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + } + + // Run the reconnect process + function executeReconnect(self) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + var monitoringFrequencey = self.s.replicaSetState.hasPrimary() + ? _haInterval + : self.s.minHeartbeatFrequencyMS; + + // Create a timeout + self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); + }); + }; + } + + // Decide what kind of interval to use + var intervalTime = !self.s.replicaSetState.hasPrimary() + ? self.s.minHeartbeatFrequencyMS + : _haInterval; + + self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); +} + +function addServerToList(list, server) { + for (var i = 0; i < list.length; i++) { + if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; + } + + list.push(server); +} + +function handleEvent(self, event) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) + ); + } + + // Remove from the replicaset state + self.s.replicaSetState.remove(this); + + // Are we in a destroyed state return + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // If no primary and secondary available + if ( + !self.s.replicaSetState.hasPrimary() && + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + stateTransition(self, DISCONNECTED); + } else if (!self.s.replicaSetState.hasPrimary()) { + stateTransition(self, DISCONNECTED); + } + + addServerToList(self.s.connectingServers, this); + }; +} + +function applyAuthenticationContexts(self, server, callback) { + if (self.s.authenticationContexts.length === 0) { + return callback(); + } + + // Do not apply any auth contexts if it's an arbiter + if (server.lastIsMaster() && server.lastIsMaster().arbiterOnly) { + return callback(); + } + + // Copy contexts to ensure no modificiation in the middle of + // auth process. + var authContexts = self.s.authenticationContexts.slice(0); + + // Apply one of the contexts + function applyAuth(authContexts, server, callback) { + if (authContexts.length === 0) return callback(); + // Get the first auth context + var authContext = authContexts.shift(); + // Copy the params + var customAuthContext = authContext.slice(0); + // Push our callback handler + customAuthContext.push(function(/* err */) { + applyAuth(authContexts, server, callback); + }); + + // Attempt authentication + server.auth.apply(server, customAuthContext); + } + + // Apply all auth contexts + applyAuth(authContexts, server, callback); +} + +function shouldTriggerConnect(self) { + const isConnecting = self.state === CONNECTING; + const hasPrimary = self.s.replicaSetState.hasPrimary(); + const hasSecondary = self.s.replicaSetState.hasSecondary(); + const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; + const readPreferenceSecondary = + self.s.connectOptions.readPreference && + self.s.connectOptions.readPreference.equals(ReadPreference.secondary); + + return ( + (isConnecting && + ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || + (hasSecondary && secondaryOnlyConnectionAllowed) + ); +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s', + event, + this.name, + self.id + ) + ); + } + + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + // Check the type of server + if (event === 'connect') { + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _this, function() { + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _this.destroy({ force: true }); + } + + // Update the state + var result = self.s.replicaSetState.update(_this); + if (result === true) { + // Primary lastIsMaster store it + if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { + self.ismaster = _this.lastIsMaster(); + } + + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', + event, + _this.name, + self.id, + JSON.stringify(self.s.replicaSetState.set) + ) + ); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Do we have a primary or primaryAndSecondary + if (shouldTriggerConnect(self)) { + // We are connected + self.state = CONNECTED; + + // Set initial connect state + self.initialConnectState.connect = true; + // Emit connect event + process.nextTick(function() { + self.emit('connect', self); + }); + + topologyMonitor(self, {}); + } + } else if (result instanceof MongoError) { + _this.destroy({ force: true }); + self.destroy({ force: true }); + return self.emit('error', result); + } else { + _this.destroy({ force: true }); + } + }); + } else { + // Emit failure to connect + self.emit('failed', this); + + addServerToList(self.s.connectingServers, this); + // Remove from the state + self.s.replicaSetState.remove(this); + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + + // Remove from the list from connectingServers + for (var i = 0; i < self.s.connectingServers.length; i++) { + if (self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Trigger topologyMonitor + if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { + topologyMonitor(self, { haInterval: 1 }); + } + }; +} + +function connectServers(self, servers) { + // Update connectingServers + self.s.connectingServers = self.s.connectingServers.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add the server to the state + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +ReplSet.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server( + Object.assign({}, self.s.options, x, options, { + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + }); + + // Error out as high availbility interval must be < than socketTimeout + if ( + this.s.options.socketTimeout > 0 && + this.s.options.socketTimeout <= this.s.options.haInterval + ) { + return self.emit( + 'error', + new MongoError( + f( + 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', + this.s.options.haInterval, + this.s.options.socketTimeout + ) + ) + ); + } + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + // Start all server connections + connectServers(self, servers); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +ReplSet.prototype.destroy = function(options) { + options = options || {}; + // Transition state + stateTransition(this, DESTROYED); + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + // Destroy the replicaset + this.s.replicaSetState.destroy(options); + // Clear out authentication contexts + this.s.authenticationContexts = []; + + // Destroy all connecting servers + this.s.connectingServers.forEach(function(x) { + x.destroy(options); + }); + + // Clear out all monitoring + for (var i = 0; i < this.intervalIds.length; i++) { + this.intervalIds[i].stop(); + } + + // Reset list of intervalIds + this.intervalIds = []; + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); +}; + +/** + * Unref all connections belong to this server + * @method + */ +ReplSet.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + + this.s.replicaSetState.allServers().forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + // If secondaryOnlyConnectionAllowed and no primary but secondary + // return the secondaries ismaster result. + if ( + this.s.options.secondaryOnlyConnectionAllowed && + !this.s.replicaSetState.hasPrimary() && + this.s.replicaSetState.hasSecondary() + ) { + return this.s.replicaSetState.secondaries[0].lastIsMaster(); + } + + return this.s.replicaSetState.primary + ? this.s.replicaSetState.primary.lastIsMaster() + : this.ismaster; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + var servers = this.s.replicaSetState.allServers(); + var connections = []; + for (var i = 0; i < servers.length; i++) { + connections = connections.concat(servers[i].connections()); + } + + return connections; +}; + +/** + * Figure out if the server is connected + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we are authenticating signal not connected + // To avoid interleaving of operations + if (this.authenticating) return false; + + // If we specified a read preference check if we are connected to something + // than can satisfy this + if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { + return this.s.replicaSetState.hasSecondary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { + return this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { + return true; + } + + return this.s.replicaSetState.hasPrimary(); +}; + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {function} callback + */ +ReplSet.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = this.s.replicaSetState.pickServer(options.readPreference); + if (this.s.debug) this.emit('pickedServer', options.readPreference, server); + callback(null, server); +}; + +/** + * Get all connected servers + * @method + * @return {Server[]} + */ +ReplSet.prototype.getServers = function() { + return this.s.replicaSetState.allServers(); +}; + +// +// Execute write operation +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + if (self.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + if (!self.s.replicaSetState.hasPrimary()) { + if (self.s.disconnectHandler) { + // Not connected but we have a disconnecthandler + return self.s.disconnectHandler.add(op, ns, ops, options, callback); + } else if (!willRetryWrite) { + // No server returned we had an error + return callback(new MongoError('no primary server found')); + } + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + // Per SDAM, remove primary from replicaset + if (self.s.replicaSetState.primary) { + self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + self.s.replicaSetState.primary[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Establish readPreference + var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + + // If the readPreference is primary and we have no primary, store it + if ( + readPreference.preference === 'primary' && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference === 'secondary' && + !this.s.replicaSetState.hasSecondary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference !== 'primary' && + !this.s.replicaSetState.hasSecondary() && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // Pick a server + var server = this.s.replicaSetState.pickServer(readPreference); + // We received an error, return it + if (!(server instanceof Server)) return callback(server); + // Emit debug event + if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + + // No server returned we had an error + if (server == null) { + return callback( + new MongoError( + f('no server found that matches the provided readPreference %s', readPreference) + ) + ); + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + // Per SDAM, remove primary from replicaset + if (this.s.replicaSetState.primary) { + this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, options, cb); +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + var currentContextIndex = 0; + + // If we don't have the mechanism fail + if (this.authProviders[mechanism] == null && mechanism !== 'default') { + return callback(new MongoError(f('auth provider %s does not exist', mechanism))); + } + + // Are we already authenticating, throw + if (this.authenticating) { + return callback(new MongoError('authentication or logout allready in process')); + } + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!this.isConnected() && self.s.disconnectHandler != null) { + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } + } + + // Set to authenticating + this.authenticating = true; + // All errors + var errors = []; + + // Get all the servers + var servers = this.s.replicaSetState.allServers(); + // No servers return + if (servers.length === 0) { + this.authenticating = false; + callback(null, true); + } + + // Authenticate + function auth(server) { + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([ + function(err) { + count = count - 1; + // Save all the errors + if (err) errors.push({ name: server.name, err: err }); + // We are done + if (count === 0) { + // Auth is done + self.authenticating = false; + + // Return the auth error + if (errors.length) { + // Remove the entry from the stored authentication contexts + self.s.authenticationContexts.splice(currentContextIndex, 0); + // Return error + return callback( + new MongoError({ + message: 'authentication fail', + errors: errors + }), + false + ); + } + + // Successfully authenticated session + callback(null, self); + } + } + ]); + + if (!server.lastIsMaster().arbiterOnly) { + // Execute the auth only against non arbiter servers + server.auth.apply(server, finalArguments); + } else { + // If we are authenticating against an arbiter just ignore it + finalArguments.pop()(null); + } + } + + // Get total count + var count = servers.length; + + // Save current context index + currentContextIndex = this.s.authenticationContexts.length; + + // Store the auth context and return the last index + this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); + + // Authenticate against all servers + while (servers.length > 0) { + auth(servers.shift()); + } +}; + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.logout = function(dbName, callback) { + var self = this; + // Are we authenticating or logging out, throw + if (this.authenticating) { + throw new MongoError('authentication or logout allready in process'); + } + + // Ensure no new members are processed while logging out + this.authenticating = true; + + // Remove from all auth providers (avoid any reaplication of the auth details) + var providers = Object.keys(this.authProviders); + for (var i = 0; i < providers.length; i++) { + this.authProviders[providers[i]].logout(dbName); + } + + // Clear out any contexts associated with the db + self.s.authenticationContexts = self.s.authenticationContexts.filter(function(context) { + return context[1] !== dbName; + }); + + // Now logout all the servers + var servers = this.s.replicaSetState.allServers(); + var count = servers.length; + if (count === 0) return callback(); + var errors = []; + + function logoutServer(_server, cb) { + _server.logout(dbName, function(err) { + if (err) errors.push({ name: _server.name, err: err }); + cb(); + }); + } + + // Execute logout on all server instances + for (i = 0; i < servers.length; i++) { + logoutServer(servers[i], function() { + count = count - 1; + + if (count === 0) { + // Do not block new operations + self.authenticating = false; + // If we have one or more errors + if (errors.length) + return callback( + new MongoError({ + message: f('logout failed against db %s', dbName), + errors: errors + }), + false + ); + + // No errors + callback(); + } + }); + } +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); +}; + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * A replset reconnect event, used to verify that the topology reconnected + * + * @event ReplSet#reconnect + * @type {ReplSet} + */ + +/** + * A replset fullsetup event, used to signal that all topology members have been contacted. + * + * @event ReplSet#fullsetup + * @type {ReplSet} + */ + +/** + * A replset all event, used to signal that all topology members have been contacted. + * + * @event ReplSet#all + * @type {ReplSet} + */ + +/** + * A replset failed event, used to signal that initial replset connection failed. + * + * @event ReplSet#failed + * @type {ReplSet} + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event ReplSet#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event ReplSet#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event ReplSet#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event ReplSet#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event ReplSet#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event ReplSet#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event ReplSet#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event ReplSet#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event ReplSet#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset_state.js b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..4745173 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,1099 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + diff = require('./shared').diff, + EventEmitter = require('events').EventEmitter, + Logger = require('../connection/logger'), + ReadPreference = require('./read_preference'), + MongoError = require('../error').MongoError, + Buffer = require('safe-buffer').Buffer; + +var TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +var ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +var ReplSetState = function(options) { + options = options || {}; + // Add event listener + EventEmitter.call(this); + // Topology state + this.topologyType = TopologyType.ReplicaSetNoPrimary; + this.setName = options.setName; + + // Server set + this.set = {}; + + // Unpacked options + this.id = options.id; + this.setName = options.setName; + + // Replicaset logger + this.logger = options.logger || Logger('ReplSet', options); + + // Server selection index + this.index = 0; + // Acceptable latency + this.acceptableLatency = options.acceptableLatency || 15; + + // heartbeatFrequencyMS + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + // Server side + this.primary = null; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + // Current unknown hosts + this.unknownServers = []; + // In set status + this.set = {}; + // Status + this.maxElectionId = null; + this.maxSetVersion = 0; + // Description of the Replicaset + this.replicasetDescription = { + topologyType: 'Unknown', + servers: [] + }; + + this.logicalSessionTimeoutMinutes = undefined; +}; + +inherits(ReplSetState, EventEmitter); + +ReplSetState.prototype.hasPrimaryAndSecondary = function() { + return this.primary != null && this.secondaries.length > 0; +}; + +ReplSetState.prototype.hasPrimaryOrSecondary = function() { + return this.hasPrimary() || this.hasSecondary(); +}; + +ReplSetState.prototype.hasPrimary = function() { + return this.primary != null; +}; + +ReplSetState.prototype.hasSecondary = function() { + return this.secondaries.length > 0; +}; + +ReplSetState.prototype.get = function(host) { + var servers = this.allServers(); + + for (var i = 0; i < servers.length; i++) { + if (servers[i].name.toLowerCase() === host.toLowerCase()) { + return servers[i]; + } + } + + return null; +}; + +ReplSetState.prototype.allServers = function(options) { + options = options || {}; + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + return servers; +}; + +ReplSetState.prototype.destroy = function(options) { + // Destroy all sockets + if (this.primary) this.primary.destroy(options); + this.secondaries.forEach(function(x) { + x.destroy(options); + }); + this.arbiters.forEach(function(x) { + x.destroy(options); + }); + this.passives.forEach(function(x) { + x.destroy(options); + }); + this.ghosts.forEach(function(x) { + x.destroy(options); + }); + // Clear out the complete state + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + this.unknownServers = []; + this.set = {}; + this.primary = null; + // Emit the topology changed + emitTopologyDescriptionChanged(this); +}; + +ReplSetState.prototype.remove = function(server, options) { + options = options || {}; + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // Only remove if the current server is not connected + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + + // Check if it's active and this is just a failed connection attempt + for (var i = 0; i < servers.length; i++) { + if ( + !options.force && + servers[i].equals(server) && + servers[i].isConnected && + servers[i].isConnected() + ) { + return; + } + } + + // If we have it in the set remove it + if (this.set[serverName]) { + this.set[serverName].type = ServerType.Unknown; + this.set[serverName].electionId = null; + this.set[serverName].setName = null; + this.set[serverName].setVersion = null; + } + + // Remove type + var removeType = null; + + // Remove from any lists + if (this.primary && this.primary.equals(server)) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + removeType = 'primary'; + } + + // Remove from any other server lists + removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; + removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; + removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; + removeFrom(server, this.ghosts); + removeFrom(server, this.unknownServers); + + // Push to unknownServers + this.unknownServers.push(serverName); + + // Do we have a removeType + if (removeType) { + this.emit('left', removeType, server); + } +}; + +const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; + +ReplSetState.prototype.update = function(server) { + var self = this; + // Get the current ismaster + var ismaster = server.lastIsMaster(); + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // + // Add any hosts + // + if (ismaster) { + // Join all the possible new hosts + var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; + hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); + hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); + hosts = hosts.map(function(s) { + return s.toLowerCase(); + }); + + // Add all hosts as unknownServers + for (var i = 0; i < hosts.length; i++) { + // Add to the list of unknown server + if ( + this.unknownServers.indexOf(hosts[i]) === -1 && + (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) + ) { + this.unknownServers.push(hosts[i].toLowerCase()); + } + + if (!this.set[hosts[i]]) { + this.set[hosts[i]] = { + type: ServerType.Unknown, + electionId: null, + setName: null, + setVersion: null + }; + } + } + } + + // + // Unknown server + // + if (!ismaster && !inList(ismaster, server, this.unknownServers)) { + self.set[serverName] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + // Update set information about the server instance + self.set[serverName].type = ServerType.Unknown; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + + if (self.unknownServers.indexOf(server.name) === -1) { + self.unknownServers.push(serverName); + } + + // Set the topology + return false; + } + + // Update logicalSessionTimeoutMinutes + if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { + if ( + self.logicalSessionTimeoutMinutes === undefined || + ismaster.logicalSessionTimeoutMinutes === null + ) { + self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } else { + self.logicalSessionTimeoutMinutes = Math.min( + self.logicalSessionTimeoutMinutes, + ismaster.logicalSessionTimeoutMinutes + ); + } + } + + // + // Is this a mongos + // + if (ismaster && ismaster.msg === 'isdbgrid') { + return false; + } + + // A RSOther instance + if ( + (ismaster.setName && ismaster.hidden) || + (ismaster.setName && + !ismaster.ismaster && + !ismaster.secondary && + !ismaster.arbiterOnly && + !ismaster.passive) + ) { + self.set[serverName] = { + type: ServerType.RSOther, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + return false; + } + + // A RSGhost instance + if (ismaster.isreplicaset) { + self.set[serverName] = { + type: ServerType.RSGhost, + setVersion: null, + electionId: null, + setName: null + }; + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + + // Set the topology + return false; + } + + // + // Standalone server, destroy and return + // + if (ismaster && ismaster.ismaster && !ismaster.setName) { + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; + this.remove(server, { force: true }); + return false; + } + + // + // Server in maintanance mode + // + if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + this.remove(server, { force: true }); + return false; + } + + // + // If the .me field does not match the passed in server + // + if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { + if (this.logger.isWarn()) { + this.logger.warn( + f( + 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', + server.name, + ismaster.me + ) + ); + } + + // Delete from the set + delete this.set[serverName]; + // Delete unknown servers + removeFrom(server, self.unknownServers); + + // Destroy the instance + server.destroy(); + + // Set the type of topology we have + if (this.primary && !this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + // + // We have a potential primary + // + if (!this.primary && ismaster.primary) { + this.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setName: null, + electionId: null, + setVersion: null + }; + } + + return false; + } + + // + // Primary handling + // + if (!this.primary && ismaster.ismaster && ismaster.setName) { + var ismasterElectionId = server.lastIsMaster().electionId; + if (this.setName && this.setName !== ismaster.setName) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return new MongoError( + f( + 'setName from ismaster does not match provided connection setName [%s] != [%s]', + ismaster.setName, + this.setName + ) + ); + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + var result = compareObjectIds(this.maxElectionId, ismasterElectionId); + // Get the electionIds + var ismasterSetVersion = server.lastIsMaster().setVersion; + + if (result === 1) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } else if (result === 0 && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + } + + this.maxSetVersion = ismasterSetVersion; + this.maxElectionId = ismasterElectionId; + } + + // Hande normalization of server names + var normalizedHosts = ismaster.hosts.map(function(x) { + return x.toLowerCase(); + }); + var locationIndex = normalizedHosts.indexOf(serverName); + + // Validate that the server exists in the host list + if (locationIndex !== -1) { + self.primary = server; + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + emitTopologyDescriptionChanged(self); + return true; + } else if (ismaster.ismaster && ismaster.setName) { + // Get the electionIds + var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; + var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; + var currentSetName = self.set[self.primary.name.toLowerCase()].setName; + ismasterElectionId = server.lastIsMaster().electionId; + ismasterSetVersion = server.lastIsMaster().setVersion; + var ismasterSetName = server.lastIsMaster().setName; + + // Is it the same server instance + if (this.primary.equals(server) && currentSetName === ismasterSetName) { + return false; + } + + // If we do not have the same rs name + if (currentSetName && currentSetName !== ismasterSetName) { + if (!this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // Check if we need to replace the server + if (currentElectionId && ismasterElectionId) { + result = compareObjectIds(currentElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion > ismasterSetVersion) { + return false; + } + } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + result = compareObjectIds(this.maxElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } else { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + this.maxElectionId = ismasterElectionId; + this.maxSetVersion = ismasterSetVersion; + } else { + this.maxSetVersion = ismasterSetVersion; + } + + // Modify the entry to unknown + self.set[self.primary.name.toLowerCase()] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + + // Signal primary left + self.emit('left', 'primary', this.primary); + // Destroy the instance + self.primary.destroy(); + // Set the new instance + self.primary = server; + // Set the set information + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // A possible instance + if (!this.primary && ismaster.primary) { + self.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setVersion: null, + electionId: null, + setName: null + }; + } + + // + // Secondary handling + // + if ( + ismaster.secondary && + ismaster.setName && + !inList(ismaster, server, this.secondaries) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy(); + this.primary = null; + self.emit('left', 'primary', server); + } + + // Emit secondary joined replicaset + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Arbiter handling + // + if ( + isArbiter(ismaster) && + !inList(ismaster, server, this.arbiters) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + self.emit('joined', 'arbiter', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Passive handling + // + if ( + ismaster.passive && + ismaster.setName && + !inList(ismaster, server, this.passives) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy(); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Remove the primary + // + if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { + self.emit('left', 'primary', this.primary); + this.primary.destroy(); + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + return false; +}; + +/** + * Recalculate single server max staleness + * @method + */ +ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { + // Locate the max secondary lastwrite + var max = 0; + // Go over all secondaries + for (var i = 0; i < this.secondaries.length; i++) { + max = Math.max(max, this.secondaries[i].lastWriteDate); + } + + // Perform this servers staleness calculation + if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { + server.staleness = + server.lastUpdateTime - + server.lastWriteDate - + (this.primary.lastUpdateTime - this.primary.lastWriteDate) + + haInterval; + } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { + server.staleness = max - server.lastWriteDate + haInterval; + } +}; + +/** + * Recalculate all the staleness values for secodaries + * @method + */ +ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { + for (var i = 0; i < this.secondaries.length; i++) { + this.updateServerMaxStaleness(this.secondaries[i], haInterval); + } +}; + +/** + * Pick a server by the passed in ReadPreference + * @method + * @param {ReadPreference} readPreference The ReadPreference instance to use + */ +ReplSetState.prototype.pickServer = function(readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // maxStalenessSeconds is not allowed with a primary read + if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { + return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); + } + + // Check if we have any non compatible servers for maxStalenessSeconds + var allservers = this.primary ? [this.primary] : []; + allservers = allservers.concat(this.secondaries); + + // Does any of the servers not support the right wire protocol version + // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out + if (readPreference.maxStalenessSeconds != null) { + for (var i = 0; i < allservers.length; i++) { + if (allservers[i].ismaster.maxWireVersion < 5) { + return new MongoError( + 'maxStalenessSeconds not supported by at least one of the replicaset members' + ); + } + } + } + + // Do we have the nearest readPreference + if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { + return pickNearest(this, readPreference); + } else if ( + readPreference.preference === 'nearest' && + readPreference.maxStalenessSeconds != null + ) { + return pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Get all the secondaries + var secondaries = this.secondaries; + + // Check if we can satisfy and of the basic read Preferences + if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { + return new MongoError('no secondary server available'); + } + + if ( + readPreference.equals(ReadPreference.secondaryPreferred) && + secondaries.length === 0 && + this.primary == null + ) { + return new MongoError('no secondary or primary server available'); + } + + if (readPreference.equals(ReadPreference.primary) && this.primary == null) { + return new MongoError('no primary server available'); + } + + // Secondary preferred or just secondaries + if ( + readPreference.equals(ReadPreference.secondaryPreferred) || + readPreference.equals(ReadPreference.secondary) + ) { + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + // Pick nearest of any other servers available + var server = pickNearest(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + // Pick nearest of any other servers available + server = pickNearestMaxStalenessSeconds(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } + + if (readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.primary; + } + + return null; + } + + // Primary preferred + if (readPreference.equals(ReadPreference.primaryPreferred)) { + server = null; + + // We prefer the primary if it's available + if (this.primary) { + return this.primary; + } + + // Pick a secondary + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + server = pickNearest(this, readPreference); + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + server = pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Did we find a server + if (server) return server; + } + + // Return the primary + return this.primary; +}; + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if (readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; + + // Iterate over the tags + for (var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for (var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + + // Did we find the a matching server + var found = true; + // Check if the server is valid + for (var name in tags) { + if (serverTag[name] !== tags[name]) { + found = false; + } + } + + // Add to candidate list + if (found) { + filteredServers.push(servers[i]); + } + } + } + + // Returned filtered servers + return filteredServers; +}; + +function pickNearestMaxStalenessSeconds(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Get the maxStalenessMS + var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; + + // Check if the maxStalenessMS > 90 seconds + if (maxStalenessMS < 90 * 1000) { + return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); + } + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Filter by latency + servers = servers.filter(function(s) { + return s.staleness <= maxStalenessMS; + }); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function pickNearest(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.lastIsMasterMS <= lowest + self.acceptableLatency; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function inList(ismaster, server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) + return true; + } + + return false; +} + +function addToList(self, type, ismaster, server, list) { + var serverName = server.name.toLowerCase(); + // Update set information about the server instance + self.set[serverName].type = type; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + // Add to the list + list.push(server); +} + +function compareObjectIds(id1, id2) { + var a = Buffer.from(id1.toHexString(), 'hex'); + var b = Buffer.from(id2.toHexString(), 'hex'); + + if (a === b) { + return 0; + } + + if (typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +function removeFrom(server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i].equals && list[i].equals(server)) { + list.splice(i, 1); + return true; + } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { + list.splice(i, 1); + return true; + } + } + + return false; +} + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + var setName = self.setName; + + if (self.hasPrimaryAndSecondary()) { + topology = 'ReplicaSetWithPrimary'; + } else if (!self.hasPrimary() && self.hasSecondary()) { + topology = 'ReplicaSetNoPrimary'; + } + + // Generate description + var description = { + topologyType: topology, + setName: setName, + servers: [] + }; + + // Add the primary to the list + if (self.hasPrimary()) { + var desc = self.primary.getDescription(); + desc.type = 'RSPrimary'; + description.servers.push(desc); + } + + // Add all the secondaries + description.servers = description.servers.concat( + self.secondaries.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Add all the arbiters + description.servers = description.servers.concat( + self.arbiters.map(function(x) { + var description = x.getDescription(); + description.type = 'RSArbiter'; + return description; + }) + ); + + // Add all the passives + description.servers = description.servers.concat( + self.passives.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.replicasetDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.replicasetDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + // if(diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + // } + + // Set the new description + self.replicasetDescription = description; + } +} + +module.exports = ReplSetState; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..43d1cfc --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1117 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + ReadPreference = require('./read_preference'), + Logger = require('../connection/logger'), + debugOptions = require('../connection/utils').debugOptions, + retrieveBSON = require('../connection/utils').retrieveBSON, + Pool = require('../connection/pool'), + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError, + MongoNetworkError = require('../error').MongoNetworkError, + TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'), + ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'), + BasicCursor = require('../cursor'), + sdam = require('./shared'), + createClientInfo = require('./shared').createClientInfo, + createCompressionInfo = require('./shared').createCompressionInfo, + resolveClusterTime = require('./shared').resolveClusterTime, + SessionMixins = require('./shared').SessionMixins, + relayEvents = require('../utils').relayEvents; + +const collationNotSupported = require('../utils').collationNotSupported; + +function getSaslSupportedMechs(options) { + if (!options) { + return {}; + } + + const authArray = options.auth || []; + const authMechanism = authArray[0] || options.authMechanism; + const authSource = authArray[1] || options.authSource || options.dbName || 'admin'; + const user = authArray[2] || options.user; + + if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { + return {}; + } + + if (!user) { + return {}; + } + + return { saslSupportedMechs: `${authSource}.${user}` }; +} + +function getDefaultAuthMechanism(ismaster) { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 + ? 'scram-sha-256' + : 'scram-sha-1'; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return 'scram-sha-1'; + } + } + + // Default for wireprotocol < 3 + return 'mongocr'; +} + +function extractIsMasterError(err, result) { + if (err) { + return err; + } + + if (result && result.result && result.result.ok === 0) { + return new MongoError(result.result); + } +} + +// Used for filtering out fields for loggin +var debugFields = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'singleBufferSerializtion', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +// Server instance id +var id = 0; +var serverAccounting = false; +var servers = {}; +var BSON = retrieveBSON(); + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) + * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#reconnectFailed + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + * @fires Server#topologyOpening + * @fires Server#topologyClosed + * @fires Server#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Server = function(options) { + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Server instance id + this.id = id++; + + // Internal state + this.s = { + // Options + options: options, + // Logger + logger: Logger('Server', options), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Pool + pool: null, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Monitor thread (keeps the connection alive) + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, + // Is the server in a topology + inTopology: !!options.parent, + // Monitoring timeout + monitoringInterval: + typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, + // Topology id + topologyId: -1, + compression: { compressors: createCompressionInfo(options) }, + // Optional parent topology + parent: options.parent + }; + + // If this is a single deployment we need to track the clusterTime here + if (!this.s.parent) { + this.s.clusterTime = null; + } + + // Curent ismaster + this.ismaster = null; + // Current ping time + this.lastIsMasterMS = -1; + // The monitoringProcessId + this.monitoringProcessId = null; + // Initial connection + this.initialConnect = true; + // Wire protocol handler, default to oldest known protocol handler + // this gets changed when the first ismaster is called. + this.wireProtocolHandler = new TwoSixWireProtocolSupport(); + // Default type + this._type = 'server'; + // Set the client info + this.clientInfo = createClientInfo(options); + + // Max Stalleness values + // last time we updated the ismaster state + this.lastUpdateTime = 0; + // Last write time + this.lastWriteDate = 0; + // Stalleness + this.staleness = 0; +}; + +inherits(Server, EventEmitter); +Object.assign(Server.prototype, SessionMixins); + +Object.defineProperty(Server.prototype, 'type', { + enumerable: true, + get: function() { + return this._type; + } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +// In single server deployments we track the clusterTime directly on the topology, however +// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the +// tracking objects so we can ensure we are gossiping the maximum time received from the +// server. +Object.defineProperty(Server.prototype, 'clusterTime', { + enumerable: true, + set: function(clusterTime) { + const settings = this.s.parent ? this.s.parent : this.s; + resolveClusterTime(settings, clusterTime); + }, + get: function() { + const settings = this.s.parent ? this.s.parent : this.s; + return settings.clusterTime || null; + } +}); + +Server.enableServerAccounting = function() { + serverAccounting = true; + servers = {}; +}; + +Server.disableServerAccounting = function() { + serverAccounting = false; +}; + +Server.servers = function() { + return servers; +}; + +Object.defineProperty(Server.prototype, 'name', { + enumerable: true, + get: function() { + return this.s.options.host + ':' + this.s.options.port; + } +}); + +function isSupportedServer(response) { + return response && typeof response.maxWireVersion === 'number' && response.maxWireVersion >= 2; +} + +function configureWireProtocolHandler(self, ismaster) { + // 3.2 wire protocol handler + if (ismaster.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(); + } + + // default to 2.6 wire protocol handler + return new TwoSixWireProtocolSupport(); +} + +function disconnectHandler(self, type, ns, cmd, options, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ( + !self.s.pool.isConnected() && + self.s.options.reconnect && + self.s.disconnectHandler != null && + !options.monitoring + ) { + self.s.disconnectHandler.add(type, ns, cmd, options, callback); + return true; + } + + // If we have no connection error + if (!self.s.pool.isConnected()) { + callback(new MongoError(f('no connection available to server %s', self.name))); + return true; + } +} + +function monitoringProcess(self) { + return function() { + // Pool was destroyed do not continue process + if (self.s.pool.isDestroyed()) return; + // Emit monitoring Process event + self.emit('monitoring', self); + // Perform ismaster call + // Query options + var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + // Create a query instance + var query = new Query(self.s.bson, 'admin.$cmd', { ismaster: true }, queryOptions); + // Get start time + var start = new Date().getTime(); + + // Execute the ismaster query + self.s.pool.write( + query, + { + socketTimeout: + typeof self.s.options.connectionTimeout !== 'number' + ? 2000 + : self.s.options.connectionTimeout, + monitoring: true + }, + function(err, result) { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if (self.s.pool.isDestroyed()) return; + // Update the ismaster view if we have a result + if (result) { + self.ismaster = result.result; + } + // Re-schedule the monitoring process + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + ); + }; +} + +var eventHandler = function(self, event) { + return function(err) { + // Log information of received information if in info mode + if (self.s.logger.isInfo()) { + var object = err instanceof MongoError ? JSON.stringify(err) : {}; + self.s.logger.info( + f('server %s fired event %s out with message %s', self.name, event, object) + ); + } + + // Handle connect event + if (event === 'connect') { + // Issue an ismaster command at connect + // Query options + var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + // Create a query instance + var compressors = + self.s.compression && self.s.compression.compressors ? self.s.compression.compressors : []; + var query = new Query( + self.s.bson, + 'admin.$cmd', + Object.assign( + { ismaster: true, client: self.clientInfo, compression: compressors }, + getSaslSupportedMechs(self.s.options) + ), + queryOptions + ); + // Get start time + var start = new Date().getTime(); + // Execute the ismaster query + self.s.pool.write( + query, + { + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, result) { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + + const serverError = extractIsMasterError(err, result); + + if (serverError) { + self.destroy(); + return self.emit('error', serverError); + } + + if (!isSupportedServer(result.result)) { + self.destroy(); + const latestSupportedVersion = '2.6'; + const message = + 'Server at ' + + self.s.options.host + + ':' + + self.s.options.port + + ' reports wire version ' + + (result.result.maxWireVersion || 0) + + ', but this version of Node.js Driver requires at least 2 (MongoDB' + + latestSupportedVersion + + ').'; + return self.emit('error', new MongoError(message), self); + } + + // Determine whether the server is instructing us to use a compressor + if (result.result && result.result.compression) { + for (var i = 0; i < self.s.compression.compressors.length; i++) { + if (result.result.compression.indexOf(self.s.compression.compressors[i]) > -1) { + self.s.pool.options.agreedCompressor = self.s.compression.compressors[i]; + break; + } + } + + if (self.s.compression.zlibCompressionLevel) { + self.s.pool.options.zlibCompressionLevel = self.s.compression.zlibCompressionLevel; + } + } + + // Ensure no error emitted after initial connect when reconnecting + self.initialConnect = false; + // Save the ismaster + self.ismaster = result.result; + + // It's a proxy change the type so + // the wireprotocol will send $readPreference + if (self.ismaster.msg === 'isdbgrid') { + self._type = 'mongos'; + } + // Add the correct wire protocol handler + self.wireProtocolHandler = configureWireProtocolHandler(self, self.ismaster); + // Have we defined self monitoring + if (self.s.monitoring) { + self.monitoringProcessId = setTimeout( + monitoringProcess(self), + self.s.monitoringInterval + ); + } + + // Emit server description changed if something listening + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + + if (!self.s.inTopology) { + // Emit topology description changed if something listening + sdam.emitTopologyDescriptionChanged(self, { + topologyType: 'Single', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + } + ] + }); + } + + // Log the ismaster if available + if (self.s.logger.isInfo()) { + self.s.logger.info( + f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) + ); + } + + // Emit connect + self.emit('connect', self); + } + ); + } else if ( + event === 'error' || + event === 'parseError' || + event === 'close' || + event === 'timeout' || + event === 'reconnect' || + event === 'attemptReconnect' || + 'reconnectFailed' + ) { + // Remove server instance from accounting + if ( + serverAccounting && + ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 + ) { + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + self.emit('topologyOpening', { topologyId: self.id }); + } + + delete servers[self.id]; + } + + if (event === 'close') { + // Closing emits a server description changed event going to unknown. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }); + } + + // Reconnect failed return error + if (event === 'reconnectFailed') { + self.emit('reconnectFailed', err); + // Emit error if any listeners + if (self.listeners('error').length > 0) { + self.emit('error', err); + } + // Terminate + return; + } + + // On first connect fail + if ( + self.s.pool.state === 'disconnected' && + self.initialConnect && + ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 + ) { + self.initialConnect = false; + return self.emit( + 'error', + new MongoNetworkError( + f('failed to connect to server [%s] on first connect [%s]', self.name, err) + ) + ); + } + + // Reconnect event, emit the server + if (event === 'reconnect') { + // Reconnecting emits a server description changed event going from unknown to the + // current server type. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + return self.emit(event, self); + } + + // Emit the event + self.emit(event, err); + } + }; +}; + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +Server.prototype.connect = function(options) { + var self = this; + options = options || {}; + + // Set the connections + if (serverAccounting) servers[this.id] = this; + + // Do not allow connect to be called on anything that's not disconnected + if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { + throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); + } + + // Create a pool + self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); + + // Set up listeners + self.s.pool.on('close', eventHandler(self, 'close')); + self.s.pool.on('error', eventHandler(self, 'error')); + self.s.pool.on('timeout', eventHandler(self, 'timeout')); + self.s.pool.on('parseError', eventHandler(self, 'parseError')); + self.s.pool.on('connect', eventHandler(self, 'connect')); + self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); + self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); + + // Set up listeners for command monitoring + relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + this.emit('topologyOpening', { topologyId: self.id }); + } + + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Connect with optional auth settings + if (options.auth) { + self.s.pool.connect.apply(self.s.pool, options.auth); + } else { + self.s.pool.connect(); + } +}; + +/** + * Get the server description + * @method + * @return {object} + */ +Server.prototype.getDescription = function() { + var ismaster = this.ismaster || {}; + var description = { + type: sdam.getTopologyType(this), + address: this.name + }; + + // Add fields if available + if (ismaster.hosts) description.hosts = ismaster.hosts; + if (ismaster.arbiters) description.arbiters = ismaster.arbiters; + if (ismaster.passives) description.passives = ismaster.passives; + if (ismaster.setName) description.setName = ismaster.setName; + return description; +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Server.prototype.unref = function() { + this.s.pool.unref(); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + if (!this.s.pool) return false; + return this.s.pool.isConnected(); +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + if (!this.s.pool) return false; + return this.s.pool.isDestroyed(); +}; + +function basicWriteValidations(self) { + if (!self.s.pool) return new MongoError('server instance is not connected'); + if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); +} + +function basicReadValidations(self, options) { + basicWriteValidations(self, options); + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error('readPreference must be an instance of ReadPreference'); + } +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicReadValidations(self, options); + if (result) return callback(result); + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (self.s.logger.isDebug()) + self.s.logger.debug( + f( + 'executing command [%s] against %s', + JSON.stringify({ + ns: ns, + cmd: cmd, + options: debugOptions(debugFields, options) + }), + self.name + ) + ); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + self.wireProtocolHandler.command(self, ns, cmd, options, callback); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return self.wireProtocolHandler.insert(self, ns, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.wireProtocolHandler.update(self, ns, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.wireProtocolHandler.remove(self, ns, ops, options, callback); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Server.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); +}; + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +Server.prototype.logout = function(dbName, callback) { + this.s.pool.logout(dbName, callback); +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + var self = this; + + if (mechanism === 'default') { + mechanism = getDefaultAuthMechanism(self.ismaster); + } + + // Slice all the arguments off + var args = Array.prototype.slice.call(arguments, 0); + // Set the mechanism + args[0] = mechanism; + // Get the callback + var callback = args[args.length - 1]; + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'auth', db, args, {}, callback)) { + return; + } + + // Do not authenticate if we are an arbiter + if (this.lastIsMaster() && this.lastIsMaster().arbiterOnly) { + return callback(null, true); + } + + // Apply the arguments to the pool + self.s.pool.auth.apply(self.s.pool, args); +}; + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); + if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); + return false; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.allConnections(); +}; + +/** + * Selects a server + * @return {Server} + */ +Server.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + + callback(null, this); +}; + +var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; + +/** + * Destroy the server connection + * @method + * @param {boolean} [options.emitClose=false] Emit close event on destroy + * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {boolean} [options.force=false] Force destroy the pool + */ +Server.prototype.destroy = function(options) { + if (this._destroyed) return; + + options = options || {}; + var self = this; + + // Set the connections + if (serverAccounting) delete servers[this.id]; + + // Destroy the monitoring process if any + if (this.monitoringProcessId) { + clearTimeout(this.monitoringProcessId); + } + + // No pool, return + if (!self.s.pool) { + this._destroyed = true; + return; + } + + // Emit close event + if (options.emitClose) { + self.emit('close', self); + } + + // Emit destroy event + if (options.emitDestroy) { + self.emit('destroy', self); + } + + // Remove all listeners + listeners.forEach(function(event) { + self.s.pool.removeAllListeners(event); + }); + + // Emit opening server event + if (self.listeners('serverClosed').length > 0) + self.emit('serverClosed', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Emit toplogy opening event if not in topology + if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { + self.emit('topologyClosed', { topologyId: self.id }); + } + + if (self.s.logger.isDebug()) { + self.s.logger.debug(f('destroy called on server %s', self.name)); + } + + // Destroy the pool + this.s.pool.destroy(options.force); + this._destroyed = true; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * A server reconnect event, used to verify that the server topology has reconnected + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * A server opening SDAM monitoring event + * + * @event Server#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Server#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Server#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Server#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Server#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Server#topologyDescriptionChanged + * @type {object} + */ + +/** + * Server reconnect failed + * + * @event Server#reconnectFailed + * @type {Error} + */ + +/** + * Server connection pool closed + * + * @event Server#close + * @type {object} + */ + +/** + * Server connection pool caused an error + * + * @event Server#error + * @type {Error} + */ + +/** + * Server destroyed was called + * + * @event Server#destroy + * @type {Server} + */ + +module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/shared.js b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/shared.js new file mode 100644 index 0000000..4cb72ea --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/shared.js @@ -0,0 +1,434 @@ +'use strict'; + +const os = require('os'); +const f = require('util').format; +const ReadPreference = require('./read_preference'); +const Buffer = require('safe-buffer').Buffer; + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +// Get package.json variable +var driverVersion = require('../../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +function createClientInfo(options) { + // Build default client information + var clientInfo = options.clientInfo + ? clone(options.clientInfo) + : { + driver: { + name: 'nodejs-core', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + } + }; + + // Is platform specified + if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { + clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); + } else if (!clientInfo.platform) { + clientInfo.platform = nodejsversion; + } + + // Do we have an application specific string + if (options.appname) { + // Cut at 128 bytes + var buffer = Buffer.from(options.appname); + // Return the truncated appname + var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; + // Add to the clientInfo + clientInfo.application = { name: appname }; + } + + return clientInfo; +} + +function createCompressionInfo(options) { + if (!options.compression || !options.compression.compressors) { + return []; + } + + // Check that all supplied compressors are valid + options.compression.compressors.forEach(function(compressor) { + if (compressor !== 'snappy' && compressor !== 'zlib') { + throw new Error('compressors must be at least one of snappy or zlib'); + } + }); + + return options.compression.compressors; +} + +function clone(object) { + return JSON.parse(JSON.stringify(object)); +} + +var getPreviousDescription = function(self) { + if (!self.s.serverDescription) { + self.s.serverDescription = { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }; + } + + return self.s.serverDescription; +}; + +var emitServerDescriptionChanged = function(self, description) { + if (self.listeners('serverDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('serverDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var getPreviousTopologyDescription = function(self) { + if (!self.s.topologyDescription) { + self.s.topologyDescription = { + topologyType: 'Unknown', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + } + ] + }; + } + + return self.s.topologyDescription; +}; + +var emitTopologyDescriptionChanged = function(self, description) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('topologyDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousTopologyDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var changedIsMaster = function(self, currentIsmaster, ismaster) { + var currentType = getTopologyType(self, currentIsmaster); + var newType = getTopologyType(self, ismaster); + if (newType !== currentType) return true; + return false; +}; + +var getTopologyType = function(self, ismaster) { + if (!ismaster) { + ismaster = self.ismaster; + } + + if (!ismaster) return 'Unknown'; + if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; + if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; + if (ismaster.ismaster) return 'RSPrimary'; + if (ismaster.secondary) return 'RSSecondary'; + if (ismaster.arbiterOnly) return 'RSArbiter'; + return 'Unknown'; +}; + +var inquireServerState = function(self) { + return function(callback) { + if (self.s.state === 'destroyed') return; + // Record response time + var start = new Date().getTime(); + + // emitSDAMEvent + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); + + // Attempt to execute ismaster command + self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { + if (!err) { + // Legacy event sender + self.emit('ismaster', r, self); + + // Calculate latencyMS + var latencyMS = new Date().getTime() - start; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: self.name + }); + + // Did the server change + if (changedIsMaster(self, self.s.ismaster, r.result)) { + // Emit server description changed if something listening + emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) + }); + } + + // Updat ismaster view + self.s.ismaster = r.result; + + // Set server response time + self.s.isMasterLatencyMS = latencyMS; + } else { + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: self.name + }); + } + + // Peforming an ismaster monitoring callback operation + if (typeof callback === 'function') { + return callback(err, r); + } + + // Perform another sweep + self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); + }); + }; +}; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for (var name in options) { + opts[name] = options[name]; + } + return opts; +}; + +function Interval(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setInterval(fn, time); + } + + return this; + }; + + this.stop = function() { + clearInterval(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + return timer !== false; + }; +} + +function Timeout(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setTimeout(fn, time); + } + return this; + }; + + this.stop = function() { + clearTimeout(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + if (timer && timer._called) return false; + return timer !== false; + }; +} + +function diff(previous, current) { + // Difference document + var diff = { + servers: [] + }; + + // Previous entry + if (!previous) { + previous = { servers: [] }; + } + + // Check if we have any previous servers missing in the current ones + for (var i = 0; i < previous.servers.length; i++) { + var found = false; + + for (var j = 0; j < current.servers.length; j++) { + if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { + found = true; + break; + } + } + + if (!found) { + // Add to the diff + diff.servers.push({ + address: previous.servers[i].address, + from: previous.servers[i].type, + to: 'Unknown' + }); + } + } + + // Check if there are any severs that don't exist + for (j = 0; j < current.servers.length; j++) { + found = false; + + // Go over all the previous servers + for (i = 0; i < previous.servers.length; i++) { + if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { + found = true; + break; + } + } + + // Add the server to the diff + if (!found) { + diff.servers.push({ + address: current.servers[j].address, + from: 'Unknown', + to: current.servers[j].type + }); + } + } + + // Got through all the servers + for (i = 0; i < previous.servers.length; i++) { + var prevServer = previous.servers[i]; + + // Go through all current servers + for (j = 0; j < current.servers.length; j++) { + var currServer = current.servers[j]; + + // Matching server + if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { + // We had a change in state + if (prevServer.type !== currServer.type) { + diff.servers.push({ + address: prevServer.address, + from: prevServer.type, + to: currServer.type + }); + } + } + } + } + + // Return difference + return diff; +} + +/** + * Shared function to determine clusterTime for a given topology + * + * @param {*} topology + * @param {*} clusterTime + */ +function resolveClusterTime(topology, $clusterTime) { + if (topology.clusterTime == null) { + topology.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { + topology.clusterTime = $clusterTime; + } + } +} + +// NOTE: this is a temporary move until the topologies can be more formally refactored +// to share code. +const SessionMixins = { + endSessions: function(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + // TODO: + // When connected to a sharded cluster the endSessions command + // can be sent to any mongos. When connected to a replica set the + // endSessions command MUST be sent to the primary if the primary + // is available, otherwise it MUST be sent to any available secondary. + // Is it enough to use: ReadPreference.primaryPreferred ? + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } +}; + +const RETRYABLE_WIRE_VERSION = 6; + +/** + * Determines whether the provided topology supports retryable writes + * + * @param {Mongos|Replset} topology + */ +const isRetryableWritesSupported = function(topology) { + const maxWireVersion = topology.lastIsMaster().maxWireVersion; + if (maxWireVersion < RETRYABLE_WIRE_VERSION) { + return false; + } + + if (!topology.logicalSessionTimeoutMinutes) { + return false; + } + + return true; +}; + +module.exports.SessionMixins = SessionMixins; +module.exports.resolveClusterTime = resolveClusterTime; +module.exports.inquireServerState = inquireServerState; +module.exports.getTopologyType = getTopologyType; +module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; +module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; +module.exports.cloneOptions = cloneOptions; +module.exports.createClientInfo = createClientInfo; +module.exports.createCompressionInfo = createCompressionInfo; +module.exports.clone = clone; +module.exports.diff = diff; +module.exports.Interval = Interval; +module.exports.Timeout = Timeout; +module.exports.isRetryableWritesSupported = isRetryableWritesSupported; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/transactions.js b/node_modules/mongoose/node_modules/mongodb-core/lib/transactions.js new file mode 100644 index 0000000..6453aea --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/transactions.js @@ -0,0 +1,134 @@ +'use strict'; +const MongoError = require('./error').MongoError; + +let TxnState; +let stateMachine; + +(() => { + const NO_TRANSACTION = 'NO_TRANSACTION'; + const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; + const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; + const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; + const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; + const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; + + TxnState = { + NO_TRANSACTION, + STARTING_TRANSACTION, + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + }; + + stateMachine = { + [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], + [STARTING_TRANSACTION]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + ], + [TRANSACTION_IN_PROGRESS]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_ABORTED + ], + [TRANSACTION_COMMITTED]: [ + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + STARTING_TRANSACTION, + NO_TRANSACTION + ], + [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], + [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] + }; +})(); + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @typedef {Object} ReadConcern + * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level + * @see https://docs.mongodb.com/manual/reference/read-concern/ + */ + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @typedef {Object} WriteConcern + * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has + * propagated to a specified number of mongod hosts + * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has + * been written to the journal + * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + +/** + * Configuration options for a transaction. + * @typedef {Object} TransactionOptions + * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction + * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction + * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction + */ + +/** + * A class maintaining state related to a server transaction. Internal Only + * @ignore + */ +class Transaction { + /** + * Create a transaction + * + * @ignore + * @param {TransactionOptions} [options] Optional settings + */ + constructor(options) { + options = options || {}; + + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + if (options.writeConcern || typeof options.w !== 'undefined') { + const w = options.writeConcern ? options.writeConcern.w : options.w; + if (w <= 0) { + throw new MongoError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; + } + + if (options.readConcern) this.options.readConcern = options.readConcern; + if (options.readPreference) this.options.readPreference = options.readPreference; + } + + /** + * @ignore + * @return Whether this session is presently in a transaction + */ + get isActive() { + return ( + [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 + ); + } + + /** + * Transition the transaction in the state machine + * @ignore + * @param {TxnState} state The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.indexOf(nextState) !== -1) { + this.state = nextState; + return; + } + + throw new MongoError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } +} + +module.exports = { TxnState, Transaction }; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/uri_parser.js b/node_modules/mongoose/node_modules/mongodb-core/lib/uri_parser.js new file mode 100644 index 0000000..7da1641 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/uri_parser.js @@ -0,0 +1,536 @@ +'use strict'; +const URL = require('url'); +const qs = require('querystring'); +const dns = require('dns'); +const MongoParseError = require('./error').MongoParseError; +const ReadPreference = require('./topologies/read_preference'); + +/** + * The following regular expression validates a connection string and breaks the + * provide string into the following capture groups: [protocol, username, password, hosts] + */ +const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param {string} uri The connection string to parse + * @param {object} options Optional user provided connection string options + * @param {function} callback + */ +function parseSrvConnectionString(uri, options, callback) { + const result = URL.parse(uri, true); + + if (result.hostname.split('.').length < 3) { + return callback(new MongoParseError('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + if (result.pathname && result.pathname.match(',')) { + return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); + } + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = result.host; + dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoParseError('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback( + new MongoParseError('Server record does not share hostname with parent URI') + ); + } + } + + // Convert the original URL to a non-SRV URL. + result.protocol = 'mongodb'; + result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); + + // Default to SSL true if it's not specified. + if ( + !('ssl' in options) && + (!result.search || !('ssl' in result.query) || result.query.ssl === null) + ) { + result.query.ssl = true; + } + + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + if (err) { + if (err.code !== 'ENODATA') { + return callback(err); + } + record = null; + } + + if (record) { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + record = qs.parse(record[0].join('')); + if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { + return callback( + new MongoParseError('Text record must only set `authSource` or `replicaSet`') + ); + } + + Object.assign(result.query, record); + } + + // Set completed options back into the URL object. + result.search = qs.stringify(result.query); + + const finalString = URL.format(result); + parseConnectionString(finalString, options, callback); + }); + }); +} + +/** + * Parses a query string item according to the connection string spec + * + * @param {string} key The key for the parsed value + * @param {Array|String} value The value to parse + * @return {Array|Object|String} The parsed value + */ +function parseQueryStringItemValue(key, value) { + if (Array.isArray(value)) { + // deduplicate and simplify arrays + value = value.filter((v, idx) => value.indexOf(v) === idx); + if (value.length === 1) value = value[0]; + } else if (value.indexOf(':') > 0) { + value = value.split(',').reduce((result, pair) => { + const parts = pair.split(':'); + result[parts[0]] = parseQueryStringItemValue(key, parts[1]); + return result; + }, {}); + } else if (value.indexOf(',') > 0) { + value = value.split(',').map(v => { + return parseQueryStringItemValue(key, v); + }); + } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { + value = value.toLowerCase() === 'true'; + } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { + const numericValue = parseFloat(value); + if (!Number.isNaN(numericValue)) { + value = parseFloat(value); + } + } + + return value; +} + +// Options that are known boolean types +const BOOLEAN_OPTIONS = new Set([ + 'slaveok', + 'slave_ok', + 'sslvalidate', + 'fsync', + 'safe', + 'retrywrites', + 'j' +]); + +// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` +const STRING_OPTIONS = new Set(['authsource', 'replicaset']); + +// Supported text representations of auth mechanisms +// NOTE: this list exists in native already, if it is merged here we should deduplicate +const AUTH_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-X509', + 'MONGODB-CR', + 'DEFAULT', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'PLAIN' +]); + +// Lookup table used to translate normalized (lower-cased) forms of connection string +// options to their expected camelCase version +const CASE_TRANSLATION = { + replicaset: 'replicaSet', + connecttimeoutms: 'connectTimeoutMS', + sockettimeoutms: 'socketTimeoutMS', + maxpoolsize: 'maxPoolSize', + minpoolsize: 'minPoolSize', + maxidletimems: 'maxIdleTimeMS', + waitqueuemultiple: 'waitQueueMultiple', + waitqueuetimeoutms: 'waitQueueTimeoutMS', + wtimeoutms: 'wtimeoutMS', + readconcern: 'readConcern', + readconcernlevel: 'readConcernLevel', + readpreference: 'readPreference', + maxstalenessseconds: 'maxStalenessSeconds', + readpreferencetags: 'readPreferenceTags', + authsource: 'authSource', + authmechanism: 'authMechanism', + authmechanismproperties: 'authMechanismProperties', + gssapiservicename: 'gssapiServiceName', + localthresholdms: 'localThresholdMS', + serverselectiontimeoutms: 'serverSelectionTimeoutMS', + serverselectiontryonce: 'serverSelectionTryOnce', + heartbeatfrequencyms: 'heartbeatFrequencyMS', + appname: 'appName', + retrywrites: 'retryWrites', + uuidrepresentation: 'uuidRepresentation', + zlibcompressionlevel: 'zlibCompressionLevel' +}; + +/** + * Sets the value for `key`, allowing for any required translation + * + * @param {object} obj The object to set the key on + * @param {string} key The key to set the value for + * @param {*} value The value to set + * @param {object} options The options used for option parsing + */ +function applyConnectionStringOption(obj, key, value, options) { + // simple key translation + if (key === 'journal') { + key = 'j'; + } else if (key === 'wtimeoutms') { + key = 'wtimeout'; + } + + // more complicated translation + if (BOOLEAN_OPTIONS.has(key)) { + value = value === 'true' || value === true; + } else if (key === 'appname') { + value = decodeURIComponent(value); + } else if (key === 'readconcernlevel') { + key = 'readconcern'; + value = { level: value }; + } + + // simple validation + if (key === 'compressors') { + value = Array.isArray(value) ? value : [value]; + + if (!value.every(c => c === 'snappy' || c === 'zlib')) { + throw new MongoParseError( + 'Value for `compressors` must be at least one of: `snappy`, `zlib`' + ); + } + } + + if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { + throw new MongoParseError( + 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' + ); + } + + if (key === 'readpreference' && !ReadPreference.isValid(value)) { + throw new MongoParseError( + 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' + ); + } + + if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { + throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); + } + + // special cases + if (key === 'compressors' || key === 'zlibcompressionlevel') { + obj.compression = obj.compression || {}; + obj = obj.compression; + } + + if (key === 'authmechanismproperties') { + if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; + if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; + if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { + obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; + } + } + + // set the actual value + if (options.caseTranslate && CASE_TRANSLATION[key]) { + obj[CASE_TRANSLATION[key]] = value; + return; + } + + obj[key] = value; +} + +const USERNAME_REQUIRED_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-CR', + 'PLAIN', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256' +]); + +/** + * Modifies the parsed connection string object taking into account expectations we + * have for authentication-related options. + * + * @param {object} parsed The parsed connection string result + * @return The parsed connection string result possibly modified for auth expectations + */ +function applyAuthExpectations(parsed) { + if (parsed.options == null) { + return; + } + + const options = parsed.options; + const authSource = options.authsource || options.authSource; + if (authSource != null) { + parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); + } + + const authMechanism = options.authmechanism || options.authMechanism; + if (authMechanism != null) { + if ( + USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && + (!parsed.auth || parsed.auth.username == null) + ) { + throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); + } + + if (authMechanism === 'GSSAPI') { + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'MONGODB-X509') { + if (parsed.auth && parsed.auth.password != null) { + throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); + } + + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'PLAIN') { + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + } + } + + // default to `admin` if nothing else was resolved + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); + } + + return parsed; +} + +/** + * Parses a query string according the connection string spec. + * + * @param {String} query The query string to parse + * @param {object} [options] The options used for options parsing + * @return {Object|Error} The parsed query string as an object, or an error if one was encountered + */ +function parseQueryString(query, options) { + const result = {}; + let parsedQueryString = qs.parse(query); + + for (const key in parsedQueryString) { + const value = parsedQueryString[key]; + if (value === '' || value == null) { + throw new MongoParseError('Incomplete key value pair for option'); + } + + const normalizedKey = key.toLowerCase(); + const parsedValue = parseQueryStringItemValue(normalizedKey, value); + applyConnectionStringOption(result, normalizedKey, parsedValue, options); + } + + // special cases for known deprecated options + if (result.wtimeout && result.wtimeoutms) { + delete result.wtimeout; + console.warn('Unsupported option `wtimeout` specified'); + } + + return Object.keys(result).length ? result : null; +} + +const PROTOCOL_MONGODB = 'mongodb'; +const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; +const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; + +/** + * Parses a MongoDB connection string + * + * @param {*} uri the MongoDB connection string to parse + * @param {object} [options] Optional settings. + * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization + * @param {parseCallback} callback + */ +function parseConnectionString(uri, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { caseTranslate: true }, options); + + // Check for bad uris before we parse + try { + URL.parse(uri); + } catch (e) { + return callback(new MongoParseError('URI malformed, cannot be parsed')); + } + + const cap = uri.match(HOSTS_RX); + if (!cap) { + return callback(new MongoParseError('Invalid connection string')); + } + + const protocol = cap[1]; + if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { + return callback(new MongoParseError('Invalid protocol provided')); + } + + if (protocol === PROTOCOL_MONGODB_SRV) { + return parseSrvConnectionString(uri, options, callback); + } + + const dbAndQuery = cap[4].split('?'); + const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; + const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; + + let parsedOptions; + try { + parsedOptions = parseQueryString(query, options); + } catch (parseError) { + return callback(parseError); + } + + parsedOptions = Object.assign({}, parsedOptions, options); + const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; + if (parsedOptions.auth) { + // maintain support for legacy options passed into `MongoClient` + if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; + if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; + if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; + } + + if (cap[4].split('?')[0].indexOf('@') !== -1) { + return callback(new MongoParseError('Unescaped slash in userinfo section')); + } + + const authorityParts = cap[3].split('@'); + if (authorityParts.length > 2) { + return callback(new MongoParseError('Unescaped at-sign in authority section')); + } + + if (authorityParts.length > 1) { + const authParts = authorityParts.shift().split(':'); + if (authParts.length > 2) { + return callback(new MongoParseError('Unescaped colon in authority section')); + } + + auth.username = qs.unescape(authParts[0]); + auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; + } + + let hostParsingError = null; + const hosts = authorityParts + .shift() + .split(',') + .map(host => { + let parsedHost = URL.parse(`mongodb://${host}`); + if (parsedHost.path === '/:') { + hostParsingError = new MongoParseError('Double colon in host identifier'); + return null; + } + + // heuristically determine if we're working with a domain socket + if (host.match(/\.sock/)) { + parsedHost.hostname = qs.unescape(host); + parsedHost.port = null; + } + + if (Number.isNaN(parsedHost.port)) { + hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); + return; + } + + const result = { + host: parsedHost.hostname, + port: parsedHost.port ? parseInt(parsedHost.port) : 27017 + }; + + if (result.port === 0) { + hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); + return; + } + + if (result.port > 65535) { + hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); + return; + } + + if (result.port < 0) { + hostParsingError = new MongoParseError('Invalid port (negative number)'); + return; + } + + return result; + }) + .filter(host => !!host); + + if (hostParsingError) { + return callback(hostParsingError); + } + + if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { + return callback(new MongoParseError('No hostname or hostnames provided in connection string')); + } + + const result = { + hosts: hosts, + auth: auth.db || auth.username ? auth : null, + options: Object.keys(parsedOptions).length ? parsedOptions : null + }; + + if (result.auth && result.auth.db) { + result.defaultDatabase = result.auth.db; + } + + try { + applyAuthExpectations(result); + } catch (authError) { + return callback(authError); + } + + callback(null, result); +} + +module.exports = parseConnectionString; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/utils.js b/node_modules/mongoose/node_modules/mongodb-core/lib/utils.js new file mode 100644 index 0000000..486e268 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/utils.js @@ -0,0 +1,97 @@ +'use strict'; + +const crypto = require('crypto'); +const requireOptional = require('require_optional'); + +/** + * Generate a UUIDv4 + */ +const uuidV4 = () => { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +}; + +/** + * Returns the duration calculated from two high resolution timers in milliseconds + * + * @param {Object} started A high resolution timestamp created from `process.hrtime()` + * @returns {Number} The duration in milliseconds + */ +const calculateDurationInMs = started => { + const hrtime = process.hrtime(started); + return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; +}; + +/** + * Relays events for a given listener and emitter + * + * @param {EventEmitter} listener the EventEmitter to listen to the events from + * @param {EventEmitter} emitter the EventEmitter to relay the events to + */ +function relayEvents(listener, emitter, events) { + events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); +} + +function retrieveKerberos() { + let kerberos; + + try { + kerberos = requireOptional('kerberos'); + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + throw new Error('The `kerberos` module was not found. Please install it and try again.'); + } + + throw err; + } + + return kerberos; +} + +// Throw an error if an attempt to use EJSON is made when it is not installed +const noEJSONError = function() { + throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); +}; + +// Facilitate loading EJSON optionally +function retrieveEJSON() { + let EJSON = null; + try { + EJSON = requireOptional('mongodb-extjson'); + } catch (error) {} // eslint-disable-line + if (!EJSON) { + EJSON = { + parse: noEJSONError, + deserialize: noEJSONError, + serialize: noEJSONError, + stringify: noEJSONError, + setBSONModule: noEJSONError, + BSON: noEJSONError + }; + } + + return EJSON; +} + +/* + * Checks that collation is supported by server. + * + * @param {Server} [server] to check against + * @param {object} [cmd] object where collation may be specified + * @param {function} [callback] callback function + * @return true if server does not support collation + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && server.ismaster && server.ismaster.maxWireVersion < 5; +} + +module.exports = { + uuidV4, + calculateDurationInMs, + relayEvents, + collationNotSupported, + retrieveEJSON, + retrieveKerberos +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..931aada --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,267 @@ +'use strict'; + +const retrieveBSON = require('../connection/utils').retrieveBSON; +const KillCursor = require('../connection/commands').KillCursor; +const GetMore = require('../connection/commands').GetMore; +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const getReadPreference = require('./shared').getReadPreference; +const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; +const isMongos = require('./shared').isMongos; +const databaseNamespace = require('./shared').databaseNamespace; +const collectionNamespace = require('./shared').collectionNamespace; + +const BSON = retrieveBSON(); +const Long = BSON.Long; + +class WireProtocol { + insert(server, ns, ops, options, callback) { + executeWrite(this, server, 'insert', 'documents', ns, ops, options, callback); + } + + update(server, ns, ops, options, callback) { + executeWrite(this, server, 'update', 'updates', ns, ops, options, callback); + } + + remove(server, ns, ops, options, callback) { + executeWrite(this, server, 'delete', 'deletes', ns, ops, options, callback); + } + + killCursor(server, ns, cursorState, callback) { + const bson = server.s.bson; + const pool = server.s.pool; + const cursorId = cursorState.cursorId; + const killCursor = new KillCursor(bson, ns, [cursorId]); + const options = { + immediateRelease: true, + noResponse: true + }; + + if (typeof cursorState.session === 'object') { + options.session = cursorState.session; + } + + if (pool && pool.isConnected()) { + try { + pool.write(killCursor, options, callback); + } catch (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + console.warn(err); + } + } + } + } + + getMore(server, ns, cursorState, batchSize, options, callback) { + const bson = server.s.bson; + const getMore = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); + function queryCallback(err, result) { + if (err) return callback(err); + const response = result.message; + + // If we have a timed out query or a cursor that was killed + if (response.cursorNotFound) { + return callback(new MongoError('Cursor does not exist, was killed, or timed out'), null); + } + + const cursorId = + typeof response.cursorId === 'number' + ? Long.fromNumber(response.cursorId) + : response.cursorId; + + cursorState.documents = response.documents; + cursorState.cursorId = cursorId; + + callback(null, null, response.connection); + } + + const queryOptions = applyCommonQueryOptions({}, cursorState); + server.s.pool.write(getMore, queryOptions, queryCallback); + } + + query(server, ns, cmd, cursorState, options, callback) { + if (cursorState.cursorId != null) { + return; + } + + const query = setupClassicFind(server, ns, cmd, cursorState, options); + const queryOptions = applyCommonQueryOptions({}, cursorState); + if (typeof query.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = query.documentsReturnedIn; + } + + server.s.pool.write(query, queryOptions, callback); + } + + command(server, ns, cmd, options, callback) { + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + options = options || {}; + const bson = server.s.bson; + const pool = server.s.pool; + const readPreference = getReadPreference(cmd, options); + + let finalCmd = Object.assign({}, cmd); + if (finalCmd.readConcern) { + if (finalCmd.readConcern.level !== 'local') { + return callback( + new MongoError( + `server ${JSON.stringify(finalCmd)} command does not support a readConcern level of ${ + finalCmd.readConcern.level + }` + ) + ); + } + + delete finalCmd['readConcern']; + } + + if (isMongos(server) && readPreference && readPreference.preference !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const commandOptions = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false + }, + options + ); + + // This value is not overridable + commandOptions.slaveOk = readPreference.slaveOk(); + + try { + const query = new Query(bson, `${databaseNamespace(ns)}.$cmd`, finalCmd, commandOptions); + pool.write(query, commandOptions, callback); + } catch (err) { + callback(err); + } + } +} + +function executeWrite(handler, server, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError('insert must contain at least one document'); + if (typeof options === 'function') { + callback = options; + options = {}; + options = options || {}; + } + + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const writeConcern = options.writeConcern; + + const writeCommand = {}; + writeCommand[type] = collectionNamespace(ns); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + const commandOptions = Object.assign( + { + checkKeys: type === 'insert', + numberToReturn: 1 + }, + options + ); + + handler.command(server, ns, writeCommand, commandOptions, callback); +} + +function setupClassicFind(server, ns, cmd, cursorState, options) { + options = options || {}; + const bson = server.s.bson; + const readPreference = getReadPreference(cmd, options); + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + let numberToReturn = 0; + if (cursorState.limit === 0) { + numberToReturn = cursorState.batchSize; + } else if ( + cursorState.limit < 0 || + cursorState.limit < cursorState.batchSize || + (cursorState.limit > 0 && cursorState.batchSize === 0) + ) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + const numberToSkip = cursorState.skip || 0; + + const findCmd = {}; + if (isMongos(server) && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + if (cmd.sort) findCmd['$orderby'] = cmd.sort; + if (cmd.hint) findCmd['$hint'] = cmd.hint; + if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; + if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; + if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; + if (cmd.min) findCmd['$min'] = cmd.min; + if (cmd.max) findCmd['$max'] = cmd.max; + if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; + if (cmd.comment) findCmd['$comment'] = cmd.comment; + if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; + if (cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + findCmd['$explain'] = true; + } + + findCmd['$query'] = cmd.query; + if (cmd.readConcern && cmd.readConcern.level !== 'local') { + throw new MongoError( + `server find command does not support a readConcern level of ${cmd.readConcern.level}` + ); + } + + if (cmd.readConcern) { + cmd = Object.assign({}, cmd); + delete cmd['readConcern']; + } + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + const query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, + numberToReturn: numberToReturn, + pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, + checkKeys: false, + returnFieldSelector: cmd.fields, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; + if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; + if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; + if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; + + query.slaveOk = readPreference.slaveOk(); + return query; +} + +module.exports = WireProtocol; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 0000000..bba1d22 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,397 @@ +'use strict'; + +const Query = require('../connection/commands').Query; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const getReadPreference = require('./shared').getReadPreference; +const BSON = retrieveBSON(); +const Long = BSON.Long; +const ReadPreference = require('../topologies/read_preference'); +const TxnState = require('../transactions').TxnState; +const isMongos = require('./shared').isMongos; +const databaseNamespace = require('./shared').databaseNamespace; +const collectionNamespace = require('./shared').collectionNamespace; + +class WireProtocol { + insert(server, ns, ops, options, callback) { + executeWrite(this, server, 'insert', 'documents', ns, ops, options, callback); + } + + update(server, ns, ops, options, callback) { + executeWrite(this, server, 'update', 'updates', ns, ops, options, callback); + } + + remove(server, ns, ops, options, callback) { + executeWrite(this, server, 'delete', 'deletes', ns, ops, options, callback); + } + + killCursor(server, ns, cursorState, callback) { + callback = typeof callback === 'function' ? callback : () => {}; + const cursorId = cursorState.cursorId; + const killCursorCmd = { + killCursors: collectionNamespace(ns), + cursors: [cursorId] + }; + + const options = {}; + if (typeof cursorState.session === 'object') options.session = cursorState.session; + + this.command(server, ns, killCursorCmd, options, (err, result) => { + if (err) { + return callback(err); + } + + const response = result.message; + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) + ); + } + + callback(null, response.documents[0]); + }); + } + + getMore(server, ns, cursorState, batchSize, options, callback) { + options = options || {}; + const getMoreCmd = { + getMore: cursorState.cursorId, + collection: collectionNamespace(ns), + batchSize: Math.abs(batchSize) + }; + + if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + function queryCallback(err, result) { + if (err) return callback(err); + const response = result.message; + + // If we have a timed out query or a cursor that was killed + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + // Raw, return all the extracted documents + if (cursorState.raw) { + cursorState.documents = response.documents; + cursorState.cursorId = response.cursorId; + return callback(null, response.documents); + } + + // We have an error detected + if (response.documents[0].ok === 0) { + return callback(new MongoError(response.documents[0])); + } + + // Ensure we have a Long valid cursor id + const cursorId = + typeof response.documents[0].cursor.id === 'number' + ? Long.fromNumber(response.documents[0].cursor.id) + : response.documents[0].cursor.id; + + cursorState.documents = response.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + callback(null, response.documents[0], response.connection); + } + + const commandOptions = Object.assign( + { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, + options + ); + + this.command(server, ns, getMoreCmd, commandOptions, queryCallback); + } + + query(server, ns, cmd, cursorState, options, callback) { + options = options || {}; + if (cursorState.cursorId != null) { + return callback(); + } + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + const readPreference = getReadPreference(cmd, options); + const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); + + // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this + // side-effect. Change this ASAP + cmd.virtual = false; + + const commandOptions = Object.assign( + { + documentsReturnedIn: 'firstBatch', + numberToReturn: 1, + slaveOk: readPreference.slaveOk() + }, + options + ); + + if (cmd.readPreference) commandOptions.readPreference = readPreference; + this.command(server, ns, findCmd, commandOptions, callback); + } + + command(server, ns, cmd, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + const bson = server.s.bson; + const pool = server.s.pool; + const readPreference = getReadPreference(cmd, options); + + let finalCmd = Object.assign({}, cmd); + if (isMongos(server) && readPreference && readPreference.preference !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const err = decorateWithSessionsData(finalCmd, options.session, options); + if (err) { + return callback(err); + } + + const commandOptions = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false + }, + options + ); + + // This value is not overridable + commandOptions.slaveOk = readPreference.slaveOk(); + + try { + const query = new Query(bson, `${databaseNamespace(ns)}.$cmd`, finalCmd, commandOptions); + pool.write(query, commandOptions, callback); + } catch (err) { + callback(err); + } + } +} + +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param {Object} command the command to decorate + * @param {ClientSession} session the session tracking transaction state + * @param {Object} [options] Optional settings passed to calling operation + * @param {Function} [callback] Optional callback passed from calling operation + * @return {MongoError|null} An error, if some error condition was met + */ +function decorateWithSessionsData(command, session, options) { + if (!session) { + return; + } + + // first apply non-transaction-specific sessions data + const serverSession = session.serverSession; + const inTransaction = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = options.willRetryWrite; + + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); + } + + // now attempt to apply transaction-specific sessions data + if (!inTransaction) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + // for causal consistency + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + + return; + } + + if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { + return new MongoError( + `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` + ); + } + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session.clientOptions.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} + +function executeWrite(handler, server, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError('insert must contain at least one document'); + if (typeof options === 'function') { + callback = options; + options = {}; + options = options || {}; + } + + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const writeConcern = options.writeConcern; + + const writeCommand = {}; + writeCommand[type] = collectionNamespace(ns); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + if (options.collation) { + for (let i = 0; i < writeCommand[opsField].length; i++) { + if (!writeCommand[opsField][i].collation) { + writeCommand[opsField][i].collation = options.collation; + } + } + } + + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + const commandOptions = Object.assign( + { + checkKeys: type === 'insert', + numberToReturn: 1 + }, + options + ); + + handler.command(server, ns, writeCommand, commandOptions, callback); +} + +function prepareFindCommand(server, ns, cmd, cursorState) { + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + let findCmd = { + find: collectionNamespace(ns) + }; + + if (cmd.query) { + if (cmd.query['$query']) { + findCmd.filter = cmd.query['$query']; + } else { + findCmd.filter = cmd.query; + } + } + + let sortValue = cmd.sort; + if (Array.isArray(sortValue)) { + const sortObject = {}; + + if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { + let sortDirection = sortValue[1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[0]] = sortDirection; + } else { + for (let i = 0; i < sortValue.length; i++) { + let sortDirection = sortValue[i][1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + } + + if (cmd.sort) findCmd.sort = sortValue; + if (cmd.fields) findCmd.projection = cmd.fields; + if (cmd.hint) findCmd.hint = cmd.hint; + if (cmd.skip) findCmd.skip = cmd.skip; + if (cmd.limit) findCmd.limit = cmd.limit; + if (cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + if (typeof cmd.batchSize === 'number') { + if (cmd.batchSize < 0) { + if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { + findCmd.limit = Math.abs(cmd.batchSize); + } + + findCmd.singleBatch = true; + } + + findCmd.batchSize = Math.abs(cmd.batchSize); + } + + if (cmd.comment) findCmd.comment = cmd.comment; + if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; + if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + if (cmd.min) findCmd.min = cmd.min; + if (cmd.max) findCmd.max = cmd.max; + findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; + findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; + if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; + if (cmd.tailable) findCmd.tailable = cmd.tailable; + if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + if (cmd.partial) findCmd.partial = cmd.partial; + if (cmd.collation) findCmd.collation = cmd.collation; + if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if (cmd.explain) { + findCmd = { + explain: findCmd + }; + } + + return findCmd; +} + +module.exports = WireProtocol; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/compression.js b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/compression.js new file mode 100644 index 0000000..4b908e6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/compression.js @@ -0,0 +1,73 @@ +'use strict'; + +var Snappy = require('../connection/utils').retrieveSnappy(), + zlib = require('zlib'); + +var compressorIDs = { + snappy: 1, + zlib: 2 +}; + +var uncompressibleCommands = [ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]; + +// Facilitate compressing a message using an agreed compressor +var compress = function(self, dataToBeCompressed, callback) { + switch (self.options.agreedCompressor) { + case 'snappy': + Snappy.compress(dataToBeCompressed, callback); + break; + case 'zlib': + // Determine zlibCompressionLevel + var zlibOptions = {}; + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new Error( + 'Attempt to compress message using unknown compressor "' + + self.options.agreedCompressor + + '".' + ); + } +}; + +// Decompress a message using the given compressor +var decompress = function(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > compressorIDs.length) { + throw new Error( + 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + + compressorID + + ')' + ); + } + switch (compressorID) { + case compressorIDs.snappy: + Snappy.uncompress(compressedData, callback); + break; + case compressorIDs.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(null, compressedData); + } +}; + +module.exports = { + compressorIDs: compressorIDs, + uncompressibleCommands: uncompressibleCommands, + compress: compress, + decompress: decompress +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/shared.js b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/shared.js new file mode 100644 index 0000000..23da8b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/lib/wireprotocol/shared.js @@ -0,0 +1,101 @@ +'use strict'; + +var ReadPreference = require('../topologies/read_preference'), + MongoError = require('../error').MongoError; + +var MESSAGE_HEADER_SIZE = 16; + +// OPCODE Numbers +// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes +var opcodes = { + OP_REPLY: 1, + OP_UPDATE: 2001, + OP_INSERT: 2002, + OP_QUERY: 2004, + OP_GETMORE: 2005, + OP_DELETE: 2006, + OP_KILL_CURSORS: 2007, + OP_COMPRESSED: 2012 +}; + +var getReadPreference = function(cmd, options) { + // Default to command version of the readPreference + var readPreference = cmd.readPreference || new ReadPreference('primary'); + // If we have an option readPreference override the command one + if (options.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoError('read preference must be a ReadPreference instance'); + } + + return readPreference; +}; + +// Parses the header of a wire protocol message +var parseHeader = function(message) { + return { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; +}; + +function applyCommonQueryOptions(queryOptions, options) { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false + }); + + if (typeof options.socketTimeout === 'number') { + queryOptions.socketTimeout = options.socketTimeout; + } + + if (options.session) { + queryOptions.session = options.session; + } + + if (typeof options.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = options.documentsReturnedIn; + } + + return queryOptions; +} + +function isMongos(server) { + if (server.type === 'mongos') return true; + if (server.parent && server.parent.type === 'mongos') return true; + // NOTE: handle unified topology + return false; +} + +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +function collectionNamespace(ns) { + return ns + .split('.') + .slice(1) + .join('.'); +} + +module.exports = { + getReadPreference, + MESSAGE_HEADER_SIZE, + opcodes, + parseHeader, + applyCommonQueryOptions, + isMongos, + databaseNamespace, + collectionNamespace +}; diff --git a/node_modules/mongoose/node_modules/mongodb-core/package.json b/node_modules/mongoose/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..ee9e2df --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb-core/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "mongodb-core@3.1.11", + "/Users/xenia/Desktop/B_ME5/Projekt/om" + ] + ], + "_from": "mongodb-core@3.1.11", + "_id": "mongodb-core@3.1.11", + "_inBundle": false, + "_integrity": "sha512-rD2US2s5qk/ckbiiGFHeu+yKYDXdJ1G87F6CG3YdaZpzdOm5zpoAZd/EKbPmFO6cQZ+XVXBXBJ660sSI0gc6qg==", + "_location": "/mongoose/mongodb-core", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mongodb-core@3.1.11", + "name": "mongodb-core", + "escapedName": "mongodb-core", + "rawSpec": "3.1.11", + "saveSpec": null, + "fetchSpec": "3.1.11" + }, + "_requiredBy": [ + "/mongoose", + "/mongoose/mongodb" + ], + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.11.tgz", + "_spec": "3.1.11", + "_where": "/Users/xenia/Desktop/B_ME5/Projekt/om", + "author": { + "name": "Christian Kvalheim" + }, + "bugs": { + "url": "https://github.com/mongodb-js/mongodb-core/issues" + }, + "dependencies": { + "bson": "^1.1.0", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + }, + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "devDependencies": { + "chai": "^4.1.2", + "chai-subset": "^1.6.0", + "co": "^4.6.0", + "eslint": "^4.6.1", + "eslint-plugin-prettier": "^2.2.0", + "jsdoc": "3.5.4", + "mongodb-extjson": "^2.1.2", + "mongodb-mock-server": "^1.0.0", + "mongodb-test-runner": "^1.1.18", + "prettier": "~1.12.0", + "sinon": "^6.0.0", + "snappy": "^6.1.1", + "standard-version": "^4.4.0" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/mongodb-js/mongodb-core", + "keywords": [ + "mongodb", + "core" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "mongodb-core", + "optionalDependencies": { + "saslprep": "^1.0.0" + }, + "peerOptionalDependencies": { + "kerberos": "^1.0.0", + "mongodb-extjson": "^2.1.2", + "snappy": "^6.1.1", + "bson-ext": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/mongodb-js/mongodb-core.git" + }, + "scripts": { + "atlas": "node ./test/atlas.js", + "changelog": "conventional-changelog -p angular -i HISTORY.md -s", + "coverage": "nyc node test/runner.js -t functional -l && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write index.js test/**/*.js lib/**/*.js", + "lint": "eslint index.js lib test", + "release": "standard-version -i HISTORY.md", + "test": "npm run lint && mongodb-test-runner -t 60000 test/tests" + }, + "version": "3.1.11" +} diff --git a/node_modules/mongoose/node_modules/mongodb/HISTORY.md b/node_modules/mongoose/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..2e19fb9 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/HISTORY.md @@ -0,0 +1,2226 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) + + +### Bug Fixes + +* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) +* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) +* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) +* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) + + + + +## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) + + +### Features + +* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) + + + + +## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) + + +### Bug Fixes + +* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) +* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) +* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) +* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) + + + + +## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) + + +### Bug Fixes + +* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) + + +### Features + +* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) + + + + +## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) + + +### Bug Fixes + +* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) +* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) + + +### Features + +* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) + + + + +## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) + + +### Bug Fixes + +* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) + + +### Features + +* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) + + + + +## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) + + +### Features + +* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) + + + + +## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) + + +### Features + +* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) + + + + +## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) + + +### Bug Fixes + +* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) +* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) + + +### Features + +* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) + + + + +## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) + + +### Bug Fixes + +* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) +* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) +* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) +* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) +* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) + + +### Features + +* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) +* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) +* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) + + + + +## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) + + +### Features + +* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) + + + + +## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) +* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) +* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) +* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) +* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) +* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) +* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) + + +### Bug Fixes + +* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) +* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) + + +### Features + +* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) +* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) +* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) + + + + +## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) + + +### Bug Fixes + +* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) +* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) +* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) +* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) + + +### Features + +* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) + + + + +## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) +* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) + + +### Features + +* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) +* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) + + + + +## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) + + + + +## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) + + +### Bug Fixes + +* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) +* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) +* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) +* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) + + +### Features + +* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) +* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) + + + + +## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) + +* update mongodb-core to 3.0.1 + + +# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) + + +### Bug Fixes + +* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) +* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) + + +### Features + +* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) + + +### BREAKING CHANGES + +* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. + +Part of NODE-1089 +* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and +number `keepAliveInitialDelay` + +Fixes NODE-998 + + + + +# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) + + +### Bug Fixes + +* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) +* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) +* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) +* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) +* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) +* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) +* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) +* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) +* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) +* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) +* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) +* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) +* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) +* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) +* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) +* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) +* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) +* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) +* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) +* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) +* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) +* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) +* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) +* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) +* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) +* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) +* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) +* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) +* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) +* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) +* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) +* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) +* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) +* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) +* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) +* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) +* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) +* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) +* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) +* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) +* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) +* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) + + +### Features + +* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) +* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) +* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) +* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) +* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) +* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) +* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) +* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) +* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) +* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) +* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) +* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) +* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) +* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) +* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) +* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) +* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) +* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) +* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) + + +### BREAKING CHANGES + +* **aggregation:** If you use aggregation, and try to use the explain flag while you +have a readConcern or writeConcern, your query will fail +* **collection:** `find` and `findOne` no longer support the `fields` parameter. +You can achieve the same results as the `fields` parameter by +either using `Cursor.prototype.project`, or by passing the `projection` +property in on the `options` object. Additionally, `find` does not +support individual options like `skip` and `limit` as positional +parameters. You must pass in these parameters in the `options` object + + + +3.0.0 2017-??-?? +---------------- +* NODE-1043 URI-escaping authentication and hostname details in connection string + +2.2.31 2017-08-08 +----------------- +* update mongodb-core to 2.2.15 +* allow auth option in MongoClient.connect +* remove duplicate option `promoteLongs` from MongoClient's `connect` +* bulk operations should not throw an error on empty batch + +2.2.30 2017-07-07 +----------------- +* Update mongodb-core to 2.2.14 +* MongoClient + * add `appname` to list of valid option names + * added test for passing appname as option +* NODE-1052 ensure user options are applied while parsing connection string uris + +2.2.29 2017-06-19 +----------------- +* Update mongodb-core to 2.1.13 + * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. + * Use actual server type in standalone SDAM events. +* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). +* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). +* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. +* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. + +2.2.28 2017-06-02 +----------------- +* Update mongodb-core to 2.1.12 + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. + * Minor fix to report the correct state on error. + * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). + * Fix require_optional loading of bson-ext. + * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. + * NODE-999 SDAM fixes for Mongos and single Server event emitting. + * NODE-1014 Set socketTimeout to default to 360 seconds. + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. +* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. +* NODE-999 SDAM fixes for Mongos and single Server event emitting. +* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. + +2.2.27 2017-05-22 +----------------- +* Updated mongodb-core to 2.1.11 + * NODE-987 Clear out old intervalIds on when calling topologyMonitor. + * NODE-987 Moved filtering to pingServer method and added test case. + * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). + * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. +* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. +* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() +* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). +* NODE-996 Propegate all events up to a MongoClient instance. +* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). +* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. + +2.2.26 2017-04-18 +----------------- +* Updated mongodb-core to 2.1.10 + * NODE-981 delegate auth to replset/mongos if inTopology is set. + * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. + * Remove dynamic require (Issue #175, https://github.com/tellnes). + * NODE-696 Handle interrupted error for createIndexes. + * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. + * NODE-966 promoteValues not being promoted correctly to getMore. + * Merged in fix for flushing out monitoring operations. +* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). +* Mark group and profilingInfo as deprecated methods +* NODE-956 DOCS Examples. +* Update readable-stream to version 2.2.7. +* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. +* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) +* Fixed merging of writeConcerns on db.collection method. +* NODE-970 mix in readPreference for strict mode listCollections callback. +* NODE-966 added testcase for promoteValues being applied to getMore commands. +* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. +* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). +* NODE-963 Correctly handle cursor.count when using APM. + +2.2.25 2017-03-17 +----------------- +* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). +* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). +* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. +* Exposed BSONRegExp type. +* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). +* NODE-951 Added support for sslCRL option and added a test case for it. +* NODE-953 Made batchSize issue general at cursor level. +* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. +* Updated mongodb-core to 2.1.9. + * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. + * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. + * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. + * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. + * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. + +2.2.24 2017-02-14 +----------------- +* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. + +2.2.23 2017-02-13 +----------------- +* Updated mongodb-core to 2.1.8. + * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. + * NODE-927 fixes issue where authentication was performed against arbiter instances. + * NODE-915 Normalize all host names to avoid comparison issues. + * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. +* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. +* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects +* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) + +2.2.22 2017-01-24 +----------------- +* Updated mongodb-core to 2.1.7. + * NODE-919 ReplicaSet connection does not close immediately (Issue #156). + * NODE-901 Fixed bug when normalizing host names. + * NODE-909 Fixed readPreference issue caused by direct connection to primary. + * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. +* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) + +2.2.21 2017-01-13 +----------------- +* Updated mongodb-core to 2.1.6. + * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. + +2.2.20 2017-01-11 +----------------- +* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. + +2.2.19 2017-01-03 +----------------- +* Corrupted Npm release fix. + +2.2.18 2017-01-03 +----------------- +* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. + +2.2.17 2017-01-02 +----------------- +* updated createCollection doc options and linked to create command. +* Updated mongodb-core to 2.1.3. + * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining + * Moved replicaset monitoring away from serial mode and to parallel mode. + * updated bson and bson-ext dependencies to 1.0.2. + +2.2.16 2016-12-13 +----------------- +* NODE-899 reversed upsertedId change to bring back old behavior. + +2.2.15 2016-12-10 +----------------- +* Updated mongodb-core to 2.1.2. + * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. + * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). + +2.2.14 2016-12-08 +----------------- +* Updated mongodb-core to 2.1.1. +* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. + +2.2.13 2016-12-05 +----------------- +* Updated mongodb-core to 2.1.0. +* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. +* Expose parserType as property on topology objects. + +2.2.12 2016-11-29 +----------------- +* Updated mongodb-core to 2.0.14. + * Updated bson library to 0.5.7. + * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). + * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). + * Only check isConnected against availableConnections (Issue #142). + * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. + * Set default servername to host is not passed through for sni. + * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). + * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. + * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. + * NODE-850 Update Max Staleness implementation. + * NODE-849 username no longer required for MONGODB-X509 auth. + * NODE-848 BSON Regex flags must be alphabetically ordered. + * NODE-846 Create notice for all third party libraries. + * NODE-843 Executing bulk operations overwrites write concern parameter. + * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. + * NODE-840 Resync CRUD spec tests. + * Unescapable while(true) loop (Issue #152). +* NODE-864 close event not emits during network issues using single server topology. +* Introduced maxStalenessSeconds. +* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. +* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). + +2.2.11 2016-10-21 +----------------- +* Updated mongodb-core to 2.0.13. + - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). + - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). + - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). + - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). +* NODE-824, readPreference "nearest" does not work when specified at collection level. +* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. +* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. +* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. + +2.2.10 2016-09-15 +----------------- +* Updated mongodb-core to 2.0.12. +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. +* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. +* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. +* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. +* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. + +2.2.9 2016-08-29 +---------------- +* Updated mongodb-core to 2.0.11. +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. +* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). + +2.2.8 2016-08-23 +---------------- +* Updated mongodb-core to 2.0.10. +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.2.7 2016-08-19 +---------------- +* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). +* Updated mongodb-core to 2.0.9. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.2.6 2016-08-16 +---------------- +* Updated mongodb-core to 2.0.8. +* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Enable maxTimeMS in count, distinct, findAndModify. + +2.2.5 2016-07-28 +---------------- +* Updated mongodb-core to 2.0.7. +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. + +2.2.4 2016-07-19 +---------------- +* NPM corrupted upload fix. + +2.2.3 2016-07-19 +---------------- +* Updated mongodb-core to 2.0.6. +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.2.2 2016-07-15 +---------------- +* Updated mongodb-core to 2.0.5. +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.2.1 2016-07-11 +---------------- +* Updated mongodb-core to 2.0.4. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.2.0 2016-07-05 +---------------- +* Updated mongodb-core to 2.0.3. +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. +* Fixed logger error serialization issue. +* Documentation fixes. +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.1.21 2016-05-30 +----------------- +* Updated mongodb-core to 1.3.21. +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +2.1.20 2016-05-25 +----------------- +* Refactored MongoClient options handling to simplify the logic, unifying it. +* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Updated mongodb-core to 1.3.20. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +2.1.19 2016-05-17 +---------------- +* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +* Ensure replicaset topology destroy is never called by SDAM. +* Ensure all paths are correctly returned on inspectServer in replset. +* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. + +2.1.18 2016-04-27 +----------------- +* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. + +2.1.17 2016-04-26 +----------------- +* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. +* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. +* Fix timeout issue using new flags #1361. +* Updated mongodb-core to 1.3.17. +* Better handling of unique createIndex error. +* Emit error only if db instance has an error listener. +* DEFAULT authMechanism; don't throw error if explicitly set by user. + +2.1.16 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.16. + +2.1.15 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.15. +* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +2.1.14 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.13. +* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +2.1.13 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.12. + +2.1.12 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.11. +* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. +* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. +* isConnected method for mongos uses same selection code as getServer. +* Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +2.1.11 2016-03-23 +----------------- +* Updated mongodb-core to 1.3.10. +* Introducing simplified connections settings. + +2.1.10 2016-03-21 +----------------- +* Updated mongodb-core to 1.3.9. +* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) +* Forwards SDAM monitoring events from mongodb-core. + +2.1.9 2016-03-16 +---------------- +* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. +* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. + +2.1.8 2016-03-14 +---------------- +* Updated mongodb-core to 1.3.5. +* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. +* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +* Ensure RequestId can never be larger than Max Number integer size. +* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. +* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). +* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. +* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. +* NODE-663 added lookup helper on aggregation cursor. +* NODE-585 Result object specified incorrectly for findAndModify?. +* NODE-666 harden validation for findAndModify CRUD methods. + +2.1.7 2016-02-09 +---------------- +* NODE-656 fixed corner case where cursor count command could be left without a connection available. +* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. +* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). +* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). +* NODE-657 insertOne don`t return promise in some cases. +* Added destroy alias for abort function on GridFSBucketWriteStream. + +2.1.6 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/node_modules/mongoose/node_modules/mongodb/LICENSE.md b/node_modules/mongoose/node_modules/mongodb/LICENSE.md new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/README.md b/node_modules/mongoose/node_modules/mongodb/README.md new file mode 100644 index 0000000..596708c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/README.md @@ -0,0 +1,493 @@ +[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native | +| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org | + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a +case in our issue management tool, JIRA: + +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * Mailing List: [groups.google.com/forum/#!forum/node-mongodb-native](https://groups.google.com/forum/#!forum/node-mongodb-native) + * JIRA: [jira.mongodb.org](http://jira.mongodb.org) + +### Change Log + +Change history can be found in [`HISTORY.md`](HISTORY.md). + +# Installation + +The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +## MongoDB Driver + +Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. + +```bash +npm install mongodb --save +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +You can also use the [Yarn](https://yarnpkg.com/en) package manager. + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are: + +* [mongodb-core](https://github.com/mongodb-js/mongodb-core) +* [bson](https://github.com/mongodb/js-bson) +* [kerberos](https://github.com/mongodb-js/kerberos) +* [node-gyp](https://github.com/nodejs/node-gyp) + +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. + +**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** + +### Diagnosing on UNIX + +If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. + +```bash +git clone https://github.com/mongodb-js/kerberos +cd kerberos +npm install +``` + +If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: + +```bash +npm install -g node-gyp +``` + +If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. + +```bash +cd yourproject +npm install mongodb --save +``` + +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. + +```bash +npm --loglevel verbose install mongodb +``` + +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A compiler tool chain known to work for compiling `kerberos` on Windows is the following. + +* Visual Studio C++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. + +```bash +npm install -g node-gyp +``` + +Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: + +```bash +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues + +Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). + +Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. + +## Quick Start + +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init +``` + +Next, install the driver dependency. + +```bash +npm install mongodb --save +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). + +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a ``mongod`` process. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myproject**: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + client.close(); +}); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the collection"); + callback(result); + }); +} +``` + +The **insert** command returns an object with the following fields: + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Add the following code to call the **insertDocuments** function: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + client.close(); + }); +}); +``` + +Run the updated **app.js** file: + +```bash +node app.js +``` + +The operation returns the following output: + +```bash +Connected successfully to server +Inserted 3 documents into the collection +``` + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs) + callback(docs); + }); +} +``` + +This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + findDocuments(db, function() { + client.close(); + }); + }); +}); +``` + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({'a': 3}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs); + callback(docs); + }); +} +``` + +Only the documents which match ``'a' : 3`` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + client.close(); + }); + }); +}); +``` + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const removeDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Delete document where a is 3 + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +Add the new method to the **MongoClient.connect** callback function. + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + client.close(); + }); + }); + }); +}); +``` + +### Index a Collection + +[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. + +```js +const indexCollection = function(db, callback) { + db.collection('documents').createIndex( + { "a": 1 }, + null, + function(err, results) { + console.log(results); + callback(); + } + ); +}; +``` + +Add the ``indexCollection`` method to your app: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + indexCollection(db, function() { + client.close(); + }); + }); +}); +``` + +For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org) + * [Read about Schemas](http://learnmongodbthehardway.com) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) + +## License + +[Apache 2.0](LICENSE.md) + +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/node_modules/mongoose/node_modules/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/index.js new file mode 100644 index 0000000..fe305d6 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/index.js @@ -0,0 +1,67 @@ +'use strict'; + +// Core module +const core = require('mongodb-core'); +const Instrumentation = require('./lib/apm'); + +// Set up the connect function +const connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; +connect.MongoNetworkError = core.MongoNetworkError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/topologies/server'); +connect.ReplSet = require('./lib/topologies/replset'); +connect.Mongos = require('./lib/topologies/mongos'); +connect.ReadPreference = require('mongodb-core').ReadPreference; +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.AggregationCursor = require('./lib/aggregation_cursor'); +connect.CommandCursor = require('./lib/command_cursor'); +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); +// Exported to be used in tests not to be used anywhere else +connect.CoreServer = require('mongodb-core').Server; +connect.CoreConnection = require('mongodb-core').Connection; + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Int32 = core.BSON.Int32; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; +connect.BSONRegExp = core.BSON.BSONRegExp; +connect.Decimal128 = core.BSON.Decimal128; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const instrumentation = new Instrumentation(); + instrumentation.instrument(connect.MongoClient, callback); + return instrumentation; +}; + +// Set our exports to be the connect function +module.exports = connect; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/admin.js b/node_modules/mongoose/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..8fb4cac --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/admin.js @@ -0,0 +1,293 @@ +'use strict'; + +const executeOperation = require('./utils').executeOperation; +const applyWriteConcern = require('./utils').applyWriteConcern; + +const addUser = require('./operations/db_ops').addUser; +const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand; +const removeUser = require('./operations/db_ops').removeUser; +const replSetGetStatus = require('./operations/admin_ops').replSetGetStatus; +const serverStatus = require('./operations/admin_ops').serverStatus; +const validateCollection = require('./operations/admin_ops').validateCollection; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +function Admin(db, topology, promiseLibrary) { + if (!(this instanceof Admin)) return new Admin(db, topology); + + // Internal state + this.s = { + db: db, + topology: topology, + promiseLibrary: promiseLibrary + }; +} + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + command, + options, + callback + ]); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Retrieve this db's server status. + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.db.s.topology, serverStatus, [this, options, callback]); +}; + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { ping: 1 }; + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name to admin + options.dbName = 'admin'; + + return executeOperation(this.s.db.s.topology, addUser, [ + this.s.db, + username, + password, + options, + callback + ]); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name + options.dbName = 'admin'; + + return executeOperation(this.s.db.s.topology, removeUser, [ + this.s.db, + username, + options, + callback + ]); +}; + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options] Optional settings. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.db.s.topology, validateCollection, [ + this, + collectionName, + options, + callback + ]); +}; + +/** + * List the available databases + * + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { listDatabases: 1 }; + if (options.nameOnly) cmd.nameOnly = Number(cmd.nameOnly); + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Get ReplicaSet status + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.db.s.topology, replSetGetStatus, [this, options, callback]); +}; + +module.exports = Admin; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..e1bff13 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,407 @@ +'use strict'; + +const inherits = require('util').inherits; +const MongoError = require('mongodb-core').MongoError; +const Readable = require('stream').Readable; +const CoreCursor = require('./cursor'); + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary || Promise; + + // Set up + Readable.call(this, { objectMode: true }); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS, + // State + state: state, + // Stream options + streamOptions: streamOptions, + // BSON + bson: bson, + // Namespace + ns: ns, + // Command + cmd: cmd, + // Options + options: options, + // Topology + topology: topology, + // Topology Options + topologyOptions: topologyOptions, + // Promise library + promiseLibrary: promiseLibrary, + // Optional ClientSession + session: options.session + }; +}; + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Extend the Cursor +for (var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if (this.s.state === AggregationCursor.CLOSED || this.isDead()) + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + if (typeof value !== 'number') + throw MongoError.create({ message: 'batchSize requires an integer', drvier: true }); + if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +}; + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({ $geoNear: document }); + return this; +}; + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({ $group: document }); + return this; +}; + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({ $limit: value }); + return this; +}; + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({ $match: document }); + return this; +}; + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if (this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +}; + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({ $out: destination }); + return this; +}; + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({ $project: document }); + return this; +}; + +/** + * Add a lookup stage to the aggregation pipeline + * @method + * @param {object} document The lookup stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.lookup = function(document) { + this.s.cmd.pipeline.push({ $lookup: document }); + return this; +}; + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({ $redact: document }); + return this; +}; + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({ $skip: value }); + return this; +}; + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({ $sort: document }); + return this; +}; + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({ $unwind: field }); + return this; +}; + +/** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ +AggregationCursor.prototype.getLogger = function() { + return this.logger; +}; + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function AggregationCursor.prototype.hasNext + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/apm.js b/node_modules/mongoose/node_modules/mongodb/lib/apm.js new file mode 100644 index 0000000..f78e4aa --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/apm.js @@ -0,0 +1,31 @@ +'use strict'; +const EventEmitter = require('events').EventEmitter; + +class Instrumentation extends EventEmitter { + constructor() { + super(); + } + + instrument(MongoClient, callback) { + // store a reference to the original functions + this.$MongoClient = MongoClient; + const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); + + const instrumentation = this; + MongoClient.prototype.connect = function(callback) { + this.s.options.monitorCommands = true; + this.on('commandStarted', event => instrumentation.emit('started', event)); + this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); + this.on('commandFailed', event => instrumentation.emit('failed', event)); + return $prototypeConnect.call(this, callback); + }; + + if (typeof callback === 'function') callback(null, this); + } + + uninstrument() { + this.$MongoClient.prototype.connect = this.$prototypeConnect; + } +} + +module.exports = Instrumentation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/authenticate.js b/node_modules/mongoose/node_modules/mongodb/lib/authenticate.js new file mode 100644 index 0000000..35c92b4 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/authenticate.js @@ -0,0 +1,136 @@ +'use strict'; + +var shallowClone = require('./utils').shallowClone, + handleCallback = require('./utils').handleCallback, + MongoError = require('mongodb-core').MongoError, + f = require('util').format; + +var authenticate = function(client, username, password, options, callback) { + // Did the user destroy the topology + if (client.topology && client.topology.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.dbName; + authdb = options.authdb ? options.authdb : authdb; + authdb = options.authSource ? options.authSource : authdb; + + // Callback + var _callback = function(err, result) { + if (client.listeners('authenticated').length > 0) { + client.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + }; + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if (authMechanism === 'MONGODB-CR') { + client.topology.auth('mongocr', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'PLAIN') { + client.topology.auth('plain', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'MONGODB-X509') { + client.topology.auth('x509', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'SCRAM-SHA-1') { + client.topology.auth('scram-sha-1', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'SCRAM-SHA-256') { + client.topology.auth('scram-sha-256', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'GSSAPI') { + if (process.platform === 'win32') { + client.topology.auth('sspi', authdb, username, password, options, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + client.topology.auth('gssapi', authdb, username, password, options, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if (authMechanism === 'DEFAULT') { + client.topology.auth('default', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback( + callback, + MongoError.create({ + message: f('authentication mechanism %s not supported', options.authMechanism), + driver: true + }) + ); + } +}; + +module.exports = function(self, username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Shallow copy the options + options = shallowClone(options); + + // Set default mechanism + if (!options.authMechanism) { + options.authMechanism = 'DEFAULT'; + } else if ( + options.authMechanism !== 'GSSAPI' && + options.authMechanism !== 'DEFAULT' && + options.authMechanism !== 'MONGODB-CR' && + options.authMechanism !== 'MONGODB-X509' && + options.authMechanism !== 'SCRAM-SHA-1' && + options.authMechanism !== 'SCRAM-SHA-256' && + options.authMechanism !== 'PLAIN' + ) { + return handleCallback( + callback, + MongoError.create({ + message: + 'only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism', + driver: true + }) + ); + } + + // If we have a callback fallback + if (typeof callback === 'function') + return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; + // Reject error + if (err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new self.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; + // Reject error + if (err) return reject(err); + resolve(r); + }); + }); +}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..18c9ccf --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,1113 @@ +'use strict'; + +const Long = require('mongodb-core').BSON.Long; +const MongoError = require('mongodb-core').MongoError; +const toError = require('../utils').toError; +const handleCallback = require('../utils').handleCallback; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const ObjectID = require('mongodb-core').BSON.ObjectID; +const BSON = require('mongodb-core').BSON; + +// Error codes +const UNKNOWN_ERROR = 8; +const INVALID_BSON_ERROR = 22; +const WRITE_CONCERN_ERROR = 64; +const MULTIPLE_ERROR = 65; + +// Insert types +const INSERT = 1; +const UPDATE = 2; +const REMOVE = 3; + +const bson = new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp +]); + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * Wraps a legacy operation so we can correctly rewrite it's error + * @ignore + */ +class LegacyOp { + constructor(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; + } +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @return {BulkWriteResult} a BulkWriteResult instance + */ +class BulkWriteResult { + constructor(bulkResult) { + this.result = bulkResult; + } + + /** + * @return {boolean} ok Did bulk operation correctly execute + */ + get ok() { + return this.result.ok; + } + + /** + * @return {number} nInserted number of inserted documents + */ + get nInserted() { + return this.result.nInserted; + } + + /** + * @return {number} nUpserted Number of upserted documents + */ + get nUpserted() { + return this.result.nUpserted; + } + + /** + * @return {number} nMatched Number of matched documents + */ + get nMatched() { + return this.result.nMatched; + } + + /** + * @return {number} nModified Number of documents updated physically on disk + */ + get nModified() { + return this.result.nModified; + } + + /** + * @return {number} nRemoved Number of removed documents + */ + get nRemoved() { + return this.result.nRemoved; + } + + /** + * Return an array of inserted ids + * + * @return {object[]} + */ + getInsertedIds() { + return this.result.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + getUpsertedIds() { + return this.result.upserted; + } + + /** + * Return the upserted id at position x + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + getRawResponse() { + return this.result; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @param {number} index of the write error to return, returns null if there is no result for passed in index + * @return {WriteError} + */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + getWriteErrors() { + return this.result.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + getLastOp() { + return this.result.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return null; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); + } + } + + /** + * @return {BulkWriteResult} a BulkWriteResult instance + */ + toJSON() { + return this.result; + } + + /** + * @return {string} + */ + toString() { + return `BulkWriteResult(${this.toJSON(this.result)})`; + } + + /** + * @return {boolean} + */ + isOk() { + return this.result.ok === 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @return {WriteConcernError} a WriteConcernError instance + */ +class WriteConcernError { + constructor(err) { + this.err = err; + } + + /** + * @return {number} code Write concern error code. + */ + get code() { + return this.err.code; + } + + /** + * @return {string} errmsg Write concern error message. + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, errmsg: this.err.errmsg }; + } + + /** + * @return {string} + */ + toString() { + return `WriteConcernError(${this.err.errmsg})`; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @return {WriteConcernError} a WriteConcernError instance + */ +class WriteError { + constructor(err) { + this.err = err; + } + + /** + * @return {number} code Write concern error code. + */ + get code() { + return this.err.code; + } + + /** + * @return {number} index Write concern error original bulk operation index. + */ + get index() { + return this.err.index; + } + + /** + * @return {string} errmsg Write concern error message. + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * Define access methods + * @return {object} + */ + getOperation() { + return this.err.op; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + /** + * @return {string} + */ + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +function mergeBatchResults(ordered, batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } else if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if (bulkResult.lastOp) { + lastOpTS = + typeof bulkResult.lastOp.ts === 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) + : bulkResult.lastOp.ts; + lastOpT = + typeof bulkResult.lastOp.t === 'number' + ? Long.fromNumber(bulkResult.lastOp.t) + : bulkResult.lastOp.t; + } + + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // If we have an insert Batch type + if (batch.batchType === INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (batch.batchType === REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (batch.batchType === UPDATE && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index, + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +/** + * handles write concern error + * + * @param {object} batch + * @param {object} bulkResult + * @param {boolean} ordered + * @param {WriteConcernError} err + * @param {function} callback + */ +function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) { + mergeBatchResults(ordered, batch, bulkResult, null, err.result); + + const wrappedWriteConcernError = new WriteConcernError({ + errmsg: err.result.writeConcernError.errmsg, + code: err.result.writeConcernError.result + }); + return handleCallback( + callback, + new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), + null + ); +} + +/** + * Creates a new BulkWriteError + * + * @class + * @param {Error|string|object} message The error message + * @param {BulkWriteResult} result The result of the bulk write operation + * @return {BulkWriteError} A BulkWriteError instance + * @extends {MongoError} + */ +class BulkWriteError extends MongoError { + constructor(error, result) { + const message = error.err || error.errmsg || error.errMessage || error; + super(message); + + Object.assign(this, error); + + this.name = 'BulkWriteError'; + this.result = result; + } +} + +/** + * Handles the find operators for the bulk operations + * @class + */ +class FindOperators { + /** + * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation + */ + constructor(bulkOperation) { + this.s = bulkOperation.s; + } + + /** + * Add a single update document to the bulk operation + * + * @method + * @param {object} updateDocument update operations + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + update(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: true, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} updateDocument update operations + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + updateOne(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: false, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} updateDocument the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation|UnorderedBulkOperation} + */ + replaceOne(updateDocument) { + this.updateOne(updateDocument); + } + + /** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperators} + */ + upsert() { + this.s.currentOp.upsert = true; + return this; + } + + /** + * Add a delete one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + deleteOne() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 1 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * Add a delete operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + delete() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 0 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * backwards compatability for deleteOne + */ + removeOne() { + return this.deleteOne(); + } + + /** + * backwards compatability for delete + */ + remove() { + return this.delete(); + } +} + +/** + * Parent class to OrderedBulkOperation and UnorderedBulkOperation + * @class + */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + constructor(topology, collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.collectionName; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + const bson = topology.bson; + + // Set max byte size + const isMaster = topology.lastIsMaster(); + const maxBatchSizeBytes = + isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxWriteBatchSize = + isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); + const writeConcern = finalOptions.writeConcern; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult, + // Current batch state + currentBatch: null, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: null, + currentUpdateBatch: null, + currentRemoveBatch: null, + batches: [], + // Write concern + writeConcern: writeConcern, + // Max batch size options + maxBatchSizeBytes: maxBatchSizeBytes, + maxWriteBatchSize: maxWriteBatchSize, + maxKeySize, + // Namespace + namespace: namespace, + // BSON + bson: bson, + // Topology + topology: topology, + // Options + options: finalOptions, + // Current operation + currentOp: currentOp, + // Executed + executed: executed, + // Collection + collection: collection, + // Promise Library + promiseLibrary: promiseLibrary, + // Fundamental error + err: null, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @param {object} document the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation|UnorderedBulkOperation} + */ + insert(document) { + if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) + document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, document); + } + + /** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + */ + find(selector) { + if (!selector) { + throw toError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** + * Raw performs the bulk operation + * + * @method + * @param {object} op operation + * @return {OrderedBulkOperation|UnorderedBulkOperation} + */ + raw(op) { + const key = Object.keys(op)[0]; + + // Set up the force server object id + const forceServerObjectId = + typeof this.s.options.forceServerObjectId === 'boolean' + ? this.s.options.forceServerObjectId + : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if ( + (op.updateOne && op.updateOne.q) || + (op.updateMany && op.updateMany.q) || + (op.replaceOne && op.replaceOne.q) + ) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return this.s.options.addToOperationsList(this, UPDATE, op[key]); + } + + // Crud spec update format + if (op.updateOne || op.updateMany || op.replaceOne) { + const multi = op.updateOne || op.replaceOne ? false : true; + const operation = { + q: op[key].filter, + u: op[key].update || op[key].replacement, + multi: multi + }; + if (this.isOrdered) { + operation.upsert = op[key].upsert ? true : false; + if (op.collation) operation.collation = op.collation; + } else { + if (op[key].upsert) operation.upsert = true; + } + if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; + return this.s.options.addToOperationsList(this, UPDATE, operation); + } + + // Remove operations + if ( + op.removeOne || + op.removeMany || + (op.deleteOne && op.deleteOne.q) || + (op.deleteMany && op.deleteMany.q) + ) { + op[key].limit = op.removeOne ? 1 : 0; + return this.s.options.addToOperationsList(this, REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if (op.deleteOne || op.deleteMany) { + const limit = op.deleteOne ? 1 : 0; + const operation = { q: op[key].filter, limit: limit }; + if (this.isOrdered) { + if (op.collation) operation.collation = op.collation; + } + return this.s.options.addToOperationsList(this, REMOVE, operation); + } + + // Insert operations + if (op.insertOne && op.insertOne.document == null) { + if (forceServerObjectId !== true && op.insertOne._id == null) + op.insertOne._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne); + } else if (op.insertOne && op.insertOne.document) { + if (forceServerObjectId !== true && op.insertOne.document._id == null) + op.insertOne.document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); + } + + if (op.insertMany) { + for (let i = 0; i < op.insertMany.length; i++) { + if (forceServerObjectId !== true && op.insertMany[i]._id == null) + op.insertMany[i]._id = new ObjectID(); + this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError( + 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' + ); + } + + /** + * Execute next write command in a chain + * + * @method + * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation + * @param {object} writeConcern + * @param {object} options + * @param {function} callback + */ + bulkExecute(_writeConcern, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.s.executed) { + const executedError = toError('batch cannot be re-executed'); + return typeof callback === 'function' + ? callback(executedError, null) + : this.s.promiseLibrary.reject(executedError); + } + + if (typeof _writeConcern === 'function') { + callback = _writeConcern; + } else if (_writeConcern && typeof _writeConcern === 'object') { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = toError('Invalid Operation, no operations specified'); + return typeof callback === 'function' + ? callback(emptyBatchError, null) + : this.s.promiseLibrary.reject(emptyBatchError); + } + return { options, callback }; + } + + /** + * Handles final options before executing command + * + * @param {object} config + * @param {object} config.options + * @param {number} config.batch + * @param {function} config.resultHandler + * @param {function} callback + */ + finalOptionsHandler(config, callback) { + const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); + if (this.s.writeConcern != null) { + finalOptions.writeConcern = this.s.writeConcern; + } + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (this.operationId) { + config.resultHandler.operationId = this.operationId; + } + + // Serialize functions + if (this.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true; + } + + // Ignore undefined + if (this.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true; + } + + // Is the bypassDocumentValidation options specific + if (this.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (this.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (config.batch.batchType === UPDATE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); + } + + if (config.batch.batchType === REMOVE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); + } + } + + try { + if (config.batch.batchType === INSERT) { + this.s.topology.insert( + this.s.collection.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === UPDATE) { + this.s.topology.update( + this.s.collection.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === REMOVE) { + this.s.topology.remove( + this.s.collection.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback( + callback, + null, + mergeBatchResults(false, config.batch, this.s.bulkResult, err, null) + ); + } + } + + /** + * Handles the write error before executing commands + * + * @param {function} callback + * @param {BulkWriteResult} writeResult + * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + if (this.s.bulkResult.writeErrors.length === 1) { + handleCallback( + callback, + new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), + null + ); + return true; + } + + handleCallback( + callback, + new BulkWriteError( + toError({ + message: 'write operation failed', + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }), + writeResult + ), + null + ); + return true; + } else if (writeResult.getWriteConcernError()) { + handleCallback( + callback, + new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), + null + ); + return true; + } + } +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// Exports symbols +module.exports = { + Batch, + BulkOperationBase, + BulkWriteError, + BulkWriteResult, + bson, + FindOperators, + handleMongoWriteConcernError, + LegacyOp, + mergeBatchResults, + INVALID_BSON_ERROR: INVALID_BSON_ERROR, + MULTIPLE_ERROR: MULTIPLE_ERROR, + UNKNOWN_ERROR: UNKNOWN_ERROR, + WRITE_CONCERN_ERROR: WRITE_CONCERN_ERROR, + INSERT: INSERT, + UPDATE: UPDATE, + REMOVE: REMOVE, + WriteError, + WriteConcernError +}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..9f8e4b5 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,182 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const utils = require('../utils'); +const toError = utils.toError; +const handleCallback = utils.handleCallback; +const BulkWriteResult = common.BulkWriteResult; +const Batch = common.Batch; +const mergeBatchResults = common.mergeBatchResults; +const executeOperation = utils.executeOperation; +const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError; +const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError; +const bson = common.bson; +const isPromiseLike = require('../utils').isPromiseLike; + +/** + * Add to internal list of Operations + * + * @param {OrderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {OrderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false + }); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Reset the current size trackers + bulkOperation.s.currentBatchSize = 0; + bulkOperation.s.currentBatchSizeBytes = 0; + } + + if (docType === common.INSERT) { + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.currentIndex, + _id: document._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatchSize += 1; + bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; + bulkOperation.s.currentIndex += 1; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ + +class OrderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, true); + } + + /** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + if (isPromiseLike(ret)) { + return ret; + } + + options = ret.options; + callback = ret.callback; + + return executeOperation(this.s.topology, executeCommands, [this, options, callback]); + } +} + +/** + * Execute next write command in a chain + * + * @param {OrderedBulkOperation} bulkOperation + * @param {object} options + * @param {function} callback + */ +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + // Ordered execution of the command + const batch = bulkOperation.s.batches.shift(); + + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return handleCallback(callback, null, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeOrderedBulkOp(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..563777b --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,219 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const utils = require('../utils'); +const toError = utils.toError; +const handleCallback = utils.handleCallback; +const BulkWriteResult = common.BulkWriteResult; +const Batch = common.Batch; +const mergeBatchResults = common.mergeBatchResults; +const executeOperation = utils.executeOperation; +const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError; +const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError; +const bson = common.bson; +const isPromiseLike = require('../utils').isPromiseLike; + +/** + * Add to internal list of Operations + * + * @param {UnorderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {UnorderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + // Holds the current batch + bulkOperation.s.currentBatch = null; + // Get the right type of batch + if (docType === common.INSERT) { + bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; + } else if (docType === common.UPDATE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; + } + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (docType === common.INSERT) { + bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.bulkResult.insertedIds.length, + _id: document._id + }); + } else if (docType === common.UPDATE) { + bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; + } + + // Update current batch size + bulkOperation.s.currentBatch.size += 1; + bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +class UnorderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, false); + } + + /** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + if (isPromiseLike(ret)) { + return ret; + } + + options = ret.options; + callback = ret.callback; + + return executeOperation(this.s.topology, executeBatches, [this, options, callback]); + } +} + +/** + * Execute the command + * + * @param {UnorderedBulkOperation} bulkOperation + * @param {object} batch + * @param {object} options + * @param {function} callback + */ +function executeBatch(bulkOperation, batch, options, callback) { + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback); + } + handleCallback( + callback, + null, + mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result) + ); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * Execute all the commands + * + * @param {UnorderedBulkOperation} bulkOperation + * @param {object} options + * @param {function} callback + */ +function executeBatches(bulkOperation, options, callback) { + let numberOfCommandsToExecute = bulkOperation.s.batches.length; + let hasErrored = false; + // Execute over all the batches + for (let i = 0; i < bulkOperation.s.batches.length; i++) { + executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) { + if (hasErrored) { + return; + } + + if (err) { + hasErrored = true; + return handleCallback(callback, err); + } + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if (numberOfCommandsToExecute === 0) { + // Driver level error + if (err) return handleCallback(callback, err); + + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + return handleCallback(callback, null, writeResult); + } + }); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeUnorderedBulkOp(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/change_stream.js b/node_modules/mongoose/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 0000000..21f2428 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,469 @@ +'use strict'; + +const EventEmitter = require('events'); +const isResumableError = require('./error').isResumableError; +const MongoError = require('mongodb-core').MongoError; + +var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference']; + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @class ChangeStream + * @since 3.0.0 + * @param {(MongoClient|Db|Collection)} changeDomain The domain against which to create the change stream + * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @fires ChangeStream#close + * @fires ChangeStream#change + * @fires ChangeStream#end + * @fires ChangeStream#error + * @return {ChangeStream} a ChangeStream instance. + */ + +class ChangeStream extends EventEmitter { + constructor(changeDomain, pipeline, options) { + super(); + const Collection = require('./collection'); + const Db = require('./db'); + const MongoClient = require('./mongo_client'); + + this.pipeline = pipeline || []; + this.options = options || {}; + this.cursorNamespace = undefined; + this.namespace = {}; + + if (changeDomain instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + this.topology = changeDomain.s.db.serverConfig; + + this.namespace = { + collection: changeDomain.collectionName, + database: changeDomain.s.db.databaseName + }; + + this.cursorNamespace = `${this.namespace.database}.${this.namespace.collection}`; + } else if (changeDomain instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + this.namespace = { collection: '', database: changeDomain.databaseName }; + this.cursorNamespace = this.namespace.database; + this.topology = changeDomain.serverConfig; + } else if (changeDomain instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + this.namespace = { collection: '', database: 'admin' }; + this.cursorNamespace = this.namespace.database; + this.topology = changeDomain.topology; + } else { + throw new TypeError( + 'changeDomain provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' + ); + } + + this.promiseLibrary = changeDomain.s.promiseLibrary; + if (!this.options.readPreference && changeDomain.s.readPreference) { + this.options.readPreference = changeDomain.s.readPreference; + } + + // We need to get the operationTime as early as possible + const isMaster = this.topology.lastIsMaster(); + if (!isMaster) { + throw new MongoError('Topology does not have an ismaster yet.'); + } + + this.operationTime = isMaster.operationTime; + + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this); + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this.cursor.on('data', change => + processNewChange({ changeStream: this, change, eventEmitter: true }) + ); + } + }); + + // Listen for all `change` listeners being removed from ChangeStream + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this.cursor.removeAllListeners('data'); + } + }); + } + + /** + * Check if there is any document still available in the Change Stream + * @function ChangeStream.prototype.hasNext + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + return this.cursor.hasNext(callback); + } + + /** + * Get the next available document from the Change Stream, returns null if no more documents are available. + * @function ChangeStream.prototype.next + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + var self = this; + if (this.isClosed()) { + if (callback) return callback(new Error('Change Stream is not open.'), null); + return self.promiseLibrary.reject(new Error('Change Stream is not open.')); + } + + return this.cursor + .next() + .then(change => processNewChange({ changeStream: self, change, callback })) + .catch(error => processNewChange({ changeStream: self, error, callback })); + } + + /** + * Is the cursor closed + * @method ChangeStream.prototype.isClosed + * @return {boolean} + */ + isClosed() { + if (this.cursor) { + return this.cursor.isClosed(); + } + return true; + } + + /** + * Close the Change Stream + * @method ChangeStream.prototype.close + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(callback) { + if (!this.cursor) { + if (callback) return callback(); + return this.promiseLibrary.resolve(); + } + + // Tidy up the existing cursor + var cursor = this.cursor; + delete this.cursor; + return cursor.close(callback); + } + + /** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @method + * @param {Writable} destination The destination for writing data + * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} + * @return {null} + */ + pipe(destination, options) { + if (!this.pipeDestinations) { + this.pipeDestinations = []; + } + this.pipeDestinations.push(destination); + return this.cursor.pipe(destination, options); + } + + /** + * This method will remove the hooks set up for a previous pipe() call. + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + unpipe(destination) { + if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { + this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); + } + return this.cursor.unpipe(destination); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ + stream(options) { + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** + * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @return {null} + */ + pause() { + return this.cursor.pause(); + } + + /** + * This method will cause the readable stream to resume emitting data events. + * @return {null} + */ + resume() { + return this.cursor.resume(); + } +} + +// Create a new change stream cursor based on self's configuration +var createChangeStreamCursor = function(self) { + if (self.resumeToken) { + self.options.resumeAfter = self.resumeToken; + } + + var changeStreamCursor = buildChangeStreamAggregationCommand(self); + + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * + * @event ChangeStream#change + * @type {object} + */ + if (self.listenerCount('change') > 0) { + changeStreamCursor.on('data', function(change) { + processNewChange({ changeStream: self, change, eventEmitter: true }); + }); + } + + /** + * Change stream close event + * + * @event ChangeStream#close + * @type {null} + */ + changeStreamCursor.on('close', function() { + self.emit('close'); + }); + + /** + * Change stream end event + * + * @event ChangeStream#end + * @type {null} + */ + changeStreamCursor.on('end', function() { + self.emit('end'); + }); + + /** + * Fired when the stream encounters an error. + * + * @event ChangeStream#error + * @type {Error} + */ + changeStreamCursor.on('error', function(error) { + processNewChange({ changeStream: self, error, eventEmitter: true }); + }); + + if (self.pipeDestinations) { + const cursorStream = changeStreamCursor.stream(self.streamOptions); + for (let pipeDestination in self.pipeDestinations) { + cursorStream.pipe(pipeDestination); + } + } + + return changeStreamCursor; +}; + +function getResumeToken(self) { + return self.resumeToken || self.options.resumeAfter; +} + +function getStartAtOperationTime(self) { + const isMaster = self.topology.lastIsMaster() || {}; + return ( + isMaster.maxWireVersion && isMaster.maxWireVersion >= 7 && self.options.startAtOperationTime + ); +} + +var buildChangeStreamAggregationCommand = function(self) { + const topology = self.topology; + const namespace = self.namespace; + const pipeline = self.pipeline; + const options = self.options; + const cursorNamespace = self.cursorNamespace; + + var changeStreamStageOptions = { + fullDocument: options.fullDocument || 'default' + }; + + const resumeToken = getResumeToken(self); + const startAtOperationTime = getStartAtOperationTime(self); + if (resumeToken) { + changeStreamStageOptions.resumeAfter = resumeToken; + } + + if (startAtOperationTime) { + changeStreamStageOptions.startAtOperationTime = startAtOperationTime; + } + + // Map cursor options + var cursorOptions = {}; + cursorOptionNames.forEach(function(optionName) { + if (options[optionName]) { + cursorOptions[optionName] = options[optionName]; + } + }); + + if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + + var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }]; + + changeStreamPipeline = changeStreamPipeline.concat(pipeline); + + var command = { + aggregate: self.type === CHANGE_DOMAIN_TYPES.COLLECTION ? namespace.collection : 1, + pipeline: changeStreamPipeline, + readConcern: { level: 'majority' }, + cursor: { + batchSize: options.batchSize || 1 + } + }; + + // Create and return the cursor + return topology.cursor(cursorNamespace, command, cursorOptions); +}; + +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected(topology, options, callback) { + setTimeout(() => { + if (options && options.start == null) options.start = process.hrtime(); + const start = options.start || process.hrtime(); + const timeout = options.timeout || SELECTION_TIMEOUT; + const readPreference = options.readPreference; + + if (topology.isConnected({ readPreference })) return callback(null, null); + const hrElapsed = process.hrtime(start); + const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; + if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); + waitForTopologyConnected(topology, options, callback); + }, 3000); // this is an arbitrary wait time to allow SDAM to transition +} + +// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. +function processNewChange(args) { + const changeStream = args.changeStream; + const error = args.error; + const change = args.change; + const callback = args.callback; + const eventEmitter = args.eventEmitter || false; + + // If the changeStream is closed, then it should not process a change. + if (changeStream.isClosed()) { + // We do not error in the eventEmitter case. + if (eventEmitter) { + return; + } + + const error = new MongoError('ChangeStream is closed'); + return typeof callback === 'function' + ? callback(error, null) + : changeStream.promiseLibrary.reject(error); + } + + const topology = changeStream.topology; + const options = changeStream.cursor.options; + + if (error) { + if (isResumableError(error) && !changeStream.attemptingResume) { + changeStream.attemptingResume = true; + + if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) { + const startAtOperationTime = changeStream.cursor.cursorState.operationTime; + changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options); + } + + // stop listening to all events from old cursor + ['data', 'close', 'end', 'error'].forEach(event => + changeStream.cursor.removeAllListeners(event) + ); + + // close internal cursor, ignore errors + changeStream.cursor.close(); + + // attempt recreating the cursor + if (eventEmitter) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return changeStream.emit('error', err); + changeStream.cursor = createChangeStreamCursor(changeStream); + }); + + return; + } + + if (callback) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return callback(err, null); + + changeStream.cursor = createChangeStreamCursor(changeStream); + changeStream.next(callback); + }); + + return; + } + + return new Promise((resolve, reject) => { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return reject(err); + resolve(); + }); + }) + .then(() => (changeStream.cursor = createChangeStreamCursor(changeStream))) + .then(() => changeStream.next()); + } + + if (eventEmitter) return changeStream.emit('error', error); + if (typeof callback === 'function') return callback(error, null); + return changeStream.promiseLibrary.reject(error); + } + + changeStream.attemptingResume = false; + + // Cache the resume token if it is present. If it is not present return an error. + if (!change || !change._id) { + var noResumeTokenError = new Error( + 'A change stream document has been received that lacks a resume token (_id).' + ); + + if (eventEmitter) return changeStream.emit('error', noResumeTokenError); + if (typeof callback === 'function') return callback(noResumeTokenError, null); + return changeStream.promiseLibrary.reject(noResumeTokenError); + } + + changeStream.resumeToken = change._id; + + // Return the change + if (eventEmitter) return changeStream.emit('change', change); + if (typeof callback === 'function') return callback(error, change); + return changeStream.promiseLibrary.resolve(change); +} + +/** + * The callback format for results + * @callback ChangeStream~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +module.exports = ChangeStream; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/collection.js b/node_modules/mongoose/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..b5b1782 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/collection.js @@ -0,0 +1,2099 @@ +'use strict'; + +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const checkCollectionName = require('./utils').checkCollectionName; +const ObjectID = require('mongodb-core').BSON.ObjectID; +const AggregationCursor = require('./aggregation_cursor'); +const MongoError = require('mongodb-core').MongoError; +const toError = require('./utils').toError; +const normalizeHintField = require('./utils').normalizeHintField; +const handleCallback = require('./utils').handleCallback; +const decorateCommand = require('./utils').decorateCommand; +const decorateWithCollation = require('./utils').decorateWithCollation; +const decorateWithReadConcern = require('./utils').decorateWithReadConcern; +const formattedOrderClause = require('./utils').formattedOrderClause; +const ReadPreference = require('mongodb-core').ReadPreference; +const CommandCursor = require('./command_cursor'); +const unordered = require('./bulk/unordered'); +const ordered = require('./bulk/ordered'); +const ChangeStream = require('./change_stream'); +const executeOperation = require('./utils').executeOperation; +const applyWriteConcern = require('./utils').applyWriteConcern; +const resolveReadPreference = require('./utils').resolveReadPreference; + +// Operations +const bulkWrite = require('./operations/collection_ops').bulkWrite; +const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; +const count = require('./operations/collection_ops').count; +const countDocuments = require('./operations/collection_ops').countDocuments; +const createIndex = require('./operations/collection_ops').createIndex; +const createIndexes = require('./operations/collection_ops').createIndexes; +const deleteMany = require('./operations/collection_ops').deleteMany; +const deleteOne = require('./operations/collection_ops').deleteOne; +const distinct = require('./operations/collection_ops').distinct; +const dropIndex = require('./operations/collection_ops').dropIndex; +const dropIndexes = require('./operations/collection_ops').dropIndexes; +const ensureIndex = require('./operations/collection_ops').ensureIndex; +const findAndModify = require('./operations/collection_ops').findAndModify; +const findAndRemove = require('./operations/collection_ops').findAndRemove; +const findOne = require('./operations/collection_ops').findOne; +const findOneAndDelete = require('./operations/collection_ops').findOneAndDelete; +const findOneAndReplace = require('./operations/collection_ops').findOneAndReplace; +const findOneAndUpdate = require('./operations/collection_ops').findOneAndUpdate; +const geoHaystackSearch = require('./operations/collection_ops').geoHaystackSearch; +const group = require('./operations/collection_ops').group; +const indexes = require('./operations/collection_ops').indexes; +const indexExists = require('./operations/collection_ops').indexExists; +const indexInformation = require('./operations/collection_ops').indexInformation; +const insertOne = require('./operations/collection_ops').insertOne; +const isCapped = require('./operations/collection_ops').isCapped; +const mapReduce = require('./operations/collection_ops').mapReduce; +const optionsOp = require('./operations/collection_ops').optionsOp; +const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; +const prepareDocs = require('./operations/collection_ops').prepareDocs; +const reIndex = require('./operations/collection_ops').reIndex; +const removeDocuments = require('./operations/collection_ops').removeDocuments; +const rename = require('./operations/collection_ops').rename; +const replaceOne = require('./operations/collection_ops').replaceOne; +const save = require('./operations/collection_ops').save; +const stats = require('./operations/collection_ops').stats; +const updateDocuments = require('./operations/collection_ops').updateDocuments; +const updateMany = require('./operations/collection_ops').updateMany; +const updateOne = require('./operations/collection_ops').updateOne; + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + */ + +const mergeKeys = ['ignoreUndefined']; + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +function Collection(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + + // Unpack variables + const internalHint = null; + const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + const serializeFunctions = + options == null || options.serializeFunctions == null + ? db.s.options.serializeFunctions + : options.serializeFunctions; + const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; + const promoteLongs = + options == null || options.promoteLongs == null + ? db.s.options.promoteLongs + : options.promoteLongs; + const promoteValues = + options == null || options.promoteValues == null + ? db.s.options.promoteValues + : options.promoteValues; + const promoteBuffers = + options == null || options.promoteBuffers == null + ? db.s.options.promoteBuffers + : options.promoteBuffers; + let readPreference = null; + const collectionHint = null; + const namespace = `${dbName}.${name}`; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Assign the right collection level readPreference + if (options && options.readPreference) { + readPreference = options.readPreference; + } else if (db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null ? ObjectID : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory, + // Db + db: db, + // Topology + topology: topology, + // dbName + dbName: dbName, + // Options + options: options, + // Namespace + namespace: namespace, + // Read preference + readPreference: readPreference, + // SlaveOK + slaveOk: slaveOk, + // Serialize functions + serializeFunctions: serializeFunctions, + // Raw + raw: raw, + // promoteLongs + promoteLongs: promoteLongs, + // promoteValues + promoteValues: promoteValues, + // promoteBuffers + promoteBuffers: promoteBuffers, + // internalHint + internalHint: internalHint, + // collectionHint + collectionHint: collectionHint, + // Name + name: name, + // Promise library + promiseLibrary: promiseLibrary, + // Read Concern + readConcern: options.readConcern, + // Write Concern + writeConcern: options.writeConcern + }; +} + +Object.defineProperty(Collection.prototype, 'dbName', { + enumerable: true, + get: function() { + return this.s.dbName; + } +}); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, + get: function() { + return this.s.name; + } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace; + } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, + get: function() { + return this.s.readConcern || { level: 'local' }; + } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable: true, + get: function() { + let ops = {}; + if (this.s.writeConcern) { + return this.s.writeConcern; + } + + if (this.s.options.w != null) ops.w = this.s.options.w; + if (this.s.options.j != null) ops.j = this.s.options.j; + if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, 'hint', { + enumerable: true, + get: function() { + return this.s.collectionHint; + }, + set: function(v) { + this.s.collectionHint = normalizeHintField(v); + } +}); + +const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} [query={}] The cursor query object. + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `find()` must be a callback or undefined'); + } + + let selector = query; + // figuring out arguments + if (typeof callback !== 'function') { + if (typeof options === 'function') { + callback = options; + options = undefined; + } else if (options == null) { + callback = typeof selector === 'function' ? selector : undefined; + selector = typeof selector === 'object' ? selector : undefined; + } + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + const object = selector; + if (Buffer.isBuffer(object)) { + const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); + if (object_size !== object.length) { + const error = new Error( + 'query selector raw message size does not match message header size [' + + object.length + + '] != [' + + object_size + + ']' + ); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if (selector != null && selector._bsontype === 'ObjectID') { + selector = { _id: selector }; + } + + if (!options) options = {}; + + let projection = options.projection || options.fields; + + if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + // Make a shallow copy of options + let newOptions = Object.assign({}, options); + + // Make a shallow copy of the collection options + for (let key in this.s.options) { + if (mergeKeys.indexOf(key) !== -1) { + newOptions[key] = this.s.options[key]; + } + } + + // Unpack options + newOptions.skip = options.skip ? options.skip : 0; + newOptions.limit = options.limit ? options.limit : 0; + newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = + options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions.readPreference = resolveReadPreference(newOptions, { + db: this.s.db, + collection: this + }); + + // Set slave ok to true if read preference different from primary + if ( + newOptions.readPreference != null && + (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') + ) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if (selector != null && typeof selector !== 'object') { + throw MongoError.create({ message: 'query selector must be an object', driver: true }); + } + + // Build the find command + const findCommand = { + find: this.s.namespace, + limit: newOptions.limit, + skip: newOptions.skip, + query: selector + }; + + // Ensure we use the right await data option + if (typeof newOptions.awaitdata === 'boolean') { + newOptions.awaitData = newOptions.awaitdata; + } + + // Translate to new command option noCursorTimeout + if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + decorateCommand(findCommand, newOptions, ['session', 'collation']); + + if (projection) findCommand.fields = projection; + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; + // Set promoteLongs if available at collection level + if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') + newOptions.promoteLongs = this.s.promoteLongs; + if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') + newOptions.promoteValues = this.s.promoteValues; + if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') + newOptions.promoteBuffers = this.s.promoteBuffers; + + // Sort options + if (findCommand.sort) { + findCommand.sort = formattedOrderClause(findCommand.sort); + } + + // Set the readConcern + decorateWithReadConcern(findCommand, this, options); + + // Decorate find command with collation options + try { + decorateWithCollation(findCommand, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + const cursor = this.s.topology.cursor(this.s.namespace, findCommand, newOptions); + + return typeof callback === 'function' ? handleCallback(callback, null, cursor) : cursor; + } +); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, insertOne, [this, doc, options, callback]); +}; + +function mapInsertManyResults(docs, r) { + const finalResult = { + result: { ok: 1, n: r.insertedCount }, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: r.insertedIds + }; + + if (r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + if (!Array.isArray(docs) && typeof callback === 'function') { + return callback( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + } else if (!Array.isArray(docs)) { + return new this.s.promiseLibrary((resolve, reject) => { + reject( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + }); + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || this.s.serializeFunctions; + + docs = prepareDocs(this, docs, options); + + // Generate the bulk write operations + const operations = [ + { + insertMany: docs + } + ]; + + return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback], { + resultMutator: result => mapInsertManyResults(docs, result) + }); +}; + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {BulkWriteError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); + } + + return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback]); +}; + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = deprecate(function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + * @property {Object} message + * @property {Array} ops + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document in a collection + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, updateOne, [this, filter, update, options, callback]); +}; + +/** + * Replace a document in a collection with another document + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, replaceOne, [this, filter, doc, options, callback]); +}; + +/** + * Update multiple documents in a collection + * @method + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, updateMany, [this, filter, update, options, callback]); +}; + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = deprecate(function(selector, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, updateDocuments, [ + this, + selector, + update, + options, + callback + ]); +}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document from a collection + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, deleteOne, [this, filter, options, callback]); +}; + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +/** + * Delete multiple documents from a collection + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, deleteMany, [this, filter, options, callback]); +}; + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = deprecate(function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, removeDocuments, [this, selector, options, callback]); +}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = deprecate(function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, save, [this, doc, options, callback]); +}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * The callback format for an aggregation call + * @callback Collection~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOne = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `findOne()` must be a callback or undefined'); + } + + if (typeof query === 'function') (callback = query), (query = {}), (options = {}); + if (typeof options === 'function') (callback = options), (options = {}); + query = query || {}; + options = options || {}; + + return executeOperation(this.s.topology, findOne, [this, query, options, callback]); + } +); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + return executeOperation(this.s.topology, rename, [this, newName, options, callback]); +}; + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, this.s.db.dropCollection.bind(this.s.db), [ + this.s.name, + options, + callback + ]); +}; + +/** + * Returns the options of the collection. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(opts, callback) { + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + return executeOperation(this.s.topology, optionsOp, [this, opts, callback]); +}; + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, isCapped, [this, options, callback]); +}; + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, createIndex, [this, fieldOrSpec, options, callback]); +}; + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + return executeOperation(this.s.topology, createIndexes, [this, indexSpecs, options, callback]); +}; + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation(this.s.topology, dropIndex, [this, indexName, options, callback]); +}; + +/** + * Drops all indexes from this collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + return executeOperation(this.s.topology, dropIndexes, [this, options, callback]); +}; + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = deprecate( + Collection.prototype.dropIndexes, + 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' +); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, reIndex, [this, options, callback]); +}; + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = Object.assign({}, options); + // Determine the read preference in the options. + options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // Cursor options + let cursor = options.batchSize ? { batchSize: options.batchSize } : {}; + + // We have a list collections command + if (this.s.topology.capabilities().hasListIndexesCommand) { + // Build the command + const command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + cursor = this.s.topology.cursor(`${this.s.dbName}.$cmd`, command, options); + // Do we have a readPreference, apply it + if (options.readPreference) cursor.setReadPreference(options.readPreference); + // Return the cursor + return cursor; + } + + // Get the namespace + const ns = `${this.s.dbName}.system.indexes`; + // Get the query + cursor = this.s.topology.cursor(ns, { find: ns, query: { ns: this.s.namespace } }, options); + // Do we have a readPreference, apply it + if (options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if (options.batchSize) cursor = cursor.batchSize(options.batchSize); + // Return the cursor + return cursor; +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, ensureIndex, [this, fieldOrSpec, options, callback]); +}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, indexExists, [this, indexes, options, callback]); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, indexInformation, [this, options, callback]); +}; + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} [query={}] The query for the count. + * @param {object} [options] Optional settings. + * @param {boolean} [options.limit] The limit of documents to count. + * @param {boolean} [options.skip] The number of documents to skip for the count. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead + */ +Collection.prototype.count = deprecate(function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, count, [this, query, options, callback]); +}, 'collection.count is deprecated, and will be removed in a future version.' + + ' Use collection.countDocuments or collection.estimatedDocumentCount instead'); + +/** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + */ +Collection.prototype.estimatedDocumentCount = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, count, [this, null, options, callback]); +}; + +/** + * Gets the number of documents matching the filter. + * + * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param {object} [query] the query for the count + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specifies a collation. + * @param {string|object} [options.hint] The index to use. + * @param {number} [options.limit] The maximum number of document to count. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {number} [options.skip] The number of documents to skip before counting. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + +Collection.prototype.countDocuments = function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, countDocuments, [this, query, options, callback]); +}; + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + const queryOption = args.length ? args.shift() || {} : {}; + const optionsOption = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, distinct, [ + this, + key, + queryOption, + optionsOption, + callback + ]); +}; + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, indexes, [this, options, callback]); +}; + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, stats, [this, options, callback]); +}; + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + + return executeOperation(this.s.topology, findOneAndDelete, [this, filter, options, callback]); +}; + +/** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} replacement The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (replacement == null || typeof replacement !== 'object') + throw toError('replacement parameter must be an object'); + + return executeOperation(this.s.topology, findOneAndReplace, [ + this, + filter, + replacement, + options, + callback + ]); +}; + +/** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (update == null || typeof update !== 'object') + throw toError('update parameter must be an object'); + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + return executeOperation(this.s.topology, findOneAndUpdate, [ + this, + filter, + update, + options, + callback + ]); +}; + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = deprecate(function(query, sort, doc, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + options = Object.assign({}, options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation(this.s.topology, findAndModify, [ + this, + query, + sort, + doc, + options, + callback + ]); +}, 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.'); + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, findAndRemove, [this, query, sort, options, callback]); +}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + if (Array.isArray(pipeline)) { + // Set up callback if one is provided + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + const args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + const opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = + opts && + (opts.readPreference || + opts.explain || + opts.cursor || + opts.out || + opts.maxTimeMS || + opts.hint || + opts.allowDiskUse) + ? args.pop() + : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // Ignore readConcern option + let ignoreReadConcern = false; + + // Build the command + const command = { aggregate: this.s.name, pipeline: pipeline }; + + // If out was specified + if (typeof options.out === 'string') { + pipeline.push({ $out: options.out }); + // Ignore read concern + ignoreReadConcern = true; + } else if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { + ignoreReadConcern = true; + } + + // Decorate command with writeConcern if out has been specified + if ( + pipeline.length > 0 && + pipeline[pipeline.length - 1]['$out'] && + this.s.topology.capabilities().commandsTakeWriteConcern + ) { + applyWriteConcern(command, { db: this.s.db, collection: this }, options); + } + + // Have we specified collation + try { + decorateWithCollation(command, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + // If we have bypassDocumentValidation set + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if (!ignoreReadConcern) { + decorateWithReadConcern(command, this, options); + } + + // If we have allowDiskUse defined + if (options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; + + // If we are giving a hint + if (options.hint) command.hint = options.hint; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); + + // If explain has been specified add it + if (options.explain) { + if (command.readConcern || command.writeConcern) { + throw toError('"explain" cannot be used on an aggregate call with readConcern/writeConcern'); + } + command.explain = options.explain; + } + + if (typeof options.comment === 'string') command.comment = options.comment; + + // Validate that cursor options is valid + if (options.cursor != null && typeof options.cursor !== 'object') { + throw toError('cursor options must be an object'); + } + + options.cursor = options.cursor || {}; + if (options.batchSize) options.cursor.batchSize = options.batchSize; + command.cursor = options.cursor; + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if (typeof callback !== 'function') { + if (!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // Allow disk usage command + if (typeof options.allowDiskUse === 'boolean') command.allowDiskUse = options.allowDiskUse; + if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, command, options)); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * @method + * @since 3.0.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Collection.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (options.session) { + options.session = undefined; + } + + return executeOperation(this.s.topology, parallelCollectionScan, [this, options, callback], { + skipSessions: true + }); +}; + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance] Include results up to maxDistance from the point. + * @param {object} [options.search] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, geoHaystackSearch, [this, x, y, options, callback]); +}; + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. + */ +Collection.prototype.group = deprecate(function( + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback +) { + const args = Array.prototype.slice.call(arguments, 3); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if (!(typeof finalize === 'function')) { + command = finalize; + finalize = null; + } + + if ( + !Array.isArray(keys) && + keys instanceof Object && + typeof keys !== 'function' && + !(keys._bsontype === 'Code') + ) { + keys = Object.keys(keys); + } + + if (typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if (typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + return executeOperation(this.s.topology, group, [ + this, + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback + ]); +}, +'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query] Query filter object. + * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize] Finalize function. + * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + if ('function' === typeof options) (callback = options), (options = {}); + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if (null == options.out) { + throw new Error( + 'the out option parameter must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + return executeOperation(this.s.topology, mapReduce, [this, map, reduce, options, callback]); +}; + +/** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +}; + +/** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session's options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Collection.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +module.exports = Collection; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..50afb6f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,334 @@ +'use strict'; + +const inherits = require('util').inherits; +const ReadPreference = require('mongodb-core').ReadPreference; +const MongoError = require('mongodb-core').MongoError; +const Readable = require('stream').Readable; +const CoreCursor = require('./cursor'); + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary || Promise; + + // Set up + Readable.call(this, { objectMode: true }); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS, + // State + state: state, + // Stream options + streamOptions: streamOptions, + // BSON + bson: bson, + // Namespace + ns: ns, + // Command + cmd: cmd, + // Options + options: options, + // Topology + topology: topology, + // Topology Options + topologyOptions: topologyOptions, + // Promise library + promiseLibrary: promiseLibrary, + // Optional ClientSession + session: options.session + }; +}; + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = [ + '_next', + 'next', + 'hasNext', + 'each', + 'forEach', + 'toArray', + 'rewind', + 'bufferedCount', + 'readBufferedDocuments', + 'close', + 'isClosed', + 'kill', + 'setCursorBatchSize', + '_find', + '_getmore', + '_killcursor', + 'isDead', + 'explain', + 'isNotified', + 'isKilled', + '_endSession', + '_initImplicitSession' +]; + +// Only inherit the types we need +for (var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +CommandCursor.prototype.setReadPreference = function(readPreference) { + if (this.s.state === CommandCursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (this.s.state !== CommandCursor.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.s.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.s.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; +}; + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if (this.s.state === CommandCursor.CLOSED || this.isDead()) + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + if (typeof value !== 'number') + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +}; + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if (this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +}; + +/** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ +CommandCursor.prototype.getLogger = function() { + return this.logger; +}; + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function CommandCursor.prototype.hasNext + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/constants.js b/node_modules/mongoose/node_modules/mongodb/lib/constants.js new file mode 100644 index 0000000..d6cc68a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/constants.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', + SYSTEM_INDEX_COLLECTION: 'system.indexes', + SYSTEM_PROFILE_COLLECTION: 'system.profile', + SYSTEM_USER_COLLECTION: 'system.users', + SYSTEM_COMMAND_COLLECTION: '$cmd', + SYSTEM_JS_COLLECTION: 'system.js' +}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..4a0b815 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1152 @@ +'use strict'; + +const Transform = require('stream').Transform; +const PassThrough = require('stream').PassThrough; +const inherits = require('util').inherits; +const deprecate = require('util').deprecate; +const handleCallback = require('./utils').handleCallback; +const ReadPreference = require('mongodb-core').ReadPreference; +const MongoError = require('mongodb-core').MongoError; +const Readable = require('stream').Readable; +const CoreCursor = require('mongodb-core').Cursor; +const Map = require('mongodb-core').BSON.Map; +const executeOperation = require('./utils').executeOperation; + +const count = require('./operations/cursor_ops').count; +const each = require('./operations/cursor_ops').each; +const hasNext = require('./operations/cursor_ops').hasNext; +const next = require('./operations/cursor_ops').next; +const toArray = require('./operations/cursor_ops').toArray; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +const fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor max + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(true) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +function Cursor(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + const state = Cursor.INIT; + const streamOptions = {}; + + // Tailable cursor options + const numberOfRetries = options.numberOfRetries || 5; + const tailableRetryInterval = options.tailableRetryInterval || 500; + const currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Set up + Readable.call(this, { objectMode: true }); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries, + tailableRetryInterval: tailableRetryInterval, + currentNumberOfRetries: currentNumberOfRetries, + // State + state: state, + // Stream options + streamOptions: streamOptions, + // BSON + bson: bson, + // Namespace + ns: ns, + // Command + cmd: cmd, + // Options + options: options, + // Topology + topology: topology, + // Topology options + topologyOptions: topologyOptions, + // Promise library + promiseLibrary: promiseLibrary, + // Current doc + currentDoc: null, + // explicitlyIgnoreSession + explicitlyIgnoreSession: options.explicitlyIgnoreSession + }; + + // Optional ClientSession + if (!options.explicitlyIgnoreSession && options.session) { + this.s.session = options.session; + } + + // Translate correctly + if (this.s.options.noCursorTimeout === true) { + this.addCursorFlag('noCursorTimeout', true); + } + + // Set the sort value + this.sortValue = this.s.cmd.sort; + + // Get the batchSize + const batchSize = + cmd.cursor && cmd.cursor.batchSize + ? cmd.cursor && cmd.cursor.batchSize + : options.cursor && options.cursor.batchSize + ? options.cursor.batchSize + : 1000; + + // Set the batchSize + this.setCursorBatchSize(batchSize); +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +Cursor.prototype._next = function() { + if (this._initImplicitSession) { + this._initImplicitSession(); + } + return CoreCursor.prototype.next.apply(this, arguments); +}; + +for (let name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +Cursor.prototype._initImplicitSession = function() { + if (!this.s.explicitlyIgnoreSession && !this.s.session && this.s.topology.hasSessionSupport()) { + this.s.session = this.s.topology.startSession({ owner: this }); + this.cursorState.session = this.s.session; + } +}; + +Cursor.prototype._endSession = function() { + const didCloseCursor = CoreCursor.prototype._endSession.apply(this, arguments); + if (didCloseCursor) { + this.s.session = undefined; + } +}; + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + return executeOperation(this.s.topology, hasNext, [this, callback], { + skipSessions: true + }); +}; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + return executeOperation(this.s.topology, next, [this, callback], { + skipSessions: true + }); +}; + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.query = filter; + return this; +}; + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ +Cursor.prototype.maxScan = deprecate(function(maxScan) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.maxScan = maxScan; + return this; +}, 'Cursor.maxScan is deprecated, and will be removed in a later version'); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.hint = hint; + return this; +}; + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + this.s.cmd.min = min; + return this; +}; + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.max = max; + return this; +}; + +/** + * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * @method + * @param {bool} returnKey the returnKey value. + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.returnKey = value; + return this; +}; + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.showDiskLoc = value; + return this; +}; + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ +Cursor.prototype.snapshot = deprecate(function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.snapshot = value; + return this; +}, 'Cursor Snapshot is deprecated, and will be removed in a later version'); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (fields.indexOf(field) === -1) { + throw MongoError.create({ + message: `option ${field} is not a supported option ${fields}`, + driver: true + }); + } + + this.s[field] = value; + if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; + return this; +}; + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (flags.indexOf(flag) === -1) { + throw MongoError.create({ + message: `flag ${flag} is not a supported flag ${flags}`, + driver: true + }); + } + + if (typeof value !== 'boolean') { + throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); + } + + this.s.cmd[flag] = value; + return this; +}; + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {string|boolean|number} value The modifier value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (name[0] !== '$') { + throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); + } + + // Strip of the $ + const field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if (field === 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +}; + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.comment = value; + return this; +}; + +/** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxAwaitTimeMS = function(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.maxAwaitTimeMS = value; + return this; +}; + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.maxTimeMS = value; + return this; +}; + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.fields = value; + return this; +}; + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + let order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if (Array.isArray(order) && Array.isArray(order[0])) { + order = new Map( + order.map(x => { + const value = [x[0], null]; + if (x[1] === 'asc') { + value[1] = 1; + } else if (x[1] === 'desc') { + value[1] = -1; + } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { + value[1] = x[1]; + } else { + throw new MongoError( + "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return value; + }) + ); + } + + if (direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +}; + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support batchSize", driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +}; + +/** + * Set the collation options for the cursor. + * @method + * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.collation = function(value) { + this.s.cmd.collation = value; + return this; +}; + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); + } + + if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'limit requires an integer', driver: true }); + } + + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +}; + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); + } + + if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'skip requires an integer', driver: true }); + } + + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +}; + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = deprecate(function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + each(this, callback); +}, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {Promise} if no callback supplied + */ +Cursor.prototype.forEach = function(iterator, callback) { + // Rewind cursor state + this.rewind(); + + // Set current cursor to INIT + this.s.state = Cursor.INIT; + + if (typeof callback === 'function') { + each(this, (err, doc) => { + if (err) { + callback(err); + return false; + } + if (doc != null) { + iterator(doc); + return true; + } + if (doc == null && callback) { + const internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); + } else { + return new this.s.promiseLibrary((fulfill, reject) => { + each(this, (err, doc) => { + if (err) { + reject(err); + return false; + } else if (doc == null) { + fulfill(null); + return false; + } else { + iterator(doc); + return true; + } + }); + }); + } +}; + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(readPreference) { + if (this.s.state !== Cursor.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.s.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.s.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; +}; + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + if (this.s.options.tailable) { + throw MongoError.create({ + message: 'Tailable cursor cannot be converted to array', + driver: true + }); + } + + return executeOperation(this.s.topology, toArray, [this, callback], { + skipSessions: true + }); +}; + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options] Optional settings. + * @param {number} [options.skip] The number of documents to skip. + * @param {number} [options.limit] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + if (this.s.cmd.query == null) + throw MongoError.create({ message: 'count can only be used with find command', driver: true }); + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + if (typeof applySkipLimit === 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if (this.s.session) { + opts = Object.assign({}, opts, { session: this.s.session }); + } + + return executeOperation(this.s.topology, count, [this, applySkipLimit, opts, callback], { + skipSessions: !!this.s.session + }); +}; + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { skipKillCursors: false }, options); + + this.s.state = Cursor.CLOSED; + if (!options.skipKillCursors) { + // Kill the cursor + this.kill(); + } + + const completeClose = () => { + // Emit the close event for the cursor + this.emit('close'); + + // Callback if provided + if (typeof callback === 'function') { + return handleCallback(callback, null, this); + } + + // Return a Promise + return new this.s.promiseLibrary(resolve => { + resolve(); + }); + }; + + if (this.s.session) { + if (typeof callback === 'function') { + return this._endSession(() => completeClose()); + } + + return new this.s.promiseLibrary(resolve => { + this._endSession(() => completeClose().then(resolve)); + }); + } + + return completeClose(); +}; + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {Cursor} + */ +Cursor.prototype.map = function(transform) { + if (this.cursorState.transforms && this.cursorState.transforms.doc) { + const oldTransform = this.cursorState.transforms.doc; + this.cursorState.transforms.doc = doc => { + return transform(oldTransform(doc)); + }; + } else { + this.cursorState.transforms = { doc: transform }; + } + return this; +}; + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +}; + +Cursor.prototype.destroy = function(err) { + if (err) this.emit('error', err); + this.pause(); + this.close(); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + * TODO: replace this method with transformStream in next major release + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +}; + +/** + * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, + * returns a stream of unmodified docs. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {stream} + */ +Cursor.prototype.transformStream = function(options) { + const streamOptions = options || {}; + if (typeof streamOptions.transform === 'function') { + const stream = new Transform({ + objectMode: true, + transform: function(chunk, encoding, callback) { + this.push(streamOptions.transform(chunk)); + callback(); + } + }); + + return this.pipe(stream); + } + return this.pipe(new PassThrough({ objectMode: true })); +}; + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + this.s.cmd.explain = true; + + // Do we have a readConcern + if (this.s.cmd.readConcern) { + delete this.s.cmd['readConcern']; + } + + return executeOperation(this.s.topology, this._next.bind(this), [callback], { + skipSessions: true + }); +}; + +Cursor.prototype._read = function() { + if (this.s.state === Cursor.CLOSED || this.isDead()) { + return this.push(null); + } + + // Get the next item + this.next((err, result) => { + if (err) { + if (this.listeners('error') && this.listeners('error').length > 0) { + this.emit('error', err); + } + if (!this.isDead()) this.close(); + + // Emit end event + this.emit('end'); + return this.emit('finish'); + } + + // If we provided a transformation method + if (typeof this.s.streamOptions.transform === 'function' && result != null) { + return this.push(this.s.streamOptions.transform(result)); + } + + // If we provided a map function + if ( + this.cursorState.transforms && + typeof this.cursorState.transforms.doc === 'function' && + result != null + ) { + return this.push(this.cursorState.transforms.doc(result)); + } + + // Return the result + this.push(result); + + if (result === null && this.isDead()) { + this.once('end', () => { + this.close(); + this.emit('finish'); + }); + } + }); +}; + +/** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ +Cursor.prototype.getLogger = function() { + return this.logger; +}; + +Object.defineProperty(Cursor.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + return this.s.options.readPreference; + } +}); + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + const ns = this.s.ns || ''; + const firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/db.js b/node_modules/mongoose/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..b3257f3 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/db.js @@ -0,0 +1,985 @@ +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const inherits = require('util').inherits; +const getSingleProperty = require('./utils').getSingleProperty; +const CommandCursor = require('./command_cursor'); +const handleCallback = require('./utils').handleCallback; +const filterOptions = require('./utils').filterOptions; +const toError = require('./utils').toError; +const ReadPreference = require('mongodb-core').ReadPreference; +const MongoError = require('mongodb-core').MongoError; +const ObjectID = require('mongodb-core').ObjectID; +const Logger = require('mongodb-core').Logger; +const Collection = require('./collection'); +const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; +const executeOperation = require('./utils').executeOperation; +const applyWriteConcern = require('./utils').applyWriteConcern; +const resolveReadPreference = require('./utils').resolveReadPreference; +const ChangeStream = require('./change_stream'); +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const CONSTANTS = require('./constants'); + +// Operations +const addUser = require('./operations/db_ops').addUser; +const collections = require('./operations/db_ops').collections; +const createCollection = require('./operations/db_ops').createCollection; +const createIndex = require('./operations/db_ops').createIndex; +const createListener = require('./operations/db_ops').createListener; +const dropCollection = require('./operations/db_ops').dropCollection; +const dropDatabase = require('./operations/db_ops').dropDatabase; +const ensureIndex = require('./operations/db_ops').ensureIndex; +const evaluate = require('./operations/db_ops').evaluate; +const executeCommand = require('./operations/db_ops').executeCommand; +const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand; +const indexInformation = require('./operations/db_ops').indexInformation; +const listCollectionsTransforms = require('./operations/db_ops').listCollectionsTransforms; +const profilingInfo = require('./operations/db_ops').profilingInfo; +const profilingLevel = require('./operations/db_ops').profilingLevel; +const removeUser = require('./operations/db_ops').removeUser; +const setProfilingLevel = require('./operations/db_ops').setProfilingLevel; +const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + */ + +// Allowed parameters +const legalOptionNames = [ + 'w', + 'wtimeout', + 'fsync', + 'j', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'bufferMaxEntries', + 'authSource', + 'ignoreUndefined', + 'promoteLongs', + 'promiseLibrary', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'parentDb', + 'noListener', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options] Optional settings. + * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @property {object} topology Access the topology object (single server, replicaset or mongos). + * @fires Db#close + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +function Db(databaseName, topology, options) { + options = options || {}; + if (!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName, + // DbCache + dbCache: {}, + // Children db's + children: [], + // Topology + topology: topology, + // Options + options: options, + // Logger instance + logger: Logger('Db', options), + // Get the bson parser + bson: topology ? topology.bson : null, + // Unpack read preference + readPreference: options.readPreference, + // Set buffermaxEntries + bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, + // Parent db (if chained) + parentDb: options.parentDb || null, + // Set up the primary key factory or fallback to ObjectID + pkFactory: options.pkFactory || ObjectID, + // Get native parser + nativeParser: options.nativeParser || options.native_parser, + // Promise library + promiseLibrary: promiseLibrary, + // No listener + noListener: typeof options.noListener === 'boolean' ? options.noListener : false, + // ReadConcern + readConcern: options.readConcern + }; + + // Ensure we have a valid db name + validateDatabaseName(this.s.databaseName); + + // Add a read Only property + getSingleProperty(this, 'serverConfig', this.s.topology); + getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', this.s.databaseName); + + // This is a child db, do not register any listeners + if (options.parentDb) return; + if (this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(this, 'error', this)); + topology.on('timeout', createListener(this, 'timeout', this)); + topology.on('close', createListener(this, 'close', this)); + topology.on('parseError', createListener(this, 'parseError', this)); + topology.once('open', createListener(this, 'open', this)); + topology.once('fullsetup', createListener(this, 'fullsetup', this)); + topology.once('all', createListener(this, 'all', this)); + topology.on('reconnect', createListener(this, 'reconnect', this)); +} + +inherits(Db, EventEmitter); + +// Topology +Object.defineProperty(Db.prototype, 'topology', { + enumerable: true, + get: function() { + return this.s.topology; + } +}); + +// Options +Object.defineProperty(Db.prototype, 'options', { + enumerable: true, + get: function() { + return this.s.options; + } +}); + +// slaveOk specified +Object.defineProperty(Db.prototype, 'slaveOk', { + enumerable: true, + get: function() { + if ( + this.s.options.readPreference != null && + (this.s.options.readPreference !== 'primary' || + this.s.options.readPreference.mode !== 'primary') + ) { + return true; + } + return false; + } +}); + +// get the write Concern +Object.defineProperty(Db.prototype, 'writeConcern', { + enumerable: true, + get: function() { + const ops = {}; + if (this.s.options.w != null) ops.w = this.s.options.w; + if (this.s.options.j != null) ops.j = this.s.options.j; + if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + return executeOperation(this.s.topology, executeCommand, [this, command, options, callback]); +}; + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + const Admin = require('./admin'); + + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +const collectionKeys = [ + 'pkFactory', + 'readPreference', + 'serializeFunctions', + 'strict', + 'readConcern', + 'ignoreUndefined', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs' +]; + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you + * can use it without a callback in the following way: `const collection = db.collection('mycollection');` + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} [callback] The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options = Object.assign({}, options); + + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if (this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Merge in all needed options and ensure correct writeConcern merging from db level + options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); + + // Execute + if (options == null || !options.strict) { + try { + const collection = new Collection( + this, + this.s.topology, + this.s.databaseName, + name, + this.s.pkFactory, + options + ); + if (callback) callback(null, collection); + return collection; + } catch (err) { + if (err instanceof MongoError && callback) return callback(err); + throw err; + } + } + + // Strict mode + if (typeof callback !== 'function') { + throw toError(`A callback is required in strict mode. While getting collection ${name}`); + } + + // Did the user destroy the topology + if (this.serverConfig && this.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + + // Strict mode + this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length === 0) + return handleCallback( + callback, + toError(`Collection ${name} does not exist. Currently in strict mode.`), + null + ); + + try { + return handleCallback( + callback, + null, + new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err, null); + } + }); +}; + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 + * @param {number} [options.size] The size of the capped collection in bytes. + * @param {number} [options.max] The maximum number of documents in the capped collection. + * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. + * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. + * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. + * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. + * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. + * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. + * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. + * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = deprecateOptions( + { + name: 'Db.createCollection', + deprecatedOptions: ['autoIndexId'], + optionsIndex: 1 + }, + function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + return executeOperation(this.s.topology, createCollection, [this, name, options, callback]); + } +); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Build command object + const commandObject = { dbStats: true }; + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + // If we have a readPreference set + if (options.readPreference == null && this.s.readPreference) { + options.readPreference = this.s.readPreference; + } + + // Execute the command + return this.command(commandObject, options, callback); +}; + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} [filter={}] Query to filter collections by + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info + * @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = Object.assign({}, options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // Ensure valid readPreference + options.readPreference = resolveReadPreference(options, { + db: this, + default: ReadPreference.primary + }); + + // Cursor options + let cursor = options.batchSize ? { batchSize: options.batchSize } : {}; + + // We have a list collections command + if (this.serverConfig.capabilities().hasListCollectionsCommand) { + const nameOnly = typeof options.nameOnly === 'boolean' ? options.nameOnly : false; + // Build the command + const command = { listCollections: true, filter, cursor, nameOnly }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Create the cursor + cursor = this.s.topology.cursor(`${this.s.databaseName}.$cmd`, command, options); + // Do we have a readPreference, apply it + if (options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + // Return the cursor + return cursor; + } + + // We cannot use the listCollectionsCommand + if (!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if ( + typeof filter.name === 'string' && + !new RegExp('^' + this.databaseName + '\\.').test(filter.name) + ) { + filter = Object.assign({}, filter); + filter.name = `${this.s.databaseName}.${filter.name}`; + } + } + + // No filter, filter by current database + if (filter == null) { + filter.name = `/${this.s.databaseName}/`; + } + + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } else { + filter = { name: /^((?!\$).)*$/ }; + } + + // Return options + const _options = { transforms: listCollectionsTransforms(this.s.databaseName) }; + // Get the cursor + cursor = this.collection(CONSTANTS.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); + // Do we have a readPreference, apply it + if (options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if (options.batchSize) cursor = cursor.batchSize(options.batchSize); + // We have a fallback mode using legacy systems collections + return cursor; +}; + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = deprecate(function(code, parameters, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, evaluate, [this, code, parameters, options, callback]); +}, 'Db.eval is deprecated as of MongoDB version 3.2'); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Add return new collection + options.new_collection = true; + + const collection = this.collection(fromCollection); + return executeOperation(this.s.topology, collection.rename.bind(collection), [ + toCollection, + options, + callback + ]); +}; + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Command to execute + const cmd = { drop: name }; + + // Decorate with write concern + applyWriteConcern(cmd, { db: this }, options); + + // options + const opts = Object.assign({}, this.s.options, { readPreference: ReadPreference.PRIMARY }); + if (options.session) opts.session = options.session; + + return executeOperation(this.s.topology, dropCollection, [this, cmd, opts, callback]); +}; + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Drop database command + const cmd = { dropDatabase: 1 }; + + // Decorate with write concern + applyWriteConcern(cmd, { db: this }, options); + + // Ensure primary only + const finalOptions = Object.assign({}, this.s.options, { + readPreference: ReadPreference.PRIMARY + }); + + if (options.session) { + finalOptions.session = options.session; + } + + return executeOperation(this.s.topology, dropDatabase, [this, cmd, finalOptions, callback]); +}; + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, collections, [this, options, callback]); +}; + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.readPreference = resolveReadPreference(options); + + return executeOperation(this.s.topology, executeDbAdminCommand, [ + this, + selector, + options, + callback + ]); +}; + +/** + * Creates an index on the db and collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + return executeOperation(this.s.topology, createIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, ensureIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); + +Db.prototype.addChild = function(db) { + if (this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, addUser, [this, username, password, options, callback]); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, removeUser, [this, username, options, callback]); +}; + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.setProfilingLevel = function(level, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, setProfilingLevel, [this, level, options, callback]); +}; + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Query the system.profile collection directly. + */ +Db.prototype.profilingInfo = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, profilingInfo, [this, options, callback]); +}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.profilingLevel = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, profilingLevel, [this, options, callback]); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, indexInformation, [this, name, options, callback]); +}; + +/** + * Unref all sockets + * @method + */ +Db.prototype.unref = function() { + this.s.topology.unref(); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Db.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Db.prototype.getLogger = function() { + return this.s.logger; +}; + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + +module.exports = Db; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/error.js b/node_modules/mongoose/node_modules/mongodb/lib/error.js new file mode 100644 index 0000000..03b555a --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/error.js @@ -0,0 +1,43 @@ +'use strict'; + +const MongoNetworkError = require('mongodb-core').MongoNetworkError; +const mongoErrorContextSymbol = require('mongodb-core').mongoErrorContextSymbol; + +const GET_MORE_NON_RESUMABLE_CODES = new Set([ + 136, // CappedPositionLost + 237, // CursorKilled + 11601 // Interrupted +]); + +// From spec@https://github.com/mongodb/specifications/blob/35e466ddf25059cb30e4113de71cdebd3754657f/source/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the following error codes +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// - a server error response with an error message containing the substring "not master" or "node is recovering" +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. + +function isGetMoreError(error) { + if (error[mongoErrorContextSymbol]) { + return error[mongoErrorContextSymbol].isGetMore; + } +} + +function isResumableError(error) { + if (!isGetMoreError(error)) { + return false; + } + + return !!( + error instanceof MongoNetworkError || + !GET_MORE_NON_RESUMABLE_CODES.has(error.code) || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 0000000..9012602 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,415 @@ +'use strict'; + +var stream = require('stream'), + util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options] Optional settings. + * @param {Number} [options.sort] Optional sort for the file find query + * @param {Number} [options.skip] Optional skip for the file find query + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Emitted when a chunk of data is available to be consumed. + * + * @event GridFSBucketReadStream#data + * @type {object} + */ + +/** + * Fired when the stream is exhausted (no more data events). + * + * @event GridFSBucketReadStream#end + * @type {object} + */ + +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * + * @event GridFSBucketReadStream#close + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + if (this.destroyed) { + return; + } + + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @method + * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. + * @fires GridFSBucketWriteStream#close + * @fires GridFSBucketWriteStream#end + */ + +GridFSBucketReadStream.prototype.abort = function(callback) { + var _this = this; + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(function(error) { + _this.emit('close'); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + _this.emit('close'); + } + callback && callback(); + } +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + if (_this.destroyed) { + return; + } + + _this.s.cursor.next(function(error, doc) { + if (_this.destroyed) { + return; + } + if (error) { + return __handleError(_this, error); + } + if (!doc) { + _this.push(null); + return _this.s.cursor.close(function(error) { + if (error) { + return __handleError(_this, error); + } + _this.emit('close'); + }); + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); + + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.n < expectedN) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.length !== expectedLength) { + if (bytesRemaining <= 0) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + + errmsg = + 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += buf.length; + + if (buf.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.bytesToTrim; + } + + // If the remaining amount of data left is < chunkSize read the right amount of data + if (_this.s.options.end && _this.s.options.end - _this.s.bytesToSkip < buf.length) { + sliceEnd = _this.s.options.end - _this.s.bytesToSkip; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +} + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + var err = new Error(errmsg); + err.code = 'ENOENT'; + return __handleError(self, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + if (self.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + self.emit('close'); + return; + } + + self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); + + var filter = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (self.s.options && self.s.options.start != null) { + var skip = Math.floor(self.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); + + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +} + +/** + * @ignore + */ + +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'greater than stream end (' + + options.end + + ')' + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error( + 'Stream end (' + + options.end + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); + } + + var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 0000000..9d64a84 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,358 @@ +'use strict'; + +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); +var executeOperation = require('../utils').executeOperation; + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || Promise + }; +} + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string|number|object} id A custom id used to identify the file + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + + options.id = id; + + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options] Optional settings. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + options = { + start: options && options.start, + end: options && options.end + }; + + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.delete = function(id, callback) { + return executeOperation(this.s.db.s.topology, _delete, [this, id, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options] Optional settings for cursor + * @param {number} [options.batchSize] Optional batch size for cursor + * @param {number} [options.limit] Optional limit for cursor + * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip] Optional skip for cursor + * @param {object} [options.sort] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + return executeOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + return executeOperation(this.s.db.s.topology, _drop, [this, callback], { + skipSessions: true + }); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +GridFSBucket.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 0000000..adbba41 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,538 @@ +'use strict'; + +var core = require('mongodb-core'); +var crypto = require('crypto'); +var stream = require('stream'); +var util = require('util'); +var Buffer = require('safe-buffer').Buffer; + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {string|number|object} [options.id] Custom file id for the GridFS file. + * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes + * @param {number} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {number} [options.j] The journal write concern + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + options = options || {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.md5 = !options.disableMD5 && crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false, + promiseLibrary: this.bucket.s.promiseLibrary + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * `end()` was called and the write stream successfully wrote the file + * metadata and all the chunks to MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @method + * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred + * @return {Promise} if no callback specified + */ + +GridFSBucketWriteStream.prototype.abort = function(callback) { + if (this.state.streamEnd) { + var error = new Error('Cannot abort a stream that has already completed'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + if (this.state.aborted) { + error = new Error('Cannot call abort() on a stream twice'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, function(error) { + if (typeof callback === 'function') callback(error); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + if (typeof chunk === 'function') { + (callback = chunk), (chunk = null), (encoding = null); + } else if (typeof encoding === 'function') { + (callback = encoding), (encoding = null); + } + + if (checkAborted(this, callback)) { + return; + } + this.state.streamEnd = true; + + if (callback) { + this.once('finish', function(result) { + callback(null, result); + }); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.done) return true; + if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { + // Set done so we dont' trigger duplicate createFilesDoc + _this.done = true; + // Create a new files doc + var filesDoc = createFilesDoc( + _this.id, + _this.length, + _this.chunkSizeBytes, + _this.md5 && _this.md5.digest('hex'), + _this.filename, + _this.options.contentType, + _this.options.aliases, + _this.options.metadata + ); + + if (checkAborted(_this, callback)) { + return false; + } + + _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + filename: filename + }; + + if (md5) { + ret.md5 = md5; + } + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + if (checkAborted(_this, callback)) { + return false; + } + + var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + if (_this.md5) { + _this.md5.update(_this.bufToStore); + } + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = _this.options.writeConcern.w; + obj.wtimeout = _this.options.writeConcern.wtimeout; + obj.j = _this.options.writeConcern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = Buffer.alloc(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + if (_this.md5) { + _this.md5.update(remnant); + } + var doc = createChunkDoc(_this.id, _this.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} + +/** + * @ignore + */ + +function checkAborted(_this, callback) { + if (_this.state.aborted) { + if (typeof callback === 'function') { + callback(new Error('this stream has been aborted')); + } + return true; + } + return false; +} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..c29bba0 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,236 @@ +'use strict'; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').BSON.ObjectID; + +var Buffer = require('safe-buffer').Buffer; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || { w: 1 }; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if (typeof mongoObjectFinal.data === 'string') { + var buffer = Buffer.alloc(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if (Array.isArray(mongoObjectFinal.data)) { + buffer = Buffer.alloc(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { + throw Error('Illegal chunk format'); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if (callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length === 0 ? this.length() : length; + + if (this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if (this.length() - this.internalPosition >= length) { + var data = null; + if (this.data.buffer != null) { + //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { + //Native BSON + data = Buffer.alloc(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition === this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if (typeof options === 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if (err) return callback(err); + + // Merge the options + var writeOptions = { upsert: true }; + for (var name in options) writeOptions[name] = options[name]; + for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + if (self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = { forceServerObjectId: true }; + for (var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + // }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *

+ *        {
+ *          '_id' : , // {number} id for this chunk
+ *          'files_id' : , // {number} foreign key to the file collection
+ *          'n' : , // {number} chunk number
+ *          'data' : , // {bson#Binary} the chunk data itself
+ *        }
+ *        
+ * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + files_id: this.file.fileId, + n: this.chunkNumber, + data: this.data + }; + // If we are saving using a specific ObjectId + if (this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, 'position', { + enumerable: true, + get: function() { + return this.internalPosition; + }, + set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..4b5eb5e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1907 @@ +'use strict'; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * const GridStore = require('mongodb').GridStore; + * const ObjectID = require('mongodb').ObjectID; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * const gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * client.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +const Chunk = require('./chunk'); +const ObjectID = require('mongodb-core').BSON.ObjectID; +const ReadPreference = require('mongodb-core').ReadPreference; +const Buffer = require('safe-buffer').Buffer; +const fs = require('fs'); +const f = require('util').format; +const util = require('util'); +const MongoError = require('mongodb-core').MongoError; +const inherits = util.inherits; +const Duplex = require('stream').Duplex; +const shallowClone = require('../utils').shallowClone; +const executeOperation = require('../utils').executeOperation; +const deprecate = require('util').deprecate; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +const deprecationFn = deprecate(() => {}, +'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + deprecationFn(); + if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + this.db = db; + + // Handle options + if (typeof options === 'undefined') options = {}; + // Handle mode + if (typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if (typeof mode === 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if (id && id._bsontype === 'ObjectID') { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if (typeof filename === 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? 'r' : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = + this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = + this.options.readPreference || db.options.readPreference || ReadPreference.primary; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = + this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary || Promise; + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, 'chunkSize', { + enumerable: true, + get: function() { + return this.internalChunkSize; + }, + set: function(value) { + if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, 'md5', { + enumerable: true, + get: function() { + return this.internalMd5; + } + }); + + Object.defineProperty(this, 'chunkNumber', { + enumerable: true, + get: function() { + return this.currentChunk && this.currentChunk.chunkNumber + ? this.currentChunk.chunkNumber + : null; + } + }); +}; + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { + throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); + } + + return executeOperation(this.db.s.topology, open, [this, options, callback], { + skipSessions: true + }); +}; + +var open = function(self, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if (self.mode === 'w' || self.mode === 'w+') { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function() { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { + // Open the connection + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +}; + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position === this.length ? true : false; +}; + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, getc, [this, options, callback], { + skipSessions: true + }); +}; + +var getc = function(self, options, callback) { + if (self.eof()) { + callback(null, null); + } else if (self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +}; + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + var finalString = string.match(/\n$/) == null ? string + '\n' : string; + return executeOperation( + this.db.s.topology, + this.write.bind(this), + [finalString, options, callback], + { skipSessions: true } + ); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +}; + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.db.s.topology, + _writeNormal, + [this, data, close, options, callback], + { skipSessions: true } + ); +}; + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if (!this.writable) return; + this.readable = false; + if (this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +}; + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function(file, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, writeFile, [this, file, options, callback], { + skipSessions: true + }); +}; + +var writeFile = function(self, file, options, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function(err, fd) { + if (err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function(err, self) { + if (err) return callback(err, self); + + fs.fstat(file, function(err, stats) { + if (err) return callback(err, self); + + var offset = 0; + var index = 0; + + // Write a chunk + var writeChunk = function() { + // Allocate the buffer + var _buffer = Buffer.alloc(self.chunkSize); + // Read the file + fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { + if (err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, { n: index++ }, self.writeConcern); + chunk.write(data.slice(0, bytesRead), function(err, chunk) { + if (err) return callback(err, self); + + chunk.save({}, function(err) { + if (err) return callback(err, self); + + self.position = self.position + bytesRead; + + // Point to current chunk + self.currentChunk = chunk; + + if (offset >= stats.size) { + fs.close(file, function(err) { + if (err) return callback(err); + + self.close(function(err) { + if (err) return callback(err, self); + return callback(null, self); + }); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + }; + + // Process the first write + process.nextTick(writeChunk); + }); + }); +}; + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, close, [this, options, callback], { + skipSessions: true + }); +}; + +var close = function(self, options, callback) { + if (self.mode[0] === 'w') { + // Set up options + options = Object.assign({}, self.writeConcern, options); + + if (self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err) { + if (err && typeof callback === 'function') return callback(err); + + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + // Build the mongo object + if (self.uploadDate != null) { + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + }); + } + } else if (self.mode[0] === 'r') { + if (typeof callback === 'function') callback(null, null); + } else { + if (typeof callback === 'function') + callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); + } +}; + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); + return this.db.collection(this.root + '.chunks'); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, unlink, [this, options, callback], { + skipSessions: true + }); +}; + +var unlink = function(self, options, callback) { + deleteChunks(self, function(err) { + if (err !== null) { + err.message = 'at deleteChunks: ' + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if (err !== null) { + err.message = 'at collection: ' + err.message; + return callback(err); + } + + collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +}; + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); + return this.db.collection(this.root + '.files'); +}; + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : '\n'; + separator = separator || '\n'; + options = args.length ? args.shift() : {}; + + return executeOperation(this.db.s.topology, readlines, [this, separator, options, callback], { + skipSessions: true + }); +}; + +var readlines = function(self, separator, options, callback) { + self.read(function(err, data) { + if (err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for (var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +}; + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, rewind, [this, options, callback], { + skipSessions: true + }); +}; + +var rewind = function(self, options, callback) { + if (self.currentChunk.chunkNumber !== 0) { + if (self.mode[0] === 'w') { + deleteChunks(self, function(err) { + if (err) return callback(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if (err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +}; + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeOperation(this.db.s.topology, read, [this, length, buffer, options, callback], { + skipSessions: true + }); +}; + +var read = function(self, length, buffer, options, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if (finalLength === 0 && finalBuffer.length === 0) + return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if (err) return callback(err); + + if (chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if (finalBuffer._index > 0) { + callback(null, finalBuffer); + } else { + callback( + MongoError.create({ + message: 'no chunks found for file, possibly corrupt', + driver: true + }), + null + ); + } + } + }); +}; + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if (typeof callback === 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve) { + resolve(self.position); + }); +}; + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + seekLocation = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeOperation( + this.db.s.topology, + seek, + [this, position, seekLocation, options, callback], + { skipSessions: true } + ); +}; + +var seek = function(self, position, seekLocation, options, callback) { + // Seek only supports read mode + if (self.mode !== 'r') { + return callback( + MongoError.create({ message: 'seek is only supported for mode r', driver: true }) + ); + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if (seekLocationFinal === GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if (seekLocationFinal === GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition / self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if (err) return callback(err, null); + if (chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = self.position % self.chunkSize; + callback(err, self); + }); + }; + + seekChunk(); +}; + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = + self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if (query != null) { + collection.findOne(query, options, function(err, doc) { + if (err) { + return error(err); + } + + // Check if the collection for the files exists otherwise prepare the new one + if (doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = + self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode !== 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; + return error( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename + ), + driver: true + }), + self + ); + } + + // Process the mode of the object + if (self.mode === 'r') { + nthChunk(self, 0, options, function(err, chunk) { + if (err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w' && doc) { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null + ? self.internalChunkSize + : self.options['chunk_size']; + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w') { + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + // No file exists set up write mode + if (self.mode === 'w') { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error(err) { + if (error.err) return; + callback((error.err = err)); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if (typeof close === 'function') { + callback = close; + close = null; + } + var finalClose = typeof close === 'boolean' ? close : false; + + if (self.mode !== 'w') { + callback( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename + ), + driver: true + }), + null + ); + } else { + if (self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while (leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + // If we have left over data write it + if (leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for (var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err) { + if (err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if (numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + _id: self.fileId, + filename: self.filename, + contentType: self.contentType, + length: self.position ? self.position : 0, + chunkSize: self.chunkSize, + uploadDate: self.uploadDate, + aliases: self.aliases, + metadata: self.metadata + }; + + var md5Command = { filemd5: self.fileId, root: self.root }; + self.db.command(md5Command, function(err, results) { + if (err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self + .chunkCollection() + .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { + if (err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if (self.fileId != null) { + self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { + if (err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** + * The collection to be used for holding the files and chunks collection. + * + * @classconstant DEFAULT_ROOT_COLLECTION + */ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** + * Default file mime type + * + * @classconstant DEFAULT_CONTENT_TYPE + */ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** + * Seek mode where the given length is absolute. + * + * @classconstant IO_SEEK_SET + */ +GridStore.IO_SEEK_SET = 0; + +/** + * Seek mode where the given length is an offset to the current read/write head. + * + * @classconstant IO_SEEK_CUR + */ +GridStore.IO_SEEK_CUR = 1; + +/** + * Seek mode where the given length is an offset to the end of the file. + * + * @classconstant IO_SEEK_END + */ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeOperation( + db.s.topology, + exists, + [db, fileIdObject, rootCollection, options, callback], + { skipSessions: true } + ); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + // Build query + var query = + typeof fileIdObject === 'string' || + Object.prototype.toString.call(fileIdObject) === '[object RegExp]' + ? { filename: fileIdObject } + : { _id: fileIdObject }; // Attempt to locate file + + // We have a specific query + if ( + fileIdObject != null && + typeof fileIdObject === 'object' && + Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' + ) { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, { readPreference: readPreference }, function(err, item) { + if (err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +}; + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeOperation(db.s.topology, list, [db, rootCollection, options, callback], { + skipSessions: true + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if (rootCollection != null && typeof rootCollection === 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.primary; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + collection.find({}, { readPreference: readPreference }, function(err, cursor) { + if (err) return callback(err); + + cursor.each(function(err, item) { + if (item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +}; + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeOperation( + db.s.topology, + readStatic, + [db, name, length, offset, options, callback], + { skipSessions: true } + ); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + // Make sure we are not reading out of bounds + if (offset && offset >= gridStore.length) + return callback('offset larger than size of file', null); + if (length && length > gridStore.length) + return callback('length is larger than the size of the file', null); + if (offset && length && offset + length > gridStore.length) + return callback('offset and length is larger than the size of the file', null); + + if (offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if (err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +}; + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeOperation( + db.s.topology, + readlinesStatic, + [db, name, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? '\n' : separator; + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +}; + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options] Optional settings. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { + skipSessions: true + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if (names.constructor === Array) { + var tc = 0; + for (var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function() { + if (--tc === 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, 'w', options).open(function(err, gridStore) { + if (err) return callback(err); + deleteChunks(gridStore, function(err) { + if (err) return callback(err); + gridStore.collection(function(err, collection) { + if (err) return callback(err); + collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { + callback(err, self); + }); + }); + }); + }); + } +}; + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, options, callback) { + // If we have a buffer write it using the writeBuffer method + if (Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); + } +}; + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if (options.w != null) finalOptions.w = options.w; + if (options.journal === true) finalOptions.j = options.journal; + if (options.j === true) finalOptions.j = options.j; + if (options.fsync === true) finalOptions.fsync = options.fsync; + if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +}; + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = { w: 1 }; + options = options || {}; + + // Local options verification + if ( + options.w != null || + typeof options.j === 'boolean' || + typeof options.journal === 'boolean' || + typeof options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(options); + } else if (options.safe != null && typeof options.safe === 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if (typeof options.safe === 'boolean') { + finalOptions = { w: options.safe ? 1 : 0 }; + } else if ( + self.options.w != null || + typeof self.options.j === 'boolean' || + typeof self.options.journal === 'boolean' || + typeof self.options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(self.options); + } else if ( + self.safe && + (self.safe.w != null || + typeof self.safe.j === 'boolean' || + typeof self.safe.journal === 'boolean' || + typeof self.safe.fsync === 'boolean') + ) { + finalOptions = _setWriteConcernHash(self.safe); + } else if (typeof self.safe === 'boolean') { + finalOptions = { w: self.safe ? 1 : 0 }; + } + + // Ensure we don't have an invalid combination of write concerns + if ( + finalOptions.w < 1 && + (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) + ) + throw MongoError.create({ + message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', + driver: true + }); + + // Return the options + return finalOptions; +}; + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +}; + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if (!self.gs.isOpen) { + self.gs.open(function(err) { + if (err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +}; + +// Called by stream +GridStoreStream.prototype._read = function() { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if (err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if (self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if (buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if (buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if (self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + }; + + // Set read length + var length = + self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if (!self.gs.isOpen) { + self.gs.open(function(err) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if (err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +}; + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +}; + +GridStoreStream.prototype.write = function(chunk) { + var self = this; + if (self.endCalled) + return self.emit( + 'error', + MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) + ); + // Do we have to open the gridstore + if (!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +}; + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if (chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); + }); + } + + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); +}; + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js b/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..e6e9381 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,472 @@ +'use strict'; + +const ChangeStream = require('./change_stream'); +const Db = require('./db'); +const EventEmitter = require('events').EventEmitter; +const executeOperation = require('./utils').executeOperation; +const handleCallback = require('./utils').handleCallback; +const inherits = require('util').inherits; +const MongoError = require('mongodb-core').MongoError; + +// Operations +const connectOp = require('./operations/mongo_client_ops').connectOp; +const logout = require('./operations/mongo_client_ops').logout; +const validOptions = require('./operations/mongo_client_ops').validOptions; + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * + * @example + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {boolean} [options.useNewUrlParser=false] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {MongoClient} a MongoClient instance + */ +function MongoClient(url, options) { + if (!(this instanceof MongoClient)) return new MongoClient(url, options); + // Set up event emitter + EventEmitter.call(this); + + // The internal state + this.s = { + url: url, + options: options || {}, + promiseLibrary: null, + dbCache: {}, + sessions: [] + }; + + // Get the promiseLibrary + const promiseLibrary = this.s.options.promiseLibrary || Promise; + + // Add the promise to the internal state + this.s.promiseLibrary = promiseLibrary; +} + +/** + * @ignore + */ +inherits(MongoClient, EventEmitter); + +/** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {MongoClient} client The connected client. + */ + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.connect = function(callback) { + // Validate options object + const err = validOptions(this.s.options); + + if (typeof callback === 'string') { + throw new TypeError('`connect` only accepts a callback'); + } + + return executeOperation(this, connectOp, [this, err, callback], { + skipSessions: true + }); +}; + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options] Optional settings. + * @param {string} [options.dbName] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.logout = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Establish the correct database name + const dbName = this.s.options.authSource ? this.s.options.authSource : this.s.options.dbName; + + return executeOperation(this, logout, [this, dbName, callback], { + skipSessions: true + }); +}; + +/** + * Close the db and its underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.close = function(force, callback) { + if (typeof force === 'function') (callback = force), (force = false); + + // Close the topology connection + if (this.topology) { + this.topology.close(force); + } + // Emit close event + this.emit('close', this); + + // Fire close event on any cached db instances + for (const name in this.s.dbCache) { + this.s.dbCache[name].emit('close'); + } + + // Remove listeners after emit + this.removeAllListeners('close'); + + // Callback after next event loop tick + if (typeof callback === 'function') + return process.nextTick(() => { + handleCallback(callback, null); + }); + + // Return dummy promise + return new this.s.promiseLibrary(resolve => { + resolve(); + }); +}; + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +MongoClient.prototype.db = function(dbName, options) { + options = options || {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.s.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this.s.options, options); + + // Do we have the db in the cache already + if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add promiseLibrary + finalOptions.promiseLibrary = this.s.promiseLibrary; + + // If no topology throw an error message + if (!this.topology) { + throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); + } + + // Return the db object + const db = new Db(dbName, this.topology, finalOptions); + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +/** + * Check if MongoClient is connected + * + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {boolean} + */ +MongoClient.prototype.isConnected = function(options) { + options = options || {}; + + if (!this.topology) return false; + return this.topology.isConnected(options); +}; + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : null; + options = options || {}; + + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + return mongoClient.connect(callback); +}; + +/** + * Starts a new session on the server + * + * @param {SessionOptions} [options] optional settings for a driver session + * @return {ClientSession} the newly established session + */ +MongoClient.prototype.startSession = function(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new MongoError('Must connect to a server before calling this method'); + } + + if (!this.topology.hasSessionSupport()) { + throw new MongoError('Current topology does not support sessions'); + } + + return this.topology.startSession(options, this.s.options); +}; + +/** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) + * + * @param {Object} [options] Optional settings to be appled to implicitly created session + * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` + * @return {Promise} + */ +MongoClient.prototype.withSession = function(options, operation) { + if (typeof options === 'function') (operation = options), (options = undefined); + const session = this.startSession(options); + + let cleanupHandler = (err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + throw new ReferenceError('cleanupHandler was called too many times'); + }; + + opts = Object.assign({ throw: true }, opts); + session.endSession(); + + if (err) { + if (opts.throw) throw err; + return Promise.reject(err); + } + }; + + try { + const result = operation(session); + return Promise.resolve(result) + .then(result => cleanupHandler(null, result)) + .catch(err => cleanupHandler(err, null, { throw: true })); + } catch (err) { + return cleanupHandler(err, null, { throw: false }); + } +}; +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, + * and config databases. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +MongoClient.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the mongo client logger + * @method + * @return {Logger} return the mongo client logger + * @ignore + */ +MongoClient.prototype.getLogger = function() { + return this.s.options.logger; +}; + +module.exports = MongoClient; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js new file mode 100644 index 0000000..b08071c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js @@ -0,0 +1,62 @@ +'use strict'; + +const executeCommand = require('./db_ops').executeCommand; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; + +/** + * Get ReplicaSet status + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function replSetGetStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); +} + +/** + * Retrieve this db's server status. + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback + */ +function serverStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); +} + +/** + * Validate an existing collection + * + * @param {Admin} a collection instance. + * @param {string} collectionName The name of the collection to validate. + * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function validateCollection(admin, collectionName, options, callback) { + const command = { validate: collectionName }; + const keys = Object.keys(options); + + // Decorate command with extra options + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + executeCommand(admin.s.db, command, options, (err, doc) => { + if (err != null) return callback(err, null); + + if (doc.ok === 0) return callback(new Error('Error with validate command'), null); + if (doc.result != null && doc.result.constructor !== String) + return callback(new Error('Error with validation data'), null); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error('Error: invalid collection ' + collectionName), null); + if (doc.valid != null && !doc.valid) + return callback(new Error('Error: invalid collection ' + collectionName), null); + + return callback(null, doc); + }); +} + +module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js new file mode 100644 index 0000000..1314723 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js @@ -0,0 +1,1494 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const checkCollectionName = require('../utils').checkCollectionName; +const Code = require('mongodb-core').BSON.Code; +const createIndexDb = require('./db_ops').createIndex; +const decorateCommand = require('../utils').decorateCommand; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const ensureIndexDb = require('./db_ops').ensureIndex; +const evaluate = require('./db_ops').evaluate; +const executeCommand = require('./db_ops').executeCommand; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const resolveReadPreference = require('../utils').resolveReadPreference; +const handleCallback = require('../utils').handleCallback; +const indexInformationDb = require('./db_ops').indexInformation; +const isObject = require('../utils').isObject; +const Long = require('mongodb-core').BSON.Long; +const MongoError = require('mongodb-core').MongoError; +const ReadPreference = require('mongodb-core').ReadPreference; +const toError = require('../utils').toError; + +let collection; +function loadCollection() { + if (!collection) { + collection = require('../collection'); + } + return collection; +} +let db; +function loadDb() { + if (!db) { + db = require('../db'); + } + return db; +} + +/** + * Group function helper + * @ignore + */ +// var groupFunction = function () { +// var c = db[ns].find(condition); +// var map = new Map(); +// var reduce_function = reduce; +// +// while (c.hasNext()) { +// var obj = c.next(); +// var key = {}; +// +// for (var i = 0, len = keys.length; i < len; ++i) { +// var k = keys[i]; +// key[k] = obj[k]; +// } +// +// var aggObj = map.get(key); +// +// if (aggObj == null) { +// var newObj = Object.extend({}, key); +// aggObj = Object.extend(newObj, initial); +// map.put(key, aggObj); +// } +// +// reduce_function(obj, aggObj); +// } +// +// return { "result": map.values() }; +// }.toString(); +const groupFunction = + 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; + +/** + * Perform a bulkWrite operation. See Collection.prototype.bulkWrite for more information. + * + * @method + * @param {Collection} a Collection instance. + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. See Collection.prototype.bulkWrite for a list of options. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + */ +function bulkWrite(coll, operations, options, callback) { + // Add ignoreUndfined + if (coll.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = coll.s.options.ignoreUndefined; + } + + // Create the bulk operation + const bulk = + options.ordered === true || options.ordered == null + ? coll.initializeOrderedBulkOp(options) + : coll.initializeUnorderedBulkOp(options); + + // Do we have a collation + let collation = false; + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + // Get the operation type + const key = Object.keys(operations[i])[0]; + // Check if we have a collation + if (operations[i][key].collation) { + collation = true; + } + + // Pass to the raw bulk + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err, null); + } + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + const capabilities = coll.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + // Execute the bulk + bulk.execute(writeCon, finalOptions, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err, null); + } + + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + const inserted = r.getInsertedIds(); + // Map inserted ids + for (let i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + const upserted = r.getUpsertedIds(); + // Map upserted ids + for (let i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Return the results + callback(null, r); + }); +} + +// Check the update operation to ensure it has atomic operators. +function checkForAtomicOperators(update) { + const keys = Object.keys(update); + + // same errors as the server would give for update doc lacking atomic operators + if (keys.length === 0) { + return toError('The update operation document must contain at least one atomic operator.'); + } + + if (keys[0][0] !== '$') { + return toError('the update operation document must contain atomic operators.'); + } +} + +/** + * Count the number of documents in the collection that match the query. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count for a list of options. + * @param {Collection~countCallback} [callback] The command result callback + */ +function count(coll, query, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + options.collectionName = coll.s.name; + + options.readPreference = resolveReadPreference(options, { + db: coll.s.db, + collection: coll + }); + + let cmd; + try { + cmd = buildCountCommand(coll, query, options); + } catch (err) { + return callback(err); + } + + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +function countDocuments(coll, query, options, callback) { + const skip = options.skip; + const limit = options.limit; + options = Object.assign({}, options); + + const pipeline = [{ $match: query }]; + + // Add skip and limit if defined + if (typeof skip === 'number') { + pipeline.push({ $skip: skip }); + } + + if (typeof limit === 'number') { + pipeline.push({ $limit: limit }); + } + + pipeline.push({ $group: { _id: null, n: { $sum: 1 } } }); + + delete options.limit; + delete options.skip; + + coll.aggregate(pipeline, options).toArray((err, docs) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, docs.length ? docs[0].n : 0); + }); +} + +/** + * Build the count command. + * + * @method + * @param {collectionOrCursor} an instance of a collection or cursor + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. + */ +function buildCountCommand(collectionOrCursor, query, options) { + const skip = options.skip; + const limit = options.limit; + let hint = options.hint; + const maxTimeMS = options.maxTimeMS; + query = query || {}; + + // Final query + const cmd = { + count: options.collectionName, + query: query + }; + + // check if collectionOrCursor is a cursor by using cursor.s.numberOfRetries + if (collectionOrCursor.s.numberOfRetries) { + if (collectionOrCursor.s.options.hint) { + hint = collectionOrCursor.s.options.hint; + } else if (collectionOrCursor.s.cmd.hint) { + hint = collectionOrCursor.s.cmd.hint; + } + decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.s.cmd); + } else { + decorateWithCollation(cmd, collectionOrCursor, options); + } + + // Add limit, skip and maxTimeMS if defined + if (typeof skip === 'number') cmd.skip = skip; + if (typeof limit === 'number') cmd.limit = limit; + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + if (hint) cmd.hint = hint; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, collectionOrCursor); + + return cmd; +} + +/** + * Create an index on the db and collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndex(coll, fieldOrSpec, options, callback) { + createIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); +} + +/** + * Create multiple indexes in the collection. This method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * + * @method + * @param {Collection} a Collection instance. + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndexes(coll, indexSpecs, options, callback) { + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.s.name, + indexes: indexSpecs + }, + options, + callback + ); +} + +function deleteCallback(err, r, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.deletedCount = r.result.n; + if (callback) callback(null, r); +} + +/** + * Delete multiple documents from the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. See Collection.prototype.deleteMany for a list of options. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + */ +function deleteMany(coll, filter, options, callback) { + options.single = false; + + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); +} + +/** + * Delete a single document from the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. See Collection.prototype.deleteOne for a list of options. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + */ +function deleteOne(coll, filter, options, callback) { + options.single = true; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); +} + +/** + * Return a list of distinct values for the given key across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function distinct(coll, key, query, options, callback) { + // maxTimeMS option + const maxTimeMS = options.maxTimeMS; + + // Distinct command + const cmd = { + distinct: coll.s.name, + key: key, + query: query + }; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Add maxTimeMS if defined + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +/** + * Drop an index from this collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. See Collection.prototype.dropIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function dropIndex(coll, indexName, options, callback) { + // Delete index command + const cmd = { dropIndexes: coll.s.name, index: indexName }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute command + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (typeof callback !== 'function') return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +/** + * Drop all indexes from this collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.dropIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function dropIndexes(coll, options, callback) { + dropIndex(coll, '*', options, err => { + if (err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +/** + * Ensure that an index exists. If the index does not exist, this function creates it. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function ensureIndex(coll, fieldOrSpec, options, callback) { + ensureIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); +} + +/** + * Find and update a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +function findAndModify(coll, query, sort, doc, options, callback) { + // Create findAndModify command object + const queryObject = { + findAndModify: coll.s.name, + query: query + }; + + sort = formattedOrderClause(sort); + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + delete options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (finalOptions.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + finalOptions.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, finalOptions); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); +} + +/** + * Find and remove a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. See Collection.prototype.findAndRemove for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated use findOneAndDelete instead + */ +function findAndRemove(coll, query, sort, options, callback) { + // Add the remove option + options.remove = true; + // Execute the callback + findAndModify(coll, query, sort, null, options, callback); +} + +/** + * Fetch the first document that matches the query. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. See Collection.prototype.findOne for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function findOne(coll, query, options, callback) { + const cursor = coll + .find(query, options) + .limit(-1) + .batchSize(1); + + // Return the item + cursor.next((err, item) => { + if (err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +/** + * Find a document and delete it in one atomic operation. This requires a write lock for the duration of the operation. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter Document selection filter. + * @param {object} [options] Optional settings. See Collection.prototype.findOneAndDelete for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + */ +function findOneAndDelete(coll, filter, options, callback) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.remove = true; + // Execute find and Modify + findAndModify(coll, filter, options.sort, null, finalOptions, callback); +} + +/** + * Find a document and replace it in one atomic operation. This requires a write lock for the duration of the operation. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options] Optional settings. See Collection.prototype.findOneAndReplace for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + */ +function findOneAndReplace(coll, filter, replacement, options, callback) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; + finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; + + // Execute findAndModify + findAndModify(coll, filter, options.sort, replacement, finalOptions, callback); +} + +/** + * Find a document and update it in one atomic operation. This requires a write lock for the duration of the operation. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. See Collection.prototype.findOneAndUpdate for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + */ +function findOneAndUpdate(coll, filter, update, options, callback) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; + finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; + + // Execute findAndModify + findAndModify(coll, filter, options.sort, update, finalOptions, callback); +} + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function geoHaystackSearch(coll, x, y, options, callback) { + // Build command object + let commandObject = { + geoSearch: coll.s.name, + near: [x, y] + }; + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, res) => { + if (err) return handleCallback(callback, err); + if (res.err || res.errmsg) handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +/** + * Run a group command across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. + */ +function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if (command) { + const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); + + const selector = { + group: { + ns: coll.s.name, + $reduce: reduceFunction, + cond: condition, + initial: initial, + out: 'inline' + } + }; + + // if finalize is defined + if (finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { + selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); + } else { + const hash = {}; + keys.forEach(key => { + hash[key] = 1; + }); + selector.group.key = hash; + } + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Do we have a readConcern specified + decorateWithReadConcern(selector, coll, options); + + // Have we specified collation + try { + decorateWithCollation(selector, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, selector, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; + + scope.ns = coll.s.name; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +/** + * Retrieve all the indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexes(coll, options, callback) { + options = Object.assign({}, { full: true }, options); + indexInformationDb(coll.s.db, coll.s.name, options, callback); +} + +/** + * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexExists(coll, indexes, options, callback) { + indexInformation(coll, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +/** + * Retrieve this collection's index info. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexInformation(coll, options, callback) { + indexInformationDb(coll.s.db, coll.s.name, options, callback); +} + +function insertDocuments(coll, docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If keep going set unordered + if (finalOptions.keepGoing === true) finalOptions.ordered = false; + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // File inserts + coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Insert a single document into the collection. See Collection.prototype.insertOne for more information. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. See Collection.prototype.insertOne for a list of options. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + */ +function insertOne(coll, doc, options, callback) { + if (Array.isArray(doc)) { + return callback( + MongoError.create({ message: 'doc parameter must be an object', driver: true }) + ); + } + + insertDocuments(coll, [doc], options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + // Workaround for pre 2.6 servers + if (r == null) return callback(null, { result: { ok: 1 } }); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if (callback) callback(null, r); + }); +} + +/** + * Determine whether the collection is a capped collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.isCapped for a list of options. + * @param {Collection~resultCallback} [callback] The results callback + */ +function isCapped(coll, options, callback) { + optionsOp(coll, options, (err, document) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, !!(document && document.capped)); + }); +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function mapReduce(coll, map, reduce, options, callback) { + const mapCommandHash = { + mapreduce: coll.s.name, + map: map, + reduce: reduce + }; + + // Exclusion list + const exclusionList = ['readPreference', 'session', 'bypassDocumentValidation']; + + // Add any other options passed in + for (let n in options) { + if ('scope' === n) { + mapCommandHash[n] = processScope(options[n]); + } else { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + } + + options = Object.assign({}, options); + + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // If we have a read preference and inline is not set as output fail hard + if ( + options.readPreference !== false && + options.readPreference !== 'primary' && + options['out'] && + (options['out'].inline !== 1 && options['out'] !== 'inline') + ) { + // Force readPreference to primary + options.readPreference = 'primary'; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { + if (err) return handleCallback(callback, err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + const stats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + let Db = loadDb(); + collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( + doc.collection + ); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, { collection: collection, stats: stats }); + }); +} + +/** + * Return the options of the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.options for a list of options. + * @param {Collection~resultCallback} [callback] The results callback + */ +function optionsOp(coll, opts, callback) { + coll.s.db.listCollections({ name: coll.s.name }, opts).toArray((err, collections) => { + if (err) return handleCallback(callback, err); + if (collections.length === 0) { + return handleCallback( + callback, + MongoError.create({ message: `collection ${coll.s.namespace} not found`, driver: true }) + ); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +/** + * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are + * no ordering guarantees for returned results. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + */ +function parallelCollectionScan(coll, options, callback) { + // Create command object + const commandObject = { + parallelCollectionScan: coll.s.name, + numCursors: options.numCursors + }; + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Store the raw value + const raw = options.raw; + delete options['raw']; + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result == null) + return handleCallback( + callback, + new Error('no result returned for parallelCollectionScan'), + null + ); + + options = Object.assign({ explicitlyIgnoreSession: true }, options); + + const cursors = []; + // Add the raw back to the option + if (raw) options.raw = raw; + // Create command cursors for each item + for (let i = 0; i < result.cursors.length; i++) { + const rawId = result.cursors[i].cursor.id; + // Convert cursorId to Long if needed + const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; + // Add a command cursor + cursors.push(coll.s.topology.cursor(coll.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +// modifies documents before being inserted or updated +function prepareDocs(coll, docs, options) { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (forceServerObjectId !== true && doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope(scope) { + if (!isObject(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + + const keys = Object.keys(scope); + let key; + const new_scope = {}; + + for (let i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if ('function' === typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +/** + * Reindex all indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.reIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function reIndex(coll, options, callback) { + // Reindex + const cmd = { reIndex: coll.s.name }; + + // Execute the command + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +function removeDocuments(coll, selector, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}); + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If selector is null set empty + if (selector == null) selector = {}; + + // Build the op + const op = { q: selector, limit: 0 }; + if (options.single) { + op.limit = 1; + } else if (finalOptions.retryWrites) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the remove + coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Rename the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. See Collection.prototype.rename for a list of options. + * @param {Collection~collectionResultCallback} [callback] The results callback + */ +function rename(coll, newName, options, callback) { + let Collection = loadCollection(); + // Check the collection name + checkCollectionName(newName); + // Build the command + const renameCollection = `${coll.s.dbName}.${coll.s.name}`; + const toCollection = `${coll.s.dbName}.${newName}`; + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute against admin + executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { + if (err) return handleCallback(callback, err, null); + // We have an error + if (doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback( + callback, + null, + new Collection( + coll.s.db, + coll.s.topology, + coll.s.dbName, + newName, + coll.s.pkFactory, + coll.s.options + ) + ); + } catch (err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +/** + * Replace a document in the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. See Collection.prototype.replaceOne for a list of options. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + */ +function replaceOne(coll, filter, doc, options, callback) { + // Set single document update + options.multi = false; + + // Execute update + updateDocuments(coll, filter, doc, options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + r.ops = [doc]; + if (callback) callback(null, r); + }); +} + +/** + * Save a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to save + * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +function save(coll, doc, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern( + Object.assign({}, options), + { db: coll.s.db, collection: coll }, + options + ); + // Establish if we need to perform an insert or update + if (doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(coll, [doc], finalOptions, (err, result) => { + if (callback == null) return; + if (doc == null) return handleCallback(callback, null, null); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +/** + * Get all the collection statistics. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + * @param {Collection~resultCallback} [callback] The collection result callback + */ +function stats(coll, options, callback) { + // Build command object + const commandObject = { + collStats: coll.s.name + }; + + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, callback); +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +function updateDocuments(coll, selector, document, options, callback) { + if ('function' === typeof options) (callback = options), (options = null); + if (options == null) options = {}; + if (!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if (selector == null || typeof selector !== 'object') + return callback(toError('selector must be a valid JavaScript object')); + if (document == null || typeof document !== 'object') + return callback(toError('document must be a valid JavaScript object')); + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // Execute the operation + const op = { q: selector, u: document }; + op.upsert = options.upsert !== void 0 ? !!options.upsert : false; + op.multi = options.multi !== void 0 ? !!options.multi : false; + + if (finalOptions.arrayFilters) { + op.arrayFilters = finalOptions.arrayFilters; + delete finalOptions.arrayFilters; + } + + if (finalOptions.retryWrites && op.multi) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Update options + coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Update multiple documents in the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. See Collection.prototype.updateMany for a list of options. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + */ +function updateMany(coll, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); +} + +/** + * Update a single document in the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. See Collection.prototype.updateOne for a list of options. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + */ +function updateOne(coll, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); +} + +module.exports = { + bulkWrite, + checkForAtomicOperators, + count, + countDocuments, + buildCountCommand, + createIndex, + createIndexes, + deleteMany, + deleteOne, + distinct, + dropIndex, + dropIndexes, + ensureIndex, + findAndModify, + findAndRemove, + findOne, + findOneAndDelete, + findOneAndReplace, + findOneAndUpdate, + geoHaystackSearch, + group, + indexes, + indexExists, + indexInformation, + insertOne, + isCapped, + mapReduce, + optionsOp, + parallelCollectionScan, + prepareDocs, + reIndex, + removeDocuments, + rename, + replaceOne, + save, + stats, + updateDocuments, + updateMany, + updateOne +}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js new file mode 100644 index 0000000..fa6db95 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js @@ -0,0 +1,250 @@ +'use strict'; + +const buildCountCommand = require('./collection_ops').buildCountCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('mongodb-core').MongoError; +const push = Array.prototype.push; + +let cursor; +function loadCursor() { + if (!cursor) { + cursor = require('../cursor'); + } + return cursor; +} + +/** + * Get the count of documents for this cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to count. + * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. + * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. + * @param {Cursor~countResultCallback} [callback] The result callback. + */ +function count(cursor, applySkipLimit, opts, callback) { + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (opts.readPreference) { + cursor.setReadPreference(opts.readPreference); + } + + if ( + typeof opts.maxTimeMS !== 'number' && + cursor.s.cmd && + typeof cursor.s.cmd.maxTimeMS === 'number' + ) { + opts.maxTimeMS = cursor.s.cmd.maxTimeMS; + } + + let options = {}; + options.skip = opts.skip; + options.limit = opts.limit; + options.hint = opts.hint; + options.maxTimeMS = opts.maxTimeMS; + + // Command + const delimiter = cursor.s.ns.indexOf('.'); + options.collectionName = cursor.s.ns.substr(delimiter + 1); + + let command; + try { + command = buildCountCommand(cursor, cursor.s.cmd.query, options); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.s.topology.command( + `${cursor.s.ns.substr(0, delimiter)}.$cmd`, + command, + cursor.s.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); +} + +/** + * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. + * + * @method + * @deprecated + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} callback The result callback. + */ +function each(cursor, callback) { + let Cursor = loadCursor(); + + if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); + if (cursor.isNotified()) return; + if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === Cursor.INIT) cursor.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + let fn = null; + // Trampoline all the entries + if (cursor.bufferedCount() > 0) { + while ((fn = loop(cursor, callback))) fn(cursor, callback); + each(cursor, callback); + } else { + cursor.next((err, item) => { + if (err) return handleCallback(callback, err); + if (item == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); + } + + if (handleCallback(callback, null, item) === false) return; + each(cursor, callback); + }); + } +} + +/** + * Check if there is any document still available in the cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function hasNext(cursor, callback) { + let Cursor = loadCursor(); + + if (cursor.s.currentDoc) { + return callback(null, true); + } + + if (cursor.isNotified()) { + return callback(null, false); + } + + nextObject(cursor, (err, doc) => { + if (err) return callback(err, null); + if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); + if (!doc) return callback(null, false); + cursor.s.currentDoc = doc; + callback(null, true); + }); +} + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +function loop(cursor, callback) { + // No more items we are done + if (cursor.bufferedCount() === 0) return; + // Get the next document + cursor._next(callback); + // Loop + return loop; +} + +/** + * Get the next available document from the cursor. Returns null if no more documents are available. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function next(cursor, callback) { + // Return the currentDoc if someone called hasNext first + if (cursor.s.currentDoc) { + const doc = cursor.s.currentDoc; + cursor.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + nextObject(cursor, callback); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + let Cursor = loadCursor(); + + if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead())) + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) { + try { + cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = Cursor.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +/** + * Returns an array of documents. See Cursor.prototype.toArray for more information. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + */ +function toArray(cursor, callback) { + let Cursor = loadCursor(); + + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = Cursor.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return cursor._endSession + ? cursor._endSession(() => handleCallback(callback, err)) + : handleCallback(callback, err); + } + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); +} + +module.exports = { count, each, hasNext, next, toArray }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js new file mode 100644 index 0000000..2717966 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js @@ -0,0 +1,1006 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('mongodb-core').BSON.Code; +const resolveReadPreference = require('../utils').resolveReadPreference; +const crypto = require('crypto'); +const debugOptions = require('../utils').debugOptions; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('mongodb-core').MongoError; +const parseIndexOptions = require('../utils').parseIndexOptions; +const ReadPreference = require('mongodb-core').ReadPreference; +const toError = require('../utils').toError; +const CONSTANTS = require('../constants'); + +const count = require('./collection_ops').count; +const findOne = require('./collection_ops').findOne; +const remove = require('./collection_ops').remove; +const updateOne = require('./collection_ops').updateOne; + +let collection; +function loadCollection() { + if (!collection) { + collection = require('../collection'); + } + return collection; +} +let db; +function loadDb() { + if (!db) { + db = require('../db'); + } + return db; +} + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +// Filter out any write concern options +const illegalCommandFields = [ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'strict', + 'serializeFunctions', + 'pkFactory', + 'raw', + 'readPreference', + 'session' +]; + +/** + * Add a user to the database. + * @method + * @param {Db} db The Db instance on which to add a user. + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function addUser(db, username, password, options, callback) { + let Db = loadDb(); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + executeAuthCreateUserCommand(db, username, password, options, (err, r) => { + // We need to perform the backward compatible insert operation + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + const userPassword = md5.digest('hex'); + + // If we have another db set + const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + count(collection, {}, finalOptions, (err, count) => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); + collection.find({ user: username }, findOptions).toArray(err => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + updateOne( + collection, + { user: username }, + { $set: { user: username, pwd: userPassword } }, + finalOptions, + err => { + if (count === 0 && err) + return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + } + ); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db} db The Db instance on which to fetch collections. + * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. + * @param {Db~collectionsResultCallback} [callback] The results callback + */ +function collections(db, options, callback) { + let Collection = loadCollection(); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.s.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); +} + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {Db} db The Db instance on which to create the collection. + * @param {string} name The collection name to create. + * @param {object} [options] Optional settings. See Db.prototype.createCollection for a list of options. + * @param {Db~collectionResultCallback} [callback] The results callback + */ +function createCollection(db, name, options, callback) { + let Collection = loadCollection(); + + // Get the write concern options + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, finalOptions, { nameOnly: true }); + + // Check if we have the name + db + .listCollections({ name }, listCollectionOptions) + .setReadPreference(ReadPreference.PRIMARY) + .toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length > 0 && finalOptions.strict) { + return handleCallback( + callback, + MongoError.create({ + message: `Collection ${name} already exists. Currently in strict mode.`, + driver: true + }), + null + ); + } else if (collections.length > 0) { + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.s.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Create collection command + const cmd = { create: name }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db }, options); + + // Add all optional parameters + for (let n in options) { + if ( + options[n] != null && + typeof options[n] !== 'function' && + illegalCommandFields.indexOf(n) === -1 + ) { + cmd[n] = options[n]; + } + } + + // Force a primary read Preference + finalOptions.readPreference = ReadPreference.PRIMARY; + // Execute command + executeCommand(db, cmd, finalOptions, err => { + if (err) return handleCallback(callback, err); + + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.s.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + }); + }); +} + +/** + * Creates an index on the db and collection. + * @method + * @param {Db} db The Db instance on which to create an index. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function createIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); + finalOptions = applyWriteConcern(finalOptions, { db }, options); + + // Ensure we have a callback + if (finalOptions.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { + if (err == null) return handleCallback(callback, err, result); + + /** + * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: + * 67 = 'CannotCreateIndex' (malformed index options) + * 85 = 'IndexOptionsConflict' (index already exists with different options) + * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) + * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) + * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) + * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) + */ + if ( + err.code === 67 || + err.code === 11000 || + err.code === 85 || + err.code === 86 || + err.code === 11600 || + err.code === 197 + ) { + return handleCallback(callback, err, result); + } + + // Create command + const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + db.s.topology.insert( + `${db.s.databaseName}.${CONSTANTS.SYSTEM_INDEX_COLLECTION}`, + doc, + finalOptions, + (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.writeErrors) + return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + } + ); + }); +} + +// Add listeners to topology +function createListener(db, e, object) { + function listener(err) { + if (object.listeners(e).length > 0) { + object.emit(e, err, db); + + // Emit on all associated db's if available + for (let i = 0; i < db.s.children.length; i++) { + db.s.children[i].emit(e, err, db.s.children[i]); + } + } + } + return listener; +} + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Db} db The Db instance on which to drop the collection. + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropCollection(db, name, options, callback) { + executeCommand(db, name, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); +} + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db} db The Db instance to drop. + * @param {Object} cmd The command document. + * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropDatabase(db, cmd, options, callback) { + executeCommand(db, cmd, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +/** + * Ensures that an index exists. If it does not, creates it. + * + * @method + * @param {Db} db The Db instance on which to ensure the index. + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function ensureIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern({}, { db }, options); + // Create command + const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); + const index_name = selector.name; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Merge primary readPreference + finalOptions.readPreference = ReadPreference.PRIMARY; + + // Check if the index already exists + indexInformation(db, name, finalOptions, (err, indexInformation) => { + if (err != null && err.code !== 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if (indexInformation == null || !indexInformation[index_name]) { + createIndex(db, name, fieldOrSpec, options, callback); + } else { + if (typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Db} db The Db instance. + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + */ +function evaluate(db, code, parameters, options, callback) { + let finalCode = code; + let finalParameters = []; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + let cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new ReadPreference(ReadPreference.PRIMARY); + + // Execute the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result && result.ok === 1) return handleCallback(callback, null, result.retval); + if (result) + return handleCallback( + callback, + MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), + null + ); + handleCallback(callback, err, result); + }); +} + +/** + * Execute a command + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeCommand(db, command, options, callback) { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.s.databaseName; + + // Convert the readPreference if its not a write + options.readPreference = resolveReadPreference(options, { db, default: ReadPreference.primary }); + + // Debug information + if (db.s.logger.isDebug()) + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + + // Execute command + db.s.topology.command(`${dbName}.$cmd`, command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Runs a command on the database as admin. + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeDbAdminCommand(db, command, options, callback) { + db.s.topology.command('admin.$cmd', command, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db + .collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +// Transformation methods for cursor results +function listCollectionsTransforms(databaseName) { + const matching = `${databaseName}.`; + + return { + doc: doc => { + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + }; +} + +/** + * Retrive the current profiling information for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling info. + * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + * @deprecated Query the system.profile collection directly. + */ +function profilingInfo(db, options, callback) { + try { + db + .collection('system.profile') + .find({}, options) + .toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +/** + * Retrieve the current profiling level for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling level. + * @param {Object} [options] Optional settings. See Db.prototype.profilingLevel for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function profilingLevel(db, options, callback) { + executeCommand(db, { profile: -1 }, options, (err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) return callback(null, 'off'); + if (was === 1) return callback(null, 'slow_only'); + if (was === 2) return callback(null, 'all'); + return callback(new Error('Error: illegal profiling level value ' + was), null); + } else { + err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); + } + }); +} + +/** + * Remove a user from a database + * + * @method + * @param {Db} db The Db instance on which to remove the user. + * @param {string} username The username. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function removeUser(db, username, options, callback) { + let Db = loadDb(); + + // Attempt to execute command + executeAuthRemoveUserCommand(db, username, options, (err, result) => { + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + // If we have another db set + const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Locate the user + findOne(collection, { user: username }, finalOptions, (err, user) => { + if (user == null) return handleCallback(callback, err, false); + remove(collection, { user: username }, finalOptions, err => { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +/** + * Set the current profiling level of MongoDB + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings. See Db.prototype.setProfilingLevel for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function setProfilingLevel(db, level, options, callback) { + const command = {}; + let profile = 0; + + if (level === 'off') { + profile = 0; + } else if (level === 'slow_only') { + profile = 1; + } else if (level === 'all') { + profile = 2; + } else { + return callback(new Error('Error: illegal profiling level value ' + level)); + } + + // Set up the profile number + command['profile'] = profile; + + executeCommand(db, command, options, (err, doc) => { + if (err == null && doc.ok === 1) return callback(null, level); + return err != null + ? callback(err, null) + : callback(new Error('Error with profile command'), null); + }); +} + +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw MongoError.create({ message: 'database name must be a string', driver: true }); + if (databaseName.length === 0) + throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw MongoError.create({ + message: "database names cannot contain the character '" + invalidChars[i] + "'", + driver: true + }); + } +} + +/** + * Create the command object for Db.prototype.createIndex. + * + * @param {Db} db The Db instance on which to create the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @return {Object} The insert command object. + */ +function createCreateIndexCommand(db, name, fieldOrSpec, options) { + const indexParameters = parseIndexOptions(fieldOrSpec); + const fieldHash = indexParameters.fieldHash; + + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + const selector = { + ns: db.databaseName + '.' + name, + key: fieldHash, + name: indexName + }; + + // Ensure we have a correct finalUnique + const finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options === 'boolean' ? {} : options; + + // Add all the options + const keysToOmit = Object.keys(selector); + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + selector[optionName] = options[optionName]; + } + } + + if (selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; + for (let i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +/** + * Create index using the createIndexes command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + const keysToOmit = Object.keys(indexes[0]).concat([ + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' + ]); + + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + indexes[0][optionName] = options[optionName]; + } + } + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Create command, apply write concern to command + const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); + + // ReadPreference primary + options.readPreference = ReadPreference.PRIMARY; + + // Build the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result.ok === 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +/** + * Run the createUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to add. + * @param {string} password The password of the user to add. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthCreateUserCommand(db, username, password, options, callback) { + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + // Unpack all options + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Get additional values + const customData = options.customData != null ? options.customData : {}; + let roles = Array.isArray(options.roles) ? options.roles : []; + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + // Build the command to execute + let command = { + createUser: username, + customData: customData, + roles: roles, + digestPassword + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && err.ok === 0 && err.code === undefined) + return handleCallback(callback, { code: -5000 }, null); + if (err) return handleCallback(callback, err, null); + handleCallback( + callback, + !result.ok ? toError(result) : null, + result.ok ? [{ user: username, pwd: '' }] : null + ); + }); +} + +/** + * Run the dropUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to remove. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthRemoveUserCommand(db, username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + let command = { + dropUser: username + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +module.exports = { + addUser, + collections, + createCollection, + createListener, + createIndex, + dropCollection, + dropDatabase, + ensureIndex, + evaluate, + executeCommand, + executeDbAdminCommand, + listCollectionsTransforms, + indexInformation, + profilingInfo, + profilingLevel, + removeUser, + setProfilingLevel, + validateDatabaseName +}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js new file mode 100644 index 0000000..d53ee7c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/operations/mongo_client_ops.js @@ -0,0 +1,654 @@ +'use strict'; + +const authenticate = require('../authenticate'); +const deprecate = require('util').deprecate; +const Logger = require('mongodb-core').Logger; +const MongoError = require('mongodb-core').MongoError; +const Mongos = require('../topologies/mongos'); +const parse = require('mongodb-core').parseConnectionString; +const ReadPreference = require('mongodb-core').ReadPreference; +const ReplSet = require('../topologies/replset'); +const Server = require('../topologies/server'); +const ServerSessionPool = require('mongodb-core').Sessions.ServerSessionPool; + +let client; +function loadClient() { + if (!client) { + client = require('../mongo_client'); + } + return client; +} + +const monitoringEvents = [ + 'timeout', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha', + 'all', + 'fullsetup', + 'open' +]; +const ignoreOptionNames = ['native_parser']; +const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; +const legacyParse = deprecate( + require('../url_parser'), + 'current URL string parser is deprecated, and will be removed in a future version. ' + + 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' +); +const validOptionNames = [ + 'poolSize', + 'ssl', + 'sslValidate', + 'sslCA', + 'sslCert', + 'sslKey', + 'sslPass', + 'sslCRL', + 'autoReconnect', + 'noDelay', + 'keepAlive', + 'keepAliveInitialDelay', + 'connectTimeoutMS', + 'family', + 'socketTimeoutMS', + 'reconnectTries', + 'reconnectInterval', + 'ha', + 'haInterval', + 'replicaSet', + 'secondaryAcceptableLatencyMS', + 'acceptableLatencyMS', + 'connectWithNoPrimary', + 'authSource', + 'w', + 'wtimeout', + 'j', + 'forceServerObjectId', + 'serializeFunctions', + 'ignoreUndefined', + 'raw', + 'bufferMaxEntries', + 'readPreference', + 'pkFactory', + 'promiseLibrary', + 'readConcern', + 'maxStalenessSeconds', + 'loggerLevel', + 'logger', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs', + 'domainsEnabled', + 'checkServerIdentity', + 'validateOptions', + 'appname', + 'auth', + 'user', + 'password', + 'authMechanism', + 'compression', + 'fsync', + 'readPreferenceTags', + 'numberOfRetries', + 'auto_reconnect', + 'minSize', + 'monitorCommands', + 'retryWrites', + 'useNewUrlParser' +]; + +function addListeners(mongoClient, topology) { + topology.on('authenticated', createListener(mongoClient, 'authenticated')); + topology.on('error', createListener(mongoClient, 'error')); + topology.on('timeout', createListener(mongoClient, 'timeout')); + topology.on('close', createListener(mongoClient, 'close')); + topology.on('parseError', createListener(mongoClient, 'parseError')); + topology.once('open', createListener(mongoClient, 'open')); + topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); + topology.once('all', createListener(mongoClient, 'all')); + topology.on('reconnect', createListener(mongoClient, 'reconnect')); +} + +function assignTopology(client, topology) { + client.topology = topology; + topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); +} + +// Clear out all events +function clearAllEvents(topology) { + monitoringEvents.forEach(event => topology.removeAllListeners(event)); +} + +// Collect all events in order from SDAM +function collectEvents(mongoClient, topology) { + let MongoClient = loadClient(); + const collectedEvents = []; + + if (mongoClient instanceof MongoClient) { + monitoringEvents.forEach(event => { + topology.on(event, (object1, object2) => { + if (event === 'open') { + collectedEvents.push({ event: event, object1: mongoClient }); + } else { + collectedEvents.push({ event: event, object1: object1, object2: object2 }); + } + }); + }); + } + + return collectedEvents; +} + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient} mongoClient The MongoClient instance with which to connect. + * @param {string} url The connection URI string + * @param {object} [options] Optional settings. See MongoClient.prototype.connect for a list of options. + * @param {MongoClient~connectCallback} [callback] The command result callback + */ +function connect(mongoClient, url, options, callback) { + options = Object.assign({}, options); + + // If callback is null throw an exception + if (callback == null) { + throw new Error('no callback function provided'); + } + + // Get a logger for MongoClient + const logger = Logger('MongoClient', options); + + // Did we pass in a Server/ReplSet/Mongos + if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { + return connectWithUrl(mongoClient, url, options, connectCallback); + } + + const parseFn = options.useNewUrlParser ? parse : legacyParse; + const transform = options.useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; + + parseFn(url, options, (err, _object) => { + // Do not attempt to connect if parsing error + if (err) return callback(err); + + // Flatten + const object = transform(_object); + + // Parse the string + const _finalOptions = createUnifiedOptions(object, options); + + // Check if we have connection and socket timeout set + if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; + if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; + + if (_finalOptions.db_options && _finalOptions.db_options.auth) { + delete _finalOptions.db_options.auth; + } + + // Store the merged options object + mongoClient.s.options = _finalOptions; + + // Failure modes + if (object.servers.length === 0) { + return callback(new Error('connection string must contain at least one seed host')); + } + + // Do we have a replicaset then skip discovery and go straight to connectivity + if (_finalOptions.replicaSet || _finalOptions.rs_name) { + return createTopology( + mongoClient, + 'replicaset', + _finalOptions, + connectHandler(mongoClient, _finalOptions, connectCallback) + ); + } else if (object.servers.length > 1) { + return createTopology( + mongoClient, + 'mongos', + _finalOptions, + connectHandler(mongoClient, _finalOptions, connectCallback) + ); + } else { + return createServer( + mongoClient, + _finalOptions, + connectHandler(mongoClient, _finalOptions, connectCallback) + ); + } + }); + function connectCallback(err, topology) { + const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + return callback(new MongoError(warningMessage)); + } + + // Return the error and db instance + callback(err, topology); + } +} + +function connectHandler(client, options, callback) { + return (err, topology) => { + if (err) { + return handleConnectCallback(err, topology, callback); + } + + // No authentication just reconnect + if (!options.auth) { + return handleConnectCallback(err, topology, callback); + } + + // Authenticate + authenticate(client, options.user, options.password, options, (err, success) => { + if (success) { + handleConnectCallback(null, topology, callback); + } else { + if (topology) topology.close(); + const authError = err ? err : new Error('Could not authenticate user ' + options.auth[0]); + handleConnectCallback(authError, topology, callback); + } + }); + }; +} + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient} mongoClient The MongoClient instance with which to connect. + * @param {MongoClient~connectCallback} [callback] The command result callback + */ +function connectOp(mongoClient, err, callback) { + // Did we have a validation error + if (err) return callback(err); + // Fallback to callback based connect + connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { + if (err) return callback(err); + callback(null, mongoClient); + }); +} + +function connectWithUrl(mongoClient, url, options, connectCallback) { + // Set the topology + assignTopology(mongoClient, url); + + // Add listeners + addListeners(mongoClient, url); + + // Propagate the events to the client + relayEvents(mongoClient, url); + + let finalOptions = Object.assign({}, options); + + // If we have a readPreference passed in by the db options, convert it from a string + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + finalOptions.readPreference = new ReadPreference( + options.readPreference || options.read_preference + ); + } + + // Connect + return url.connect( + finalOptions, + connectHandler(mongoClient, finalOptions, (err, topology) => { + if (err) return connectCallback(err, topology); + if (finalOptions.user || finalOptions.password || finalOptions.authMechanism) { + return authenticate( + mongoClient, + finalOptions.user, + finalOptions.password, + finalOptions, + err => { + if (err) return connectCallback(err, topology); + connectCallback(err, topology); + } + ); + } + + connectCallback(err, topology); + }) + ); +} + +function createListener(mongoClient, event) { + const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); + return (v1, v2) => { + if (eventSet.has(event)) { + return mongoClient.emit(event, mongoClient); + } + + mongoClient.emit(event, v1, v2); + }; +} + +function createServer(mongoClient, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + // Set default options + const servers = translateOptions(options); + + const server = servers[0]; + + // Propagate the events to the client + const collectedEvents = collectEvents(mongoClient, server); + + // Connect to topology + server.connect(options, (err, topology) => { + if (err) { + server.close(true); + return callback(err); + } + // Clear out all the collected event listeners + clearAllEvents(server); + + // Relay all the events + relayEvents(mongoClient, server); + // Add listeners + addListeners(mongoClient, server); + // Check if we are really speaking to a mongos + const ismaster = topology.lastIsMaster(); + + // Set the topology + assignTopology(mongoClient, topology); + + // Do we actually have a mongos + if (ismaster && ismaster.msg === 'isdbgrid') { + // Destroy the current connection + topology.close(); + // Create mongos connection instead + return createTopology(mongoClient, 'mongos', options, callback); + } + + // Fire all the events + replayEvents(mongoClient, collectedEvents); + // Otherwise callback + callback(err, topology); + }); +} + +function createTopology(mongoClient, topologyType, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + const translationOptions = {}; + if (topologyType === 'unified') translationOptions.createServers = false; + + // Set default options + const servers = translateOptions(options, translationOptions); + + // Create the topology + let topology; + if (topologyType === 'mongos') { + topology = new Mongos(servers, options); + } else if (topologyType === 'replicaset') { + topology = new ReplSet(servers, options); + } + + // Add listeners + addListeners(mongoClient, topology); + + // Propagate the events to the client + relayEvents(mongoClient, topology); + + // Open the connection + topology.connect(options, (err, newTopology) => { + if (err) { + topology.close(true); + return callback(err); + } + + assignTopology(mongoClient, newTopology); + callback(null, newTopology); + }); +} + +function createUnifiedOptions(finalOptions, options) { + const childOptions = [ + 'mongos', + 'server', + 'db', + 'replset', + 'db_options', + 'server_options', + 'rs_options', + 'mongos_options' + ]; + const noMerge = ['readconcern', 'compression']; + + for (const name in options) { + if (noMerge.indexOf(name.toLowerCase()) !== -1) { + finalOptions[name] = options[name]; + } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { + finalOptions = mergeOptions(finalOptions, options[name], false); + } else { + if ( + options[name] && + typeof options[name] === 'object' && + !Buffer.isBuffer(options[name]) && + !Array.isArray(options[name]) + ) { + finalOptions = mergeOptions(finalOptions, options[name], true); + } else { + finalOptions[name] = options[name]; + } + } + } + + return finalOptions; +} + +function handleConnectCallback(err, topology, callback) { + return process.nextTick(() => { + try { + callback(err, topology); + } catch (err) { + if (topology) topology.close(); + throw err; + } + }); +} + +function legacyTransformUrlOptions(object) { + return mergeOptions(createUnifiedOptions({}, object), object, false); +} + +/** + * Logout user from server, fire off on all connections and remove all auth info. + * + * @method + * @param {MongoClient} mongoClient The MongoClient instance on which to logout. + * @param {object} [options] Optional settings. See MongoClient.prototype.logout for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function logout(mongoClient, dbName, callback) { + mongoClient.topology.logout(dbName, err => { + if (err) return callback(err); + callback(null, true); + }); +} + +function mergeOptions(target, source, flatten) { + for (const name in source) { + if (source[name] && typeof source[name] === 'object' && flatten) { + target = mergeOptions(target, source[name], flatten); + } else { + target[name] = source[name]; + } + } + + return target; +} + +function relayEvents(mongoClient, topology) { + const serverOrCommandEvents = [ + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + + serverOrCommandEvents.forEach(event => { + topology.on(event, (object1, object2) => { + mongoClient.emit(event, object1, object2); + }); + }); +} + +// +// Replay any events due to single server connection switching to Mongos +// +function replayEvents(mongoClient, events) { + for (let i = 0; i < events.length; i++) { + mongoClient.emit(events[i].event, events[i].object1, events[i].object2); + } +} + +const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { + obj[name.toLowerCase()] = name; + return obj; +}, {}); + +function transformUrlOptions(_object) { + let object = Object.assign({ servers: _object.hosts }, _object.options); + for (let name in object) { + const camelCaseName = LEGACY_OPTIONS_MAP[name]; + if (camelCaseName) { + object[camelCaseName] = object[name]; + } + } + if (_object.auth) { + const auth = _object.auth; + for (let i in auth) { + if (auth[i]) { + object[i] = auth[i]; + } + } + + if (auth.username) { + object.auth = auth; + object.user = auth.username; + } + + if (auth.db) { + object.authSource = object.authSource || auth.db; + } + } + + if (_object.defaultDatabase) { + object.dbName = _object.defaultDatabase; + } + + if (object.maxpoolsize) { + object.poolSize = object.maxpoolsize; + } + + if (object.readconcernlevel) { + object.readConcern = { level: object.readconcernlevel }; + } + + if (object.wtimeoutms) { + object.wtimeout = object.wtimeoutms; + } + + return object; +} + +function translateOptions(options, translationOptions) { + translationOptions = Object.assign({}, { createServers: true }, translationOptions); + + // If we have a readPreference passed in by the db options + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + options.readPreference = new ReadPreference(options.readPreference || options.read_preference); + } + + // Do we have readPreference tags, add them + if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { + options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; + } + + // Do we have maxStalenessSeconds + if (options.maxStalenessSeconds) { + options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; + } + + // Set the socket and connection timeouts + if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; + if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; + + if (!translationOptions.createServers) { + return; + } + + // Create server instances + return options.servers.map(serverObj => { + return serverObj.domain_socket + ? new Server(serverObj.domain_socket, 27017, options) + : new Server(serverObj.host, serverObj.port, options); + }); +} + +// Validate options object +function validOptions(options) { + const _validOptions = validOptionNames.concat(legacyOptionNames); + + for (const name in options) { + if (ignoreOptionNames.indexOf(name) !== -1) { + continue; + } + + if (_validOptions.indexOf(name) === -1 && options.validateOptions) { + return new MongoError(`option ${name} is not supported`); + } else if (_validOptions.indexOf(name) === -1) { + console.warn(`the options [${name}] is not supported`); + } + + if (legacyOptionNames.indexOf(name) !== -1) { + console.warn( + `the server/replset/mongos/db options are deprecated, ` + + `all their options are supported at the top level of the options object [${validOptionNames}]` + ); + } + } +} + +module.exports = { connectOp, logout, validOptions }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js new file mode 100644 index 0000000..dc14277 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js @@ -0,0 +1,452 @@ +'use strict'; + +const TopologyBase = require('./topology_base').TopologyBase; +const MongoError = require('mongodb-core').MongoError; +const CMongos = require('mongodb-core').Mongos; +const Cursor = require('../cursor'); +const Server = require('./server'); +const Store = require('./topology_base').Store; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @fires Mongos#commandStarted + * @fires Mongos#commandSucceeded + * @fires Mongos#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Mongos} a Mongos instance. + */ +class Mongos extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Internal state + this.s = { + // Create the Mongos + coreTopology: new CMongos(seedlist, clonedOptions), + // Server capabilities + sCapabilities: null, + // Debug turned on + debug: clonedOptions.debug, + // Store option defaults + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Actual store of callbacks + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: [], + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Force close the topology + self.close(true); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect'); + self.s.store.execute(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + var events = ['timeout', 'error', 'close', 'fullsetup']; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.on('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + + // Set up serverConfig listeners + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + // Join and leave events + self.s.coreTopology.on('joined', relay('joined')); + self.s.coreTopology.on('left', relay('left')); + + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Mongos.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js new file mode 100644 index 0000000..0a73134 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js @@ -0,0 +1,497 @@ +'use strict'; + +const Server = require('./server'); +const Cursor = require('../cursor'); +const MongoError = require('mongodb-core').MongoError; +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const CReplSet = require('mongodb-core').ReplSet; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'replicaSet', + 'rs_name', + 'secondaryAcceptableLatencyMS', + 'connectWithNoPrimary', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslCRL', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'strategy', + 'debug', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'maxStalenessSeconds', + 'promiseLibrary', + 'minSize', + 'monitorCommands' +]; + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {boolean} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=10000] Time between each replicaset status check. + * @param {string} [options.replicaSet] The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @fires ReplSet#commandStarted + * @fires ReplSet#commandSucceeded + * @fires ReplSet#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {ReplSet} a ReplSet instance. + */ +class ReplSet extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create the ReplSet + var coreTopology = new CReplSet(seedlist, clonedOptions); + + // Listen to reconnect event + coreTopology.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + coreTopology: coreTopology, + // Server capabilities + sCapabilities: null, + // Debug tag + tag: options.tag, + // Store options + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Store + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: [], + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + + // Debug + if (clonedOptions.debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable: true, + get: function() { + return coreTopology; + } + }); + } + } + + // Connect method + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + }; + }; + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if (t === 'start') { + self.emit('ha_connect', t, state); + } else if (t === 'end') { + self.emit('ha_ismaster', t, state); + } + }; + + // Set up serverConfig listeners + self.s.coreTopology.on('joined', replsetRelay('joined')); + self.s.coreTopology.on('left', relay('left')); + self.s.coreTopology.on('ping', relay('ping')); + self.s.coreTopology.on('ha', relayHa); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self, self); + }); + + self.s.coreTopology.on('all', function() { + self.emit('all', null, self); + }); + + // Connect handler + var connectHandler = function() { + // Set up listeners + self.s.coreTopology.once('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.once('close', errorHandler('close')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.coreTopology.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.coreTopology.destroy(); + + // Try to callback + try { + callback(err); + } catch (err) { + if (!self.s.coreTopology.isConnected()) + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } + + close(forceClosed) { + super.close(forceClosed); + + ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); + } +} + +Object.defineProperty(ReplSet.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js new file mode 100644 index 0000000..77d8b6e --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js @@ -0,0 +1,455 @@ +'use strict'; + +const CServer = require('mongodb-core').Server; +const Cursor = require('../cursor'); +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const MongoError = require('mongodb-core').MongoError; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'reconnectInterval', + 'monitoring', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'compression', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster + * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#commandStarted + * @fires Server#commandSucceeded + * @fires Server#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Server} a Server instance. + */ +class Server extends TopologyBase { + constructor(host, port, options) { + super(); + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Promise library + const promiseLibrary = options.promiseLibrary; + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if (host.indexOf('/') !== -1) { + if (port != null && typeof port === 'object') { + options = port; + port = null; + } + } else if (port == null) { + throw MongoError.create({ message: 'port must be specified', driver: true }); + } + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + host: host, + port: port, + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + coreTopology: new CServer(clonedOptions), + // Server capabilities + sCapabilities: null, + // Cloned options + clonedOptions: clonedOptions, + // Reconnect + reconnect: clonedOptions.reconnect, + // Emit error + emitError: clonedOptions.emitError, + // Pool size + poolSize: clonedOptions.size, + // Store Options + storeOptions: storeOptions, + // Store + store: store, + // Host + host: host, + // Port + port: port, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: [], + // Promise library + promiseLibrary: promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = this.s.clonedOptions; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.coreTopology.removeListener(e, connectHandlers[e]); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect', self); + self.s.store.execute(); + }; + + // Reconnect failed + var reconnectFailedHandler = function(err) { + self.emit('reconnectFailed', err); + self.s.store.flush(err); + }; + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + // Only called on destroy + self.s.coreTopology.on('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Clear out all the current handlers left over + [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Add the event handlers + self.s.coreTopology.once('timeout', connectHandlers.timeout); + self.s.coreTopology.once('error', connectHandlers.error); + self.s.coreTopology.once('close', connectHandlers.close); + self.s.coreTopology.once('connect', connectHandler); + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); + self.s.coreTopology.on('monitoring', relay('monitoring')); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Server.prototype, 'poolSize', { + enumerable: true, + get: function() { + return this.s.coreTopology.connections().length; + } +}); + +Object.defineProperty(Server.prototype, 'autoReconnect', { + enumerable: true, + get: function() { + return this.s.reconnect; + } +}); + +Object.defineProperty(Server.prototype, 'host', { + enumerable: true, + get: function() { + return this.s.host; + } +}); + +Object.defineProperty(Server.prototype, 'port', { + enumerable: true, + get: function() { + return this.s.port; + } +}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Server#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Server#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Server#commandFailed + * @type {object} + */ + +module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js new file mode 100644 index 0000000..54f848c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js @@ -0,0 +1,446 @@ +'use strict'; + +const EventEmitter = require('events'), + MongoError = require('mongodb-core').MongoError, + f = require('util').format, + os = require('os'), + translateReadPreference = require('../utils').translateReadPreference, + ClientSession = require('mongodb-core').Sessions.ClientSession; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; + + // Internal state + this.s = { + storedOps: storedOps, + storeOptions: storeOptions, + topology: topology + }; + + Object.defineProperty(this, 'length', { + enumerable: true, + get: function() { + return self.s.storedOps.length; + } + }); +}; + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); +}; + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); +}; + +Store.prototype.flush = function(err) { + while (this.s.storedOps.length > 0) { + this.s.storedOps + .shift() + .c( + err || + MongoError.create({ message: f('no connection available for operation'), driver: true }) + ); + } +}; + +var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; +var secondaryOptions = ['secondary', 'secondaryPreferred']; + +Store.prototype.execute = function(options) { + options = options || {}; + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Unpack options + var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; + var executeSecondary = + typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; + + // Execute all the stored ops + while (ops.length > 0) { + var op = ops.shift(); + + if (op.t === 'cursor') { + if (executePrimary && executeSecondary) { + op.o[op.m].apply(op.o, op.p); + } else if ( + executePrimary && + op.o.options && + op.o.options.readPreference && + primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } else if ( + !executePrimary && + executeSecondary && + op.o.options && + op.o.options.readPreference && + secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } + } else if (op.t === 'auth') { + this.s.topology[op.t].apply(this.s.topology, op.o); + } else { + if (executePrimary && executeSecondary) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + executePrimary && + op.op && + op.op.readPreference && + primaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + !executePrimary && + executeSecondary && + op.op && + op.op.readPreference && + secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } + } +}; + +Store.prototype.all = function() { + return this.s.storedOps; +}; + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + get: function() { + return value; + } + }); + }; + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + var commandsTakeWriteConcern = false; + var commandsTakeCollation = false; + + if (ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if (ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if (ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if (ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + if (ismaster.maxWireVersion >= 5) { + commandsTakeWriteConcern = true; + commandsTakeCollation = true; + } + + // If no min or max wire version set to 0 + if (ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if (ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, 'hasAggregationCursor', aggregationCursor); + setup_get_property(this, 'hasWriteCommands', writeCommands); + setup_get_property(this, 'hasTextSearch', textSearch); + setup_get_property(this, 'hasAuthCommands', authCommands); + setup_get_property(this, 'hasListCollectionsCommand', listCollections); + setup_get_property(this, 'hasListIndexesCommand', listIndexes); + setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); + setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); + setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); + setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); + setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); +}; + +// Get package.json variable +const driverVersion = require('../../package.json').version, + nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), + type = os.type(), + name = process.platform, + architecture = process.arch, + release = os.release(); + +class TopologyBase extends EventEmitter { + constructor() { + super(); + + // Build default client information + this.clientInfo = { + driver: { + name: 'nodejs', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + }; + + this.setMaxListeners(Infinity); + } + + // Sessions related methods + hasSessionSupport() { + return this.logicalSessionTimeoutMinutes != null; + } + + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions = this.s.sessions.filter(s => !s.equals(session)); + }); + + this.s.sessions.push(session); + return session; + } + + endSessions(sessions, callback) { + return this.s.coreTopology.endSessions(sessions, callback); + } + + // Server capabilities + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.s.coreTopology.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + this.s.coreTopology.command(ns, cmd, translateReadPreference(options), callback); + } + + // Insert + insert(ns, ops, options, callback) { + this.s.coreTopology.insert(ns, ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + this.s.coreTopology.update(ns, ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + this.s.coreTopology.remove(ns, ops, options, callback); + } + + // IsConnected + isConnected(options) { + options = options || {}; + options = translateReadPreference(options); + + return this.s.coreTopology.isConnected(options); + } + + // IsDestroyed + isDestroyed() { + return this.s.coreTopology.isDestroyed(); + } + + // Cursor + cursor(ns, cmd, options) { + options = options || {}; + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + options.topology = this; + + return this.s.coreTopology.cursor(ns, cmd, options); + } + + lastIsMaster() { + return this.s.coreTopology.lastIsMaster(); + } + + selectServer(selector, options, callback) { + return this.s.coreTopology.selectServer(selector, options, callback); + } + + /** + * Unref all sockets + * @method + */ + unref() { + return this.s.coreTopology.unref(); + } + + auth() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.coreTopology.auth.apply(this.s.coreTopology, args); + } + + logout() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.coreTopology.logout.apply(this.s.coreTopology, args); + } + + /** + * All raw connections + * @method + * @return {array} + */ + connections() { + return this.s.coreTopology.connections(); + } + + close(forceClosed) { + // If we have sessions, we want to individually move them to the session pool, + // and then send a single endSessions call. + if (this.s.sessions.length) { + this.s.sessions.forEach(session => session.endSession()); + } + + if (this.s.sessionPool) { + this.s.sessionPool.endAllPooledSessions(); + } + + this.s.coreTopology.destroy({ + force: typeof forceClosed === 'boolean' ? forceClosed : false + }); + + // We need to wash out all stored processes + if (forceClosed === true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + } +} + +// Properties +Object.defineProperty(TopologyBase.prototype, 'bson', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.bson; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'parserType', { + enumerable: true, + get: function() { + return this.s.coreTopology.parserType; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.coreTopology.logicalSessionTimeoutMinutes; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'type', { + enumerable: true, + get: function() { + return this.s.coreTopology.type; + } +}); + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; +exports.TopologyBase = TopologyBase; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js b/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..7cc0b2f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,622 @@ +'use strict'; + +const ReadPreference = require('mongodb-core').ReadPreference, + parser = require('url'), + f = require('util').format, + Logger = require('mongodb-core').Logger, + dns = require('dns'); + +module.exports = function(url, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + let result; + try { + result = parser.parse(url, true); + } catch (e) { + return callback(new Error('URL malformed, cannot be parsed')); + } + + if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { + return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); + } + + if (result.protocol === 'mongodb:') { + return parseHandler(url, options, callback); + } + + // Otherwise parse this as an SRV record + if (result.hostname.split('.').length < 3) { + return callback(new Error('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + + if (result.pathname && result.pathname.match(',')) { + return callback(new Error('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); + } + + let srvAddress = `_mongodb._tcp.${result.host}`; + dns.resolveSrv(srvAddress, function(err, addresses) { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new Error('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback(new Error('Server record does not share hostname with parent URI')); + } + } + + let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; + let connectionStrings = addresses.map(function(address, i) { + if (i === 0) return `${base}${address.name}:${address.port}`; + else return `${address.name}:${address.port}`; + }); + + let connectionString = connectionStrings.join(',') + '/'; + let connectionStringOptions = []; + + // Add the default database if needed + if (result.path) { + let defaultDb = result.path.slice(1); + if (defaultDb.indexOf('?') !== -1) { + defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); + } + + connectionString += defaultDb; + } + + // Default to SSL true + if (!options.ssl && !result.search) { + connectionStringOptions.push('ssl=true'); + } else if (!options.ssl && result.search && !result.search.match('ssl')) { + connectionStringOptions.push('ssl=true'); + } + + // Keep original uri options + if (result.search) { + connectionStringOptions.push(result.search.replace('?', '')); + } + + dns.resolveTxt(result.host, function(err, record) { + if (err && err.code !== 'ENODATA') return callback(err); + if (err && err.code === 'ENODATA') record = null; + + if (record) { + if (record.length > 1) { + return callback(new Error('Multiple text records not allowed')); + } + + record = record[0]; + if (record.length > 1) record = record.join(''); + else record = record[0]; + + if (!record.includes('authSource') && !record.includes('replicaSet')) { + return callback(new Error('Text record must only set `authSource` or `replicaSet`')); + } + + connectionStringOptions.push(record); + } + + // Add any options to the connection string + if (connectionStringOptions.length) { + connectionString += `?${connectionStringOptions.join('&')}`; + } + + parseHandler(connectionString, options, callback); + }); + }); +}; + +function matchesParentDomain(srvAddress, parentDomain) { + let regex = /^.*?\./; + let srv = `.${srvAddress.replace(regex, '')}`; + let parent = `.${parentDomain.replace(regex, '')}`; + if (srv.endsWith(parent)) return true; + else return false; +} + +function parseHandler(address, options, callback) { + let result, err; + try { + result = parseConnectionString(address, options); + } catch (e) { + err = e; + } + + return err ? callback(err, null) : callback(null, result); +} + +function parseConnectionString(url, options) { + // Variables + let connection_part = ''; + let auth_part = ''; + let query_string_part = ''; + let dbName = 'admin'; + + // Url parser result + let result = parser.parse(url, true); + if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { + throw new Error('No hostname or hostnames provided in connection string'); + } + + if (result.port === '0') { + throw new Error('Invalid port (zero) with hostname'); + } + + if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('Invalid port (larger than 65535) with hostname'); + } + + if ( + result.path && + result.path.length > 0 && + result.path[0] !== '/' && + url.indexOf('.sock') === -1 + ) { + throw new Error('Missing delimiting slash between hosts and options'); + } + + if (result.query) { + for (let name in result.query) { + if (name.indexOf('::') !== -1) { + throw new Error('Double colon in host identifier'); + } + + if (result.query[name] === '') { + throw new Error('Query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if (result.auth) { + let parts = result.auth.split(':'); + if (url.indexOf(result.auth) !== -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + let clean = url.split('?').shift(); + + // Extract the list of hosts + let strings = clean.split(','); + let hosts = []; + + for (let i = 0; i < strings.length; i++) { + let hostString = strings[i]; + + if (hostString.indexOf('mongodb') !== -1) { + if (hostString.indexOf('@') !== -1) { + hosts.push(hostString.split('@').pop()); + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if (hostString.indexOf('/') !== -1) { + hosts.push(hostString.split('/').shift()); + } else if (hostString.indexOf('/') === -1) { + hosts.push(hostString.trim()); + } + } + + for (let i = 0; i < hosts.length; i++) { + let r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if (r.path && r.path.indexOf('.sock') !== -1) continue; + if (r.path && r.path.indexOf(':') !== -1) { + // Not connecting to a socket so check for an extra slash in the hostname. + // Using String#split as perf is better than match. + if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { + throw new Error('Slash in host identifier'); + } else { + throw new Error('Double colon in host identifier'); + } + } + } + + // If we have a ? mark cut the query elements off + if (url.indexOf('?') !== -1) { + query_string_part = url.substr(url.indexOf('?') + 1); + connection_part = url.substring('mongodb://'.length, url.indexOf('?')); + } else { + connection_part = url.substring('mongodb://'.length); + } + + // Check if we have auth params + if (connection_part.indexOf('@') !== -1) { + auth_part = connection_part.split('@')[0]; + connection_part = connection_part.split('@')[1]; + } + + // Check there is not more than one unescaped slash + if (connection_part.split('/').length > 2) { + throw new Error( + "Unsupported host '" + + connection_part.split('?')[0] + + "', hosts must be URL encoded and contain at most one unencoded slash" + ); + } + + // Check if the connection string has a db + if (connection_part.indexOf('.sock') !== -1) { + if (connection_part.indexOf('.sock/') !== -1) { + dbName = connection_part.split('.sock/')[1]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf('/') !== -1) { + if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split( + '/', + connection_part.indexOf('.sock') + '.sock'.length + ); + } + } else if (connection_part.indexOf('/') !== -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split('/').length > 2) { + if (connection_part.split('/')[2].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + dbName = connection_part.split('/')[1]; + connection_part = connection_part.split('/')[0]; + } + + // URI decode the host information + connection_part = decodeURIComponent(connection_part); + + // Result object + let object = {}; + + // Pick apart the authentication part of the string + let authPart = auth_part || ''; + let auth = authPart.split(':', 2); + + // Decode the authentication URI components and verify integrity + let user = decodeURIComponent(auth[0]); + if (auth[0] !== encodeURIComponent(user)) { + throw new Error('Username contains an illegal unescaped character'); + } + auth[0] = user; + + if (auth[1]) { + let pass = decodeURIComponent(auth[1]); + if (auth[1] !== encodeURIComponent(pass)) { + throw new Error('Password contains an illegal unescaped character'); + } + auth[1] = pass; + } + + // Add auth to final object if we have 2 elements + if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; + // if user provided auth options, use that + if (options && options.auth != null) object.auth = options.auth; + + // Variables used for temporary storage + let hostPart; + let urlOptions; + let servers; + let compression; + let serverOptions = { socketOptions: {} }; + let dbOptions = { read_preference_tags: [] }; + let replSetServersOptions = { socketOptions: {} }; + let mongosOptions = { socketOptions: {} }; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = mongosOptions; + + // Let's check if we are using a domain socket + if (url.match(/\.sock/)) { + // Split out the socket part + let domainSocket = url.substring( + url.indexOf('mongodb://') + 'mongodb://'.length, + url.lastIndexOf('.sock') + '.sock'.length + ); + // Clean out any auth stuff if any + if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; + domainSocket = decodeURIComponent(domainSocket); + servers = [{ domain_socket: domainSocket }]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + let deduplicatedServers = {}; + + // Parse all server results + servers = hostPart + .split(',') + .map(function(h) { + let _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + let hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate servr + if (deduplicatedServers[_host + '_' + _port]) return null; + deduplicatedServers[_host + '_' + _port] = 1; + + // Return the mapped object + return { host: _host, port: _port }; + }) + .filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if (!opt) return; + var splitOpt = opt.split('='), + name = splitOpt[0], + value = splitOpt[1]; + + // Options implementations + switch (name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = value === 'true'; + dbOptions.slaveOk = value === 'true'; + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'appname': + object.appname = decodeURIComponent(value); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = value === 'true'; + break; + case 'ssl': + if (value === 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + mongosOptions.ssl = value; + break; + } + serverOptions.ssl = value === 'true'; + replSetServersOptions.ssl = value === 'true'; + mongosOptions.ssl = value === 'true'; + break; + case 'sslValidate': + serverOptions.sslValidate = value === 'true'; + replSetServersOptions.sslValidate = value === 'true'; + mongosOptions.sslValidate = value === 'true'; + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = value === 'true'; + break; + case 'fsync': + dbOptions.fsync = value === 'true'; + break; + case 'journal': + dbOptions.j = value === 'true'; + break; + case 'safe': + dbOptions.safe = value === 'true'; + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = value === 'true'; + break; + case 'readConcernLevel': + dbOptions.readConcern = { level: value }; + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if (isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if (value === 'GSSAPI') { + // If no password provided decode only the principal + if (object.auth == null) { + let urlDecodeAuthPart = decodeURIComponent(authPart); + if (urlDecodeAuthPart.indexOf('@') === -1) + throw new Error('GSSAPI requires a provided principal'); + object.auth = { user: urlDecodeAuthPart, password: null }; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if (value === 'MONGODB-X509') { + object.auth = { user: decodeURIComponent(authPart) }; + } + + // Only support GSSAPI or MONGODB-CR for now + if ( + value !== 'GSSAPI' && + value !== 'MONGODB-X509' && + value !== 'MONGODB-CR' && + value !== 'DEFAULT' && + value !== 'SCRAM-SHA-1' && + value !== 'SCRAM-SHA-256' && + value !== 'PLAIN' + ) + throw new Error( + 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' + ); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + { + // Split up into key, value pairs + let values = value.split(','); + let o = {}; + // For each value split into key, value + values.forEach(function(x) { + let v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; + if (typeof o.CANONICALIZE_HOST_NAME === 'string') + dbOptions.gssapiCanonicalizeHostName = + o.CANONICALIZE_HOST_NAME === 'true' ? true : false; + } + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if (!ReadPreference.isValid(value)) + throw new Error( + 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' + ); + dbOptions.readPreference = value; + break; + case 'maxStalenessSeconds': + dbOptions.maxStalenessSeconds = parseInt(value, 10); + break; + case 'readPreferenceTags': + { + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + let tagObject = {}; + if (value == null || value === '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + let tags = value.split(/,/); + for (let i = 0; i < tags.length; i++) { + let parts = tags[i].trim().split(/:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + } + break; + case 'compressors': + { + compression = serverOptions.compression || {}; + let compressors = value.split(','); + if ( + !compressors.every(function(compressor) { + return compressor === 'snappy' || compressor === 'zlib'; + }) + ) { + throw new Error('Compressors must be at least one of snappy or zlib'); + } + + compression.compressors = compressors; + serverOptions.compression = compression; + } + break; + case 'zlibCompressionLevel': + { + compression = serverOptions.compression || {}; + let zlibCompressionLevel = parseInt(value, 10); + if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { + throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); + } + + compression.zlibCompressionLevel = zlibCompressionLevel; + serverOptions.compression = compression; + } + break; + case 'retryWrites': + dbOptions.retryWrites = value === 'true'; + break; + case 'minSize': + dbOptions.minSize = parseInt(value, 10); + break; + default: + { + let logger = Logger('URL Parser'); + logger.warn(`${name} is not supported as a connection string option`); + } + break; + } + }); + + // No tags: should be null (not []) + if (dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if ( + (dbOptions.w === -1 || dbOptions.w === 0) && + (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) + ) + throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); + + // If no read preference set it to primary + if (!dbOptions.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // make sure that user-provided options are applied with priority + dbOptions = Object.assign(dbOptions, options); + + // Add servers to result + object.servers = servers; + + // Returned parsed object + return object; +} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..90e6b7f --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/lib/utils.js @@ -0,0 +1,723 @@ +'use strict'; + +const MongoError = require('mongodb-core').MongoError; +const ReadPreference = require('mongodb-core').ReadPreference; + +var shallowClone = function(obj) { + var copy = {}; + for (var name in obj) copy[name] = obj[name]; + return copy; +}; + +// Figure out the read preference +var translateReadPreference = function(options) { + var r = null; + if (options.readPreference) { + r = options.readPreference; + } else { + return options; + } + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +var formatSortValue = (exports.formatSortValue = function(sortDirection) { + var value = ('' + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]" + ); + } +}); + +var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if (sortValue == null) return null; + if (Array.isArray(sortValue)) { + if (sortValue.length === 0) { + return null; + } + + for (var i = 0; i < sortValue.length; i++) { + if (sortValue[i].constructor === String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if (sortValue != null && typeof sortValue === 'object') { + orderBy = sortValue; + } else if (typeof sortValue === 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return orderBy; +}); + +var checkCollectionName = function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new MongoError('collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoError('collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + throw new MongoError("collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + throw new MongoError("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the colletion name + if (collectionName.indexOf('\x00') !== -1) { + throw new MongoError('collection names cannot contain a null character'); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if (callback == null) return; + + if (callback) { + return value2 ? callback(err, value1, value2) : callback(err, value1); + } + } catch (err) { + process.nextTick(function() { + throw err; + }); + return false; + } + + return true; +}; + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({ message: msg, driver: true }); + + // Get all object keys + var keys = typeof error === 'object' ? Object.keys(error) : []; + + for (var i = 0; i < keys.length; i++) { + try { + e[keys[i]] = error[keys[i]]; + } catch (err) { + // continue + } + } + + return e; +}; + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if ('string' === typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if (Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if (isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +}; + +var isObject = (exports.isObject = function(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +}); + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var decorateCommand = function(command, options, exclude) { + for (var name in options) { + if (exclude.indexOf(name) === -1) command[name] = options[name]; + } + + return command; +}; + +var mergeOptions = function(target, source) { + for (var name in source) { + target[name] = source[name]; + } + + return target; +}; + +// Merge options with translation +var translateOptions = function(target, source) { + var translations = { + // SSL translation options + sslCA: 'ca', + sslCRL: 'crl', + sslValidate: 'rejectUnauthorized', + sslKey: 'key', + sslCert: 'cert', + sslPass: 'passphrase', + // SocketTimeout translation options + socketTimeoutMS: 'socketTimeout', + connectTimeoutMS: 'connectionTimeout', + // Replicaset options + replicaSet: 'setName', + rs_name: 'setName', + secondaryAcceptableLatencyMS: 'acceptableLatency', + connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', + // Mongos options + acceptableLatencyMS: 'localThresholdMS' + }; + + for (var name in source) { + if (translations[name]) { + target[translations[name]] = source[name]; + } else { + target[name] = source[name]; + } + } + + return target; +}; + +var filterOptions = function(options, names) { + var filterOptions = {}; + + for (var name in options) { + if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; + } + + // Filtered options + return filterOptions; +}; + +// Write concern keys +var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; + +// Merge the write concern options +var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { + // Mix in any allowed options + for (var i = 0; i < keys.length; i++) { + if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { + targetOptions[keys[i]] = sourceOptions[keys[i]]; + } + } + + // No merging of write concern + if (!mergeWriteConcern) return targetOptions; + + // Found no write Concern options + var found = false; + for (i = 0; i < writeConcernKeys.length; i++) { + if (targetOptions[writeConcernKeys[i]]) { + found = true; + break; + } + } + + if (!found) { + for (i = 0; i < writeConcernKeys.length; i++) { + if (sourceOptions[writeConcernKeys[i]]) { + targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; + } + } + } + + return targetOptions; +}; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {function} operation The operation to execute + * @param {array} args Arguments to apply the provided operation + * @param {object} [options] Options that modify the behavior of the method + * @param {function]} [options.resultMutator] Allows for the result of the operation to be changed for custom return types + */ +const executeOperation = (topology, operation, args, options) => { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!Array.isArray(args)) { + throw new TypeError('This method requires an array of arguments to apply'); + } + + options = options || {}; + const Promise = topology.s.promiseLibrary; + let resultMutator = options.resultMutator; + let callback = args[args.length - 1]; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, opOptions, owner; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } else if (opOptions.session && opOptions.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner && !options.returnsCursor) { + session.endSession(() => { + delete opOptions.session; + if (err) return reject(err); + if (resultMutator) return resolve(resultMutator(result)); + resolve(result); + }); + } else { + if (err) return reject(err); + if (resultMutator) return resolve(resultMutator(result)); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + args.push(handler); + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + throw e; + } + } + + // Return a Promise + if (args[args.length - 1] != null) { + throw new TypeError('final argument to `executeOperation` must be a callback'); + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + } + }); +}; + +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * + * @param {object} target The target command to which we will apply retryWrites. + * @param {object} db The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + if (db && db.s.options.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * + * @param {Object} target the target command we will be applying the write concern to + * @param {Object} sources sources where we can inherit default write concerns from + * @param {Object} [options] optional settings passed into a command for write concern overrides + * @returns {Object} the (now) decorated target + */ +function applyWriteConcern(target, sources, options) { + options = options || {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + if (options.w != null || options.j != null || options.fsync != null) { + const writeConcern = {}; + if (options.w != null) writeConcern.w = options.w; + if (options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; + if (options.j != null) writeConcern.j = options.j; + if (options.fsync != null) writeConcern.fsync = options.fsync; + return Object.assign(target, { writeConcern }); + } + + if ( + coll && + (coll.writeConcern.w != null || coll.writeConcern.j != null || coll.writeConcern.fsync != null) + ) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if ( + db && + (db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) + ) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Resolves a read preference based on well-defined inheritance rules. This method will not only + * determine the read preference (if there is one), but will also ensure the returned value is a + * properly constructed instance of `ReadPreference`. + * + * @param {Object} options The options passed into the method, potentially containing a read preference + * @param {Object} sources Sources from which we can inherit a read preference + * @returns {(ReadPreference|null)} The resolved read preference + */ +function resolveReadPreference(options, sources) { + options = options || {}; + sources = sources || {}; + + const db = sources.db; + const coll = sources.collection; + const defaultReadPreference = sources.default; + const session = options.session; + + let readPreference; + if (options.readPreference) { + readPreference = options.readPreference; + } else if (session && session.inTransaction() && session.transaction.options.readPreference) { + // The transaction’s read preference MUST override all other user configurable read preferences. + readPreference = session.transaction.options.readPreference; + } else { + if (coll && coll.s.readPreference) { + readPreference = coll.s.readPreference; + } else if (db && db.s.readPreference) { + readPreference = db.s.readPreference; + } else if (defaultReadPreference) { + readPreference = defaultReadPreference; + } + } + + // do we even have a read preference? + if (readPreference == null) { + return null; + } + + // now attempt to convert the read preference if necessary + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } else if ( + readPreference && + !(readPreference instanceof ReadPreference) && + typeof readPreference === 'object' + ) { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + readPreference = new ReadPreference(mode, readPreference.tags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds + }); + } + } else if (!(readPreference instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return readPreference; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * + * @param {object} [command] the command on which to apply collation + * @param {(Cursor|Collection)} [target] target of command + * @param {object} [options] options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const topology = target.s && target.s.topology; + + if (!topology) { + throw new TypeError('parameter "target" is missing a topology'); + } + + const capabilities = target.s.topology.capabilities(); + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * + * @param {object} command the command on which to apply the read concern + * @param {Collection} coll the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + let readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); +const emitConsoleWarning = msg => console.error(msg); +const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; + +/** + * Default message handler for generating deprecation warnings. + * + * @param {string} name function name + * @param {string} option option name + * @return {string} warning message + * @ignore + * @api private + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +/** + * Deprecates a given function's options. + * + * @param {object} config configuration for deprecation + * @param {string} config.name function name + * @param {Array} config.deprecatedOptions options to deprecate + * @param {number} config.optionsIndex index of options object in function arguments array + * @param {function} [config.msgHandler] optional custom message handler to generate warnings + * @param {function} fn the target function of deprecation + * @return {function} modified function that warns once per deprecated option, and executes original function + * @ignore + * @api private + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated() { + const options = arguments[config.optionsIndex]; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.apply(this, arguments); + } + + config.deprecatedOptions.forEach(deprecatedOption => { + if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitDeprecationWarning(msg); + if (this && this.getLogger) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + }); + + return fn.apply(this, arguments); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +module.exports = { + filterOptions, + mergeOptions, + translateOptions, + shallowClone, + getSingleProperty, + checkCollectionName, + toError, + formattedOrderClause, + parseIndexOptions, + normalizeHintField, + handleCallback, + decorateCommand, + isObject, + debugOptions, + MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, + mergeOptionsAndWriteConcern, + translateReadPreference, + executeOperation, + applyRetryableWrites, + applyWriteConcern, + resolveReadPreference, + isPromiseLike, + decorateWithCollation, + decorateWithReadConcern, + deprecateOptions +}; diff --git a/node_modules/mongoose/node_modules/mongodb/package.json b/node_modules/mongoose/node_modules/mongodb/package.json new file mode 100644 index 0000000..bfe2f5c --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/package.json @@ -0,0 +1,91 @@ +{ + "_args": [ + [ + "mongodb@3.1.13", + "/Users/xenia/Desktop/B_ME5/Projekt/om" + ] + ], + "_from": "mongodb@3.1.13", + "_id": "mongodb@3.1.13", + "_inBundle": false, + "_integrity": "sha512-sz2dhvBZQWf3LRNDhbd30KHVzdjZx9IKC0L+kSZ/gzYquCF5zPOgGqRz6sSCqYZtKP2ekB4nfLxhGtzGHnIKxA==", + "_location": "/mongoose/mongodb", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mongodb@3.1.13", + "name": "mongodb", + "escapedName": "mongodb", + "rawSpec": "3.1.13", + "saveSpec": null, + "fetchSpec": "3.1.13" + }, + "_requiredBy": [ + "/mongoose" + ], + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.13.tgz", + "_spec": "3.1.13", + "_where": "/Users/xenia/Desktop/B_ME5/Projekt/om", + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "dependencies": { + "mongodb-core": "3.1.11", + "safe-buffer": "^5.1.2" + }, + "description": "The official MongoDB driver for Node.js", + "devDependencies": { + "bluebird": "3.5.0", + "bson": "^1.0.4", + "chai": "^4.1.1", + "chai-subset": "^1.6.0", + "co": "4.6.0", + "coveralls": "^2.11.6", + "eslint": "^4.5.0", + "eslint-plugin-prettier": "^2.2.0", + "istanbul": "^0.4.5", + "jsdoc": "3.5.5", + "lodash.camelcase": "^4.3.0", + "mocha-sinon": "^2.1.0", + "mongodb-extjson": "^2.1.1", + "mongodb-mock-server": "^1.0.0", + "mongodb-test-runner": "^1.1.18", + "prettier": "~1.12.0", + "semver": "^5.5.0", + "sinon": "^4.3.0", + "sinon-chai": "^3.2.0", + "standard-version": "^4.4.0", + "worker-farm": "^1.5.0" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/mongodb/node-mongodb-native", + "keywords": [ + "mongodb", + "driver", + "official" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "mongodb", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "scripts": { + "bench": "node test/driverBench/", + "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", + "lint": "eslint lib test", + "release": "standard-version -i HISTORY.md", + "test": "npm run lint && mongodb-test-runner -t 60000 test/unit test/functional" + }, + "version": "3.1.13" +} diff --git a/node_modules/mongoose/package.json b/node_modules/mongoose/package.json index 2260528..ff81dfd 100644 --- a/node_modules/mongoose/package.json +++ b/node_modules/mongoose/package.json @@ -1,28 +1,37 @@ { - "_from": "mongoose", - "_id": "mongoose@5.4.3", + "_args": [ + [ + "mongoose@5.4.10", + "/Users/xenia/Desktop/B_ME5/Projekt/om" + ] + ], + "_from": "mongoose@5.4.10", + "_id": "mongoose@5.4.10", "_inBundle": false, - "_integrity": "sha512-zhfypQm63CPYHi43O/3lTcEPVucY3h6CqONbzreMKZIEXtwgkB9HCm4wn441Z9/CpM94G6/NA3wcaRb0N2kPYQ==", + "_integrity": "sha512-yJl+A7p8QF++tyBl6fRGFON5GV57MTXLKNiaiqgX5vZs1qJpcZpPiUGU5odBiqTHFYPybuRp8dW9Qtv4K6SxBQ==", "_location": "/mongoose", - "_phantomChildren": {}, + "_phantomChildren": { + "bson": "1.1.0", + "require_optional": "1.0.1", + "safe-buffer": "5.1.2", + "saslprep": "1.0.2" + }, "_requested": { - "type": "tag", + "type": "version", "registry": true, - "raw": "mongoose", + "raw": "mongoose@5.4.10", "name": "mongoose", "escapedName": "mongoose", - "rawSpec": "", + "rawSpec": "5.4.10", "saveSpec": null, - "fetchSpec": "latest" + "fetchSpec": "5.4.10" }, "_requiredBy": [ - "#USER", "/" ], - "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.4.3.tgz", - "_shasum": "9cbc689ca0c529c2d7dd5a84dcfbc9b041084367", - "_spec": "mongoose", - "_where": "D:\\Gitterra\\om", + "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.4.10.tgz", + "_spec": "5.4.10", + "_where": "/Users/xenia/Desktop/B_ME5/Projekt/om", "author": { "name": "Guillermo Rauch", "email": "guillermo@learnboost.com" @@ -31,13 +40,12 @@ "bugs": { "url": "https://github.com/Automattic/mongoose/issues/new" }, - "bundleDependencies": false, "dependencies": { "async": "2.6.1", "bson": "~1.1.0", "kareem": "2.3.0", - "mongodb": "3.1.10", - "mongodb-core": "3.1.9", + "mongodb": "3.1.13", + "mongodb-core": "3.1.11", "mongoose-legacy-pluralize": "1.0.2", "mpath": "0.5.1", "mquery": "3.2.0", @@ -46,7 +54,6 @@ "safe-buffer": "5.1.2", "sliced": "1.0.1" }, - "deprecated": false, "description": "Mongoose MongoDB ODM", "devDependencies": { "acorn": "5.7.3", @@ -58,6 +65,7 @@ "benchmark": "2.1.2", "bluebird": "3.5.0", "chalk": "2.4.1", + "cheerio": "1.0.0-rc.2", "co": "4.6.0", "dox": "0.3.1", "eslint": "5.3.0", @@ -95,7 +103,6 @@ }, "env": { "node": true, - "mocha": true, "es6": true }, "rules": { @@ -135,6 +142,13 @@ "strict": [ "error", "global" + ], + "no-restricted-globals": [ + "error", + { + "name": "context", + "message": "Don't use Mocha's global context" + } ] } }, @@ -167,5 +181,5 @@ "test": "mocha --exit test/*.test.js test/**/*.test.js", "test-cov": "nyc --reporter=html --reporter=text npm test" }, - "version": "5.4.3" + "version": "5.4.10" } diff --git a/node_modules/mongoose/search.js b/node_modules/mongoose/search.js new file mode 100644 index 0000000..48afa30 --- /dev/null +++ b/node_modules/mongoose/search.js @@ -0,0 +1,92 @@ +'use strict'; + +const config = require('./.config'); +const cheerio = require('cheerio'); +const filemap = require('./docs/source'); +const fs = require('fs'); +const jade = require('jade'); +const mongoose = require('./'); + +mongoose.set('useCreateIndex', true); + +const contentSchema = new mongoose.Schema({ + title: { type: String, required: true }, + body: { type: String, required: true }, + url: { type: String, required: true } +}); +contentSchema.index({ title: 'text', body: 'text' }); +const Content = mongoose.model('Content', contentSchema, 'Content'); + +const contents = []; +const files = Object.keys(filemap); + +for (const filename of files) { + const file = filemap[filename]; + console.log(file) + if (file.api) { + // API docs are special, raw content is in the `docs` property + for (const _class of file.docs) { + for (const prop of _class.props) { + const content = new Content({ + title: `API: ${prop.string}`, + body: prop.description, + url: `api.html#${prop.anchorId}` + }); + const err = content.validateSync(); + if (err != null) { + throw err; + } + contents.push(content); + } + } + } else if (file.guide) { + let text = fs.readFileSync(filename, 'utf8'); + text = text.substr(text.indexOf('block content') + 'block content\n'.length); + text = jade.render(`div\n${text}`); + + const content = new Content({ + title: file.title, + body: text, + url: filename.replace('.jade', '.html').replace(/^docs/, '') + }); + + content.validateSync(); + + const $ = cheerio.load(text); + + contents.push(content); + + // Break up individual h3's into separate content for more fine grained search + $('h3').each((index, el) => { + el = $(el); + const title = el.text(); + const html = el.nextUntil('h3').html(); + const content = new Content({ + title: `${file.title}: ${title}`, + body: html, + url: `${filename.replace('.jade', '.html').replace(/^docs/, '')}#${el.prop('id')}` + }); + + content.validateSync(); + contents.push(content); + }); + } +} + +run().catch(error => console.error(error.stack)); + +async function run() { + await mongoose.connect(config.uri, { useNewUrlParser: true, dbName: 'mongoose' }); + + await Content.deleteMany({}); + for (const content of contents) { + await content.save(); + } + + const results = await Content. + find({ $text: { $search: 'validate' } }, { score: { $meta: 'textScore' } }). + sort({ score: { $meta: 'textScore' } }). + limit(10); + + console.log(results.map(res => res.url)); +} diff --git a/node_modules/vue/README.md b/node_modules/vue/README.md index c89a48c..dda1c36 100644 --- a/node_modules/vue/README.md +++ b/node_modules/vue/README.md @@ -1,19 +1,19 @@

Vue logo

- Build Status + Build Status Coverage Status Downloads Version License Chat
- Sauce Test Status + Build Status

Supporting Vue.js

-Vue.js is an MIT-licensed open source project. It's an independent project with its ongoing development made possible entirely thanks to the support by these awesome [backers](https://github.com/vuejs/vue/blob/dev/BACKERS.md). If you'd like to join them, please consider: +Vue.js is an MIT-licensed open source project with its ongoing development made possible entirely by the support of these awesome [backers](https://github.com/vuejs/vue/blob/dev/BACKERS.md). If you'd like to join them, please consider: - [Become a backer or sponsor on Patreon](https://www.patreon.com/evanyou). - [Become a backer or sponsor on Open Collective](https://opencollective.com/vuejs). @@ -25,50 +25,51 @@ Funds donated via Patreon go directly to support Evan You's full-time work on Vu

Special Sponsors

- - - - - - - - -
- - - - - - - - - - - -
+ +

+ + + +

+ -

Sponsors via Patreon

- -

Platinum

+

Platinum Sponsors

+ + + + + @@ -76,84 +77,146 @@ Funds donated via Patreon go directly to support Evan You's full-time work on Vu
- + + + + + + + + + - +
- - + + + + + +
-

Gold

+ +

Platinum Sponsors (China)

+ + + + + + +
+ + + +
+ + +

Gold Sponsors

+ - - + + + + + + + + + + + + @@ -210,7 +273,7 @@ Vue.js supports all browsers that are [ES5-compliant](http://kangax.github.io/co [vue-router-status]: https://img.shields.io/npm/v/vue-router.svg [vuex-status]: https://img.shields.io/npm/v/vuex.svg -[vue-cli-status]: https://img.shields.io/npm/v/vue-cli.svg +[vue-cli-status]: https://img.shields.io/npm/v/@vue/cli.svg [vue-loader-status]: https://img.shields.io/npm/v/vue-loader.svg [vue-server-renderer-status]: https://img.shields.io/npm/v/vue-server-renderer.svg [vue-class-component-status]: https://img.shields.io/npm/v/vue-class-component.svg @@ -219,7 +282,7 @@ Vue.js supports all browsers that are [ES5-compliant](http://kangax.github.io/co [vue-router-package]: https://npmjs.com/package/vue-router [vuex-package]: https://npmjs.com/package/vuex -[vue-cli-package]: https://npmjs.com/package/vue-cli +[vue-cli-package]: https://npmjs.com/package/@vue/cli [vue-loader-package]: https://npmjs.com/package/vue-loader [vue-server-renderer-package]: https://npmjs.com/package/vue-server-renderer [vue-class-component-package]: https://npmjs.com/package/vue-class-component @@ -232,7 +295,7 @@ To check out [live examples](https://vuejs.org/v2/examples/) and docs, visit [vu ## Questions -For questions and support please use the [the official forum](http://forum.vuejs.org) or [community chat](https://chat.vuejs.org/). The issue list of this repo is **exclusively** for bug reports and feature requests. +For questions and support please use [the official forum](http://forum.vuejs.org) or [community chat](https://chat.vuejs.org/). The issue list of this repo is **exclusively** for bug reports and feature requests. ## Issues diff --git a/node_modules/vue/dist/README.md b/node_modules/vue/dist/README.md index 6b20683..fc0e9dd 100644 --- a/node_modules/vue/dist/README.md +++ b/node_modules/vue/dist/README.md @@ -25,7 +25,7 @@ If you need to compile templates on the fly (e.g. passing a string to the `template` option, or mounting to an element using its in-DOM HTML as the template), you will need the compiler and thus the full build. -When using `vue-loader` or `vueify`, templates inside `*.vue` files are compiled into JavaScript at build time. You don't really need the compiler in the final bundle, and can therefore use the runtime-only build. +When using `vue-loader` or `vueify`, templates inside `*.vue` files are compiled into JavaScript at build time. You don't really need the compiler in the final bundle, and can therefore, use the runtime-only build. Since the runtime-only builds are roughly 30% lighter-weight than their full-build counterparts, you should use it whenever you can. If you wish to use the full build instead, you need to configure an alias in your bundler. @@ -40,7 +40,7 @@ module.exports = { } } } -```` +``` #### Rollup diff --git a/node_modules/vue/dist/vue.common.dev.js b/node_modules/vue/dist/vue.common.dev.js new file mode 100644 index 0000000..ef511fc --- /dev/null +++ b/node_modules/vue/dist/vue.common.dev.js @@ -0,0 +1,11938 @@ +/*! + * Vue.js v2.6.10 + * (c) 2014-2019 Evan You + * Released under the MIT License. + */ +'use strict'; + +/* */ + +var emptyObject = Object.freeze({}); + +// These helpers produce better VM code in JS engines due to their +// explicitness and function inlining. +function isUndef (v) { + return v === undefined || v === null +} + +function isDef (v) { + return v !== undefined && v !== null +} + +function isTrue (v) { + return v === true +} + +function isFalse (v) { + return v === false +} + +/** + * Check if value is primitive. + */ +function isPrimitive (value) { + return ( + typeof value === 'string' || + typeof value === 'number' || + // $flow-disable-line + typeof value === 'symbol' || + typeof value === 'boolean' + ) +} + +/** + * Quick object check - this is primarily used to tell + * Objects from primitive values when we know the value + * is a JSON-compliant type. + */ +function isObject (obj) { + return obj !== null && typeof obj === 'object' +} + +/** + * Get the raw type string of a value, e.g., [object Object]. + */ +var _toString = Object.prototype.toString; + +function toRawType (value) { + return _toString.call(value).slice(8, -1) +} + +/** + * Strict object type check. Only returns true + * for plain JavaScript objects. + */ +function isPlainObject (obj) { + return _toString.call(obj) === '[object Object]' +} + +function isRegExp (v) { + return _toString.call(v) === '[object RegExp]' +} + +/** + * Check if val is a valid array index. + */ +function isValidArrayIndex (val) { + var n = parseFloat(String(val)); + return n >= 0 && Math.floor(n) === n && isFinite(val) +} + +function isPromise (val) { + return ( + isDef(val) && + typeof val.then === 'function' && + typeof val.catch === 'function' + ) +} + +/** + * Convert a value to a string that is actually rendered. + */ +function toString (val) { + return val == null + ? '' + : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) + ? JSON.stringify(val, null, 2) + : String(val) +} + +/** + * Convert an input value to a number for persistence. + * If the conversion fails, return original string. + */ +function toNumber (val) { + var n = parseFloat(val); + return isNaN(n) ? val : n +} + +/** + * Make a map and return a function for checking if a key + * is in that map. + */ +function makeMap ( + str, + expectsLowerCase +) { + var map = Object.create(null); + var list = str.split(','); + for (var i = 0; i < list.length; i++) { + map[list[i]] = true; + } + return expectsLowerCase + ? function (val) { return map[val.toLowerCase()]; } + : function (val) { return map[val]; } +} + +/** + * Check if a tag is a built-in tag. + */ +var isBuiltInTag = makeMap('slot,component', true); + +/** + * Check if an attribute is a reserved attribute. + */ +var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); + +/** + * Remove an item from an array. + */ +function remove (arr, item) { + if (arr.length) { + var index = arr.indexOf(item); + if (index > -1) { + return arr.splice(index, 1) + } + } +} + +/** + * Check whether an object has the property. + */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +function hasOwn (obj, key) { + return hasOwnProperty.call(obj, key) +} + +/** + * Create a cached version of a pure function. + */ +function cached (fn) { + var cache = Object.create(null); + return (function cachedFn (str) { + var hit = cache[str]; + return hit || (cache[str] = fn(str)) + }) +} + +/** + * Camelize a hyphen-delimited string. + */ +var camelizeRE = /-(\w)/g; +var camelize = cached(function (str) { + return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) +}); + +/** + * Capitalize a string. + */ +var capitalize = cached(function (str) { + return str.charAt(0).toUpperCase() + str.slice(1) +}); + +/** + * Hyphenate a camelCase string. + */ +var hyphenateRE = /\B([A-Z])/g; +var hyphenate = cached(function (str) { + return str.replace(hyphenateRE, '-$1').toLowerCase() +}); + +/** + * Simple bind polyfill for environments that do not support it, + * e.g., PhantomJS 1.x. Technically, we don't need this anymore + * since native bind is now performant enough in most browsers. + * But removing it would mean breaking code that was able to run in + * PhantomJS 1.x, so this must be kept for backward compatibility. + */ + +/* istanbul ignore next */ +function polyfillBind (fn, ctx) { + function boundFn (a) { + var l = arguments.length; + return l + ? l > 1 + ? fn.apply(ctx, arguments) + : fn.call(ctx, a) + : fn.call(ctx) + } + + boundFn._length = fn.length; + return boundFn +} + +function nativeBind (fn, ctx) { + return fn.bind(ctx) +} + +var bind = Function.prototype.bind + ? nativeBind + : polyfillBind; + +/** + * Convert an Array-like object to a real Array. + */ +function toArray (list, start) { + start = start || 0; + var i = list.length - start; + var ret = new Array(i); + while (i--) { + ret[i] = list[i + start]; + } + return ret +} + +/** + * Mix properties into target object. + */ +function extend (to, _from) { + for (var key in _from) { + to[key] = _from[key]; + } + return to +} + +/** + * Merge an Array of Objects into a single Object. + */ +function toObject (arr) { + var res = {}; + for (var i = 0; i < arr.length; i++) { + if (arr[i]) { + extend(res, arr[i]); + } + } + return res +} + +/* eslint-disable no-unused-vars */ + +/** + * Perform no operation. + * Stubbing args to make Flow happy without leaving useless transpiled code + * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). + */ +function noop (a, b, c) {} + +/** + * Always return false. + */ +var no = function (a, b, c) { return false; }; + +/* eslint-enable no-unused-vars */ + +/** + * Return the same value. + */ +var identity = function (_) { return _; }; + +/** + * Generate a string containing static keys from compiler modules. + */ +function genStaticKeys (modules) { + return modules.reduce(function (keys, m) { + return keys.concat(m.staticKeys || []) + }, []).join(',') +} + +/** + * Check if two values are loosely equal - that is, + * if they are plain objects, do they have the same shape? + */ +function looseEqual (a, b) { + if (a === b) { return true } + var isObjectA = isObject(a); + var isObjectB = isObject(b); + if (isObjectA && isObjectB) { + try { + var isArrayA = Array.isArray(a); + var isArrayB = Array.isArray(b); + if (isArrayA && isArrayB) { + return a.length === b.length && a.every(function (e, i) { + return looseEqual(e, b[i]) + }) + } else if (a instanceof Date && b instanceof Date) { + return a.getTime() === b.getTime() + } else if (!isArrayA && !isArrayB) { + var keysA = Object.keys(a); + var keysB = Object.keys(b); + return keysA.length === keysB.length && keysA.every(function (key) { + return looseEqual(a[key], b[key]) + }) + } else { + /* istanbul ignore next */ + return false + } + } catch (e) { + /* istanbul ignore next */ + return false + } + } else if (!isObjectA && !isObjectB) { + return String(a) === String(b) + } else { + return false + } +} + +/** + * Return the first index at which a loosely equal value can be + * found in the array (if value is a plain object, the array must + * contain an object of the same shape), or -1 if it is not present. + */ +function looseIndexOf (arr, val) { + for (var i = 0; i < arr.length; i++) { + if (looseEqual(arr[i], val)) { return i } + } + return -1 +} + +/** + * Ensure a function is called only once. + */ +function once (fn) { + var called = false; + return function () { + if (!called) { + called = true; + fn.apply(this, arguments); + } + } +} + +var SSR_ATTR = 'data-server-rendered'; + +var ASSET_TYPES = [ + 'component', + 'directive', + 'filter' +]; + +var LIFECYCLE_HOOKS = [ + 'beforeCreate', + 'created', + 'beforeMount', + 'mounted', + 'beforeUpdate', + 'updated', + 'beforeDestroy', + 'destroyed', + 'activated', + 'deactivated', + 'errorCaptured', + 'serverPrefetch' +]; + +/* */ + + + +var config = ({ + /** + * Option merge strategies (used in core/util/options) + */ + // $flow-disable-line + optionMergeStrategies: Object.create(null), + + /** + * Whether to suppress warnings. + */ + silent: false, + + /** + * Show production mode tip message on boot? + */ + productionTip: "development" !== 'production', + + /** + * Whether to enable devtools + */ + devtools: "development" !== 'production', + + /** + * Whether to record perf + */ + performance: false, + + /** + * Error handler for watcher errors + */ + errorHandler: null, + + /** + * Warn handler for watcher warns + */ + warnHandler: null, + + /** + * Ignore certain custom elements + */ + ignoredElements: [], + + /** + * Custom user key aliases for v-on + */ + // $flow-disable-line + keyCodes: Object.create(null), + + /** + * Check if a tag is reserved so that it cannot be registered as a + * component. This is platform-dependent and may be overwritten. + */ + isReservedTag: no, + + /** + * Check if an attribute is reserved so that it cannot be used as a component + * prop. This is platform-dependent and may be overwritten. + */ + isReservedAttr: no, + + /** + * Check if a tag is an unknown element. + * Platform-dependent. + */ + isUnknownElement: no, + + /** + * Get the namespace of an element + */ + getTagNamespace: noop, + + /** + * Parse the real tag name for the specific platform. + */ + parsePlatformTagName: identity, + + /** + * Check if an attribute must be bound using property, e.g. value + * Platform-dependent. + */ + mustUseProp: no, + + /** + * Perform updates asynchronously. Intended to be used by Vue Test Utils + * This will significantly reduce performance if set to false. + */ + async: true, + + /** + * Exposed for legacy reasons + */ + _lifecycleHooks: LIFECYCLE_HOOKS +}); + +/* */ + +/** + * unicode letters used for parsing html tags, component names and property paths. + * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname + * skipping \u10000-\uEFFFF due to it freezing up PhantomJS + */ +var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; + +/** + * Check if a string starts with $ or _ + */ +function isReserved (str) { + var c = (str + '').charCodeAt(0); + return c === 0x24 || c === 0x5F +} + +/** + * Define a property. + */ +function def (obj, key, val, enumerable) { + Object.defineProperty(obj, key, { + value: val, + enumerable: !!enumerable, + writable: true, + configurable: true + }); +} + +/** + * Parse simple path. + */ +var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]")); +function parsePath (path) { + if (bailRE.test(path)) { + return + } + var segments = path.split('.'); + return function (obj) { + for (var i = 0; i < segments.length; i++) { + if (!obj) { return } + obj = obj[segments[i]]; + } + return obj + } +} + +/* */ + +// can we use __proto__? +var hasProto = '__proto__' in {}; + +// Browser environment sniffing +var inBrowser = typeof window !== 'undefined'; +var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; +var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); +var UA = inBrowser && window.navigator.userAgent.toLowerCase(); +var isIE = UA && /msie|trident/.test(UA); +var isIE9 = UA && UA.indexOf('msie 9.0') > 0; +var isEdge = UA && UA.indexOf('edge/') > 0; +var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); +var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); +var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; +var isPhantomJS = UA && /phantomjs/.test(UA); +var isFF = UA && UA.match(/firefox\/(\d+)/); + +// Firefox has a "watch" function on Object.prototype... +var nativeWatch = ({}).watch; + +var supportsPassive = false; +if (inBrowser) { + try { + var opts = {}; + Object.defineProperty(opts, 'passive', ({ + get: function get () { + /* istanbul ignore next */ + supportsPassive = true; + } + })); // https://github.com/facebook/flow/issues/285 + window.addEventListener('test-passive', null, opts); + } catch (e) {} +} + +// this needs to be lazy-evaled because vue may be required before +// vue-server-renderer can set VUE_ENV +var _isServer; +var isServerRendering = function () { + if (_isServer === undefined) { + /* istanbul ignore if */ + if (!inBrowser && !inWeex && typeof global !== 'undefined') { + // detect presence of vue-server-renderer and avoid + // Webpack shimming the process + _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; + } else { + _isServer = false; + } + } + return _isServer +}; + +// detect devtools +var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; + +/* istanbul ignore next */ +function isNative (Ctor) { + return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) +} + +var hasSymbol = + typeof Symbol !== 'undefined' && isNative(Symbol) && + typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); + +var _Set; +/* istanbul ignore if */ // $flow-disable-line +if (typeof Set !== 'undefined' && isNative(Set)) { + // use native Set when available. + _Set = Set; +} else { + // a non-standard Set polyfill that only works with primitive keys. + _Set = /*@__PURE__*/(function () { + function Set () { + this.set = Object.create(null); + } + Set.prototype.has = function has (key) { + return this.set[key] === true + }; + Set.prototype.add = function add (key) { + this.set[key] = true; + }; + Set.prototype.clear = function clear () { + this.set = Object.create(null); + }; + + return Set; + }()); +} + +/* */ + +var warn = noop; +var tip = noop; +var generateComponentTrace = (noop); // work around flow check +var formatComponentName = (noop); + +{ + var hasConsole = typeof console !== 'undefined'; + var classifyRE = /(?:^|[-_])(\w)/g; + var classify = function (str) { return str + .replace(classifyRE, function (c) { return c.toUpperCase(); }) + .replace(/[-_]/g, ''); }; + + warn = function (msg, vm) { + var trace = vm ? generateComponentTrace(vm) : ''; + + if (config.warnHandler) { + config.warnHandler.call(null, msg, vm, trace); + } else if (hasConsole && (!config.silent)) { + console.error(("[Vue warn]: " + msg + trace)); + } + }; + + tip = function (msg, vm) { + if (hasConsole && (!config.silent)) { + console.warn("[Vue tip]: " + msg + ( + vm ? generateComponentTrace(vm) : '' + )); + } + }; + + formatComponentName = function (vm, includeFile) { + if (vm.$root === vm) { + return '' + } + var options = typeof vm === 'function' && vm.cid != null + ? vm.options + : vm._isVue + ? vm.$options || vm.constructor.options + : vm; + var name = options.name || options._componentTag; + var file = options.__file; + if (!name && file) { + var match = file.match(/([^/\\]+)\.vue$/); + name = match && match[1]; + } + + return ( + (name ? ("<" + (classify(name)) + ">") : "") + + (file && includeFile !== false ? (" at " + file) : '') + ) + }; + + var repeat = function (str, n) { + var res = ''; + while (n) { + if (n % 2 === 1) { res += str; } + if (n > 1) { str += str; } + n >>= 1; + } + return res + }; + + generateComponentTrace = function (vm) { + if (vm._isVue && vm.$parent) { + var tree = []; + var currentRecursiveSequence = 0; + while (vm) { + if (tree.length > 0) { + var last = tree[tree.length - 1]; + if (last.constructor === vm.constructor) { + currentRecursiveSequence++; + vm = vm.$parent; + continue + } else if (currentRecursiveSequence > 0) { + tree[tree.length - 1] = [last, currentRecursiveSequence]; + currentRecursiveSequence = 0; + } + } + tree.push(vm); + vm = vm.$parent; + } + return '\n\nfound in\n\n' + tree + .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) + ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") + : formatComponentName(vm))); }) + .join('\n') + } else { + return ("\n\n(found in " + (formatComponentName(vm)) + ")") + } + }; +} + +/* */ + +var uid = 0; + +/** + * A dep is an observable that can have multiple + * directives subscribing to it. + */ +var Dep = function Dep () { + this.id = uid++; + this.subs = []; +}; + +Dep.prototype.addSub = function addSub (sub) { + this.subs.push(sub); +}; + +Dep.prototype.removeSub = function removeSub (sub) { + remove(this.subs, sub); +}; + +Dep.prototype.depend = function depend () { + if (Dep.target) { + Dep.target.addDep(this); + } +}; + +Dep.prototype.notify = function notify () { + // stabilize the subscriber list first + var subs = this.subs.slice(); + if (!config.async) { + // subs aren't sorted in scheduler if not running async + // we need to sort them now to make sure they fire in correct + // order + subs.sort(function (a, b) { return a.id - b.id; }); + } + for (var i = 0, l = subs.length; i < l; i++) { + subs[i].update(); + } +}; + +// The current target watcher being evaluated. +// This is globally unique because only one watcher +// can be evaluated at a time. +Dep.target = null; +var targetStack = []; + +function pushTarget (target) { + targetStack.push(target); + Dep.target = target; +} + +function popTarget () { + targetStack.pop(); + Dep.target = targetStack[targetStack.length - 1]; +} + +/* */ + +var VNode = function VNode ( + tag, + data, + children, + text, + elm, + context, + componentOptions, + asyncFactory +) { + this.tag = tag; + this.data = data; + this.children = children; + this.text = text; + this.elm = elm; + this.ns = undefined; + this.context = context; + this.fnContext = undefined; + this.fnOptions = undefined; + this.fnScopeId = undefined; + this.key = data && data.key; + this.componentOptions = componentOptions; + this.componentInstance = undefined; + this.parent = undefined; + this.raw = false; + this.isStatic = false; + this.isRootInsert = true; + this.isComment = false; + this.isCloned = false; + this.isOnce = false; + this.asyncFactory = asyncFactory; + this.asyncMeta = undefined; + this.isAsyncPlaceholder = false; +}; + +var prototypeAccessors = { child: { configurable: true } }; + +// DEPRECATED: alias for componentInstance for backwards compat. +/* istanbul ignore next */ +prototypeAccessors.child.get = function () { + return this.componentInstance +}; + +Object.defineProperties( VNode.prototype, prototypeAccessors ); + +var createEmptyVNode = function (text) { + if ( text === void 0 ) text = ''; + + var node = new VNode(); + node.text = text; + node.isComment = true; + return node +}; + +function createTextVNode (val) { + return new VNode(undefined, undefined, undefined, String(val)) +} + +// optimized shallow clone +// used for static nodes and slot nodes because they may be reused across +// multiple renders, cloning them avoids errors when DOM manipulations rely +// on their elm reference. +function cloneVNode (vnode) { + var cloned = new VNode( + vnode.tag, + vnode.data, + // #7975 + // clone children array to avoid mutating original in case of cloning + // a child. + vnode.children && vnode.children.slice(), + vnode.text, + vnode.elm, + vnode.context, + vnode.componentOptions, + vnode.asyncFactory + ); + cloned.ns = vnode.ns; + cloned.isStatic = vnode.isStatic; + cloned.key = vnode.key; + cloned.isComment = vnode.isComment; + cloned.fnContext = vnode.fnContext; + cloned.fnOptions = vnode.fnOptions; + cloned.fnScopeId = vnode.fnScopeId; + cloned.asyncMeta = vnode.asyncMeta; + cloned.isCloned = true; + return cloned +} + +/* + * not type checking this file because flow doesn't play well with + * dynamically accessing methods on Array prototype + */ + +var arrayProto = Array.prototype; +var arrayMethods = Object.create(arrayProto); + +var methodsToPatch = [ + 'push', + 'pop', + 'shift', + 'unshift', + 'splice', + 'sort', + 'reverse' +]; + +/** + * Intercept mutating methods and emit events + */ +methodsToPatch.forEach(function (method) { + // cache original method + var original = arrayProto[method]; + def(arrayMethods, method, function mutator () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + var result = original.apply(this, args); + var ob = this.__ob__; + var inserted; + switch (method) { + case 'push': + case 'unshift': + inserted = args; + break + case 'splice': + inserted = args.slice(2); + break + } + if (inserted) { ob.observeArray(inserted); } + // notify change + ob.dep.notify(); + return result + }); +}); + +/* */ + +var arrayKeys = Object.getOwnPropertyNames(arrayMethods); + +/** + * In some cases we may want to disable observation inside a component's + * update computation. + */ +var shouldObserve = true; + +function toggleObserving (value) { + shouldObserve = value; +} + +/** + * Observer class that is attached to each observed + * object. Once attached, the observer converts the target + * object's property keys into getter/setters that + * collect dependencies and dispatch updates. + */ +var Observer = function Observer (value) { + this.value = value; + this.dep = new Dep(); + this.vmCount = 0; + def(value, '__ob__', this); + if (Array.isArray(value)) { + if (hasProto) { + protoAugment(value, arrayMethods); + } else { + copyAugment(value, arrayMethods, arrayKeys); + } + this.observeArray(value); + } else { + this.walk(value); + } +}; + +/** + * Walk through all properties and convert them into + * getter/setters. This method should only be called when + * value type is Object. + */ +Observer.prototype.walk = function walk (obj) { + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; i++) { + defineReactive$$1(obj, keys[i]); + } +}; + +/** + * Observe a list of Array items. + */ +Observer.prototype.observeArray = function observeArray (items) { + for (var i = 0, l = items.length; i < l; i++) { + observe(items[i]); + } +}; + +// helpers + +/** + * Augment a target Object or Array by intercepting + * the prototype chain using __proto__ + */ +function protoAugment (target, src) { + /* eslint-disable no-proto */ + target.__proto__ = src; + /* eslint-enable no-proto */ +} + +/** + * Augment a target Object or Array by defining + * hidden properties. + */ +/* istanbul ignore next */ +function copyAugment (target, src, keys) { + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + def(target, key, src[key]); + } +} + +/** + * Attempt to create an observer instance for a value, + * returns the new observer if successfully observed, + * or the existing observer if the value already has one. + */ +function observe (value, asRootData) { + if (!isObject(value) || value instanceof VNode) { + return + } + var ob; + if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { + ob = value.__ob__; + } else if ( + shouldObserve && + !isServerRendering() && + (Array.isArray(value) || isPlainObject(value)) && + Object.isExtensible(value) && + !value._isVue + ) { + ob = new Observer(value); + } + if (asRootData && ob) { + ob.vmCount++; + } + return ob +} + +/** + * Define a reactive property on an Object. + */ +function defineReactive$$1 ( + obj, + key, + val, + customSetter, + shallow +) { + var dep = new Dep(); + + var property = Object.getOwnPropertyDescriptor(obj, key); + if (property && property.configurable === false) { + return + } + + // cater for pre-defined getter/setters + var getter = property && property.get; + var setter = property && property.set; + if ((!getter || setter) && arguments.length === 2) { + val = obj[key]; + } + + var childOb = !shallow && observe(val); + Object.defineProperty(obj, key, { + enumerable: true, + configurable: true, + get: function reactiveGetter () { + var value = getter ? getter.call(obj) : val; + if (Dep.target) { + dep.depend(); + if (childOb) { + childOb.dep.depend(); + if (Array.isArray(value)) { + dependArray(value); + } + } + } + return value + }, + set: function reactiveSetter (newVal) { + var value = getter ? getter.call(obj) : val; + /* eslint-disable no-self-compare */ + if (newVal === value || (newVal !== newVal && value !== value)) { + return + } + /* eslint-enable no-self-compare */ + if (customSetter) { + customSetter(); + } + // #7981: for accessor properties without setter + if (getter && !setter) { return } + if (setter) { + setter.call(obj, newVal); + } else { + val = newVal; + } + childOb = !shallow && observe(newVal); + dep.notify(); + } + }); +} + +/** + * Set a property on an object. Adds the new property and + * triggers change notification if the property doesn't + * already exist. + */ +function set (target, key, val) { + if (isUndef(target) || isPrimitive(target) + ) { + warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); + } + if (Array.isArray(target) && isValidArrayIndex(key)) { + target.length = Math.max(target.length, key); + target.splice(key, 1, val); + return val + } + if (key in target && !(key in Object.prototype)) { + target[key] = val; + return val + } + var ob = (target).__ob__; + if (target._isVue || (ob && ob.vmCount)) { + warn( + 'Avoid adding reactive properties to a Vue instance or its root $data ' + + 'at runtime - declare it upfront in the data option.' + ); + return val + } + if (!ob) { + target[key] = val; + return val + } + defineReactive$$1(ob.value, key, val); + ob.dep.notify(); + return val +} + +/** + * Delete a property and trigger change if necessary. + */ +function del (target, key) { + if (isUndef(target) || isPrimitive(target) + ) { + warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); + } + if (Array.isArray(target) && isValidArrayIndex(key)) { + target.splice(key, 1); + return + } + var ob = (target).__ob__; + if (target._isVue || (ob && ob.vmCount)) { + warn( + 'Avoid deleting properties on a Vue instance or its root $data ' + + '- just set it to null.' + ); + return + } + if (!hasOwn(target, key)) { + return + } + delete target[key]; + if (!ob) { + return + } + ob.dep.notify(); +} + +/** + * Collect dependencies on array elements when the array is touched, since + * we cannot intercept array element access like property getters. + */ +function dependArray (value) { + for (var e = (void 0), i = 0, l = value.length; i < l; i++) { + e = value[i]; + e && e.__ob__ && e.__ob__.dep.depend(); + if (Array.isArray(e)) { + dependArray(e); + } + } +} + +/* */ + +/** + * Option overwriting strategies are functions that handle + * how to merge a parent option value and a child option + * value into the final value. + */ +var strats = config.optionMergeStrategies; + +/** + * Options with restrictions + */ +{ + strats.el = strats.propsData = function (parent, child, vm, key) { + if (!vm) { + warn( + "option \"" + key + "\" can only be used during instance " + + 'creation with the `new` keyword.' + ); + } + return defaultStrat(parent, child) + }; +} + +/** + * Helper that recursively merges two data objects together. + */ +function mergeData (to, from) { + if (!from) { return to } + var key, toVal, fromVal; + + var keys = hasSymbol + ? Reflect.ownKeys(from) + : Object.keys(from); + + for (var i = 0; i < keys.length; i++) { + key = keys[i]; + // in case the object is already observed... + if (key === '__ob__') { continue } + toVal = to[key]; + fromVal = from[key]; + if (!hasOwn(to, key)) { + set(to, key, fromVal); + } else if ( + toVal !== fromVal && + isPlainObject(toVal) && + isPlainObject(fromVal) + ) { + mergeData(toVal, fromVal); + } + } + return to +} + +/** + * Data + */ +function mergeDataOrFn ( + parentVal, + childVal, + vm +) { + if (!vm) { + // in a Vue.extend merge, both should be functions + if (!childVal) { + return parentVal + } + if (!parentVal) { + return childVal + } + // when parentVal & childVal are both present, + // we need to return a function that returns the + // merged result of both functions... no need to + // check if parentVal is a function here because + // it has to be a function to pass previous merges. + return function mergedDataFn () { + return mergeData( + typeof childVal === 'function' ? childVal.call(this, this) : childVal, + typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal + ) + } + } else { + return function mergedInstanceDataFn () { + // instance merge + var instanceData = typeof childVal === 'function' + ? childVal.call(vm, vm) + : childVal; + var defaultData = typeof parentVal === 'function' + ? parentVal.call(vm, vm) + : parentVal; + if (instanceData) { + return mergeData(instanceData, defaultData) + } else { + return defaultData + } + } + } +} + +strats.data = function ( + parentVal, + childVal, + vm +) { + if (!vm) { + if (childVal && typeof childVal !== 'function') { + warn( + 'The "data" option should be a function ' + + 'that returns a per-instance value in component ' + + 'definitions.', + vm + ); + + return parentVal + } + return mergeDataOrFn(parentVal, childVal) + } + + return mergeDataOrFn(parentVal, childVal, vm) +}; + +/** + * Hooks and props are merged as arrays. + */ +function mergeHook ( + parentVal, + childVal +) { + var res = childVal + ? parentVal + ? parentVal.concat(childVal) + : Array.isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res + ? dedupeHooks(res) + : res +} + +function dedupeHooks (hooks) { + var res = []; + for (var i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res +} + +LIFECYCLE_HOOKS.forEach(function (hook) { + strats[hook] = mergeHook; +}); + +/** + * Assets + * + * When a vm is present (instance creation), we need to do + * a three-way merge between constructor options, instance + * options and parent options. + */ +function mergeAssets ( + parentVal, + childVal, + vm, + key +) { + var res = Object.create(parentVal || null); + if (childVal) { + assertObjectType(key, childVal, vm); + return extend(res, childVal) + } else { + return res + } +} + +ASSET_TYPES.forEach(function (type) { + strats[type + 's'] = mergeAssets; +}); + +/** + * Watchers. + * + * Watchers hashes should not overwrite one + * another, so we merge them as arrays. + */ +strats.watch = function ( + parentVal, + childVal, + vm, + key +) { + // work around Firefox's Object.prototype.watch... + if (parentVal === nativeWatch) { parentVal = undefined; } + if (childVal === nativeWatch) { childVal = undefined; } + /* istanbul ignore if */ + if (!childVal) { return Object.create(parentVal || null) } + { + assertObjectType(key, childVal, vm); + } + if (!parentVal) { return childVal } + var ret = {}; + extend(ret, parentVal); + for (var key$1 in childVal) { + var parent = ret[key$1]; + var child = childVal[key$1]; + if (parent && !Array.isArray(parent)) { + parent = [parent]; + } + ret[key$1] = parent + ? parent.concat(child) + : Array.isArray(child) ? child : [child]; + } + return ret +}; + +/** + * Other object hashes. + */ +strats.props = +strats.methods = +strats.inject = +strats.computed = function ( + parentVal, + childVal, + vm, + key +) { + if (childVal && "development" !== 'production') { + assertObjectType(key, childVal, vm); + } + if (!parentVal) { return childVal } + var ret = Object.create(null); + extend(ret, parentVal); + if (childVal) { extend(ret, childVal); } + return ret +}; +strats.provide = mergeDataOrFn; + +/** + * Default strategy. + */ +var defaultStrat = function (parentVal, childVal) { + return childVal === undefined + ? parentVal + : childVal +}; + +/** + * Validate component names + */ +function checkComponents (options) { + for (var key in options.components) { + validateComponentName(key); + } +} + +function validateComponentName (name) { + if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) { + warn( + 'Invalid component name: "' + name + '". Component names ' + + 'should conform to valid custom element name in html5 specification.' + ); + } + if (isBuiltInTag(name) || config.isReservedTag(name)) { + warn( + 'Do not use built-in or reserved HTML elements as component ' + + 'id: ' + name + ); + } +} + +/** + * Ensure all props option syntax are normalized into the + * Object-based format. + */ +function normalizeProps (options, vm) { + var props = options.props; + if (!props) { return } + var res = {}; + var i, val, name; + if (Array.isArray(props)) { + i = props.length; + while (i--) { + val = props[i]; + if (typeof val === 'string') { + name = camelize(val); + res[name] = { type: null }; + } else { + warn('props must be strings when using array syntax.'); + } + } + } else if (isPlainObject(props)) { + for (var key in props) { + val = props[key]; + name = camelize(key); + res[name] = isPlainObject(val) + ? val + : { type: val }; + } + } else { + warn( + "Invalid value for option \"props\": expected an Array or an Object, " + + "but got " + (toRawType(props)) + ".", + vm + ); + } + options.props = res; +} + +/** + * Normalize all injections into Object-based format + */ +function normalizeInject (options, vm) { + var inject = options.inject; + if (!inject) { return } + var normalized = options.inject = {}; + if (Array.isArray(inject)) { + for (var i = 0; i < inject.length; i++) { + normalized[inject[i]] = { from: inject[i] }; + } + } else if (isPlainObject(inject)) { + for (var key in inject) { + var val = inject[key]; + normalized[key] = isPlainObject(val) + ? extend({ from: key }, val) + : { from: val }; + } + } else { + warn( + "Invalid value for option \"inject\": expected an Array or an Object, " + + "but got " + (toRawType(inject)) + ".", + vm + ); + } +} + +/** + * Normalize raw function directives into object format. + */ +function normalizeDirectives (options) { + var dirs = options.directives; + if (dirs) { + for (var key in dirs) { + var def$$1 = dirs[key]; + if (typeof def$$1 === 'function') { + dirs[key] = { bind: def$$1, update: def$$1 }; + } + } + } +} + +function assertObjectType (name, value, vm) { + if (!isPlainObject(value)) { + warn( + "Invalid value for option \"" + name + "\": expected an Object, " + + "but got " + (toRawType(value)) + ".", + vm + ); + } +} + +/** + * Merge two option objects into a new one. + * Core utility used in both instantiation and inheritance. + */ +function mergeOptions ( + parent, + child, + vm +) { + { + checkComponents(child); + } + + if (typeof child === 'function') { + child = child.options; + } + + normalizeProps(child, vm); + normalizeInject(child, vm); + normalizeDirectives(child); + + // Apply extends and mixins on the child options, + // but only if it is a raw options object that isn't + // the result of another mergeOptions call. + // Only merged options has the _base property. + if (!child._base) { + if (child.extends) { + parent = mergeOptions(parent, child.extends, vm); + } + if (child.mixins) { + for (var i = 0, l = child.mixins.length; i < l; i++) { + parent = mergeOptions(parent, child.mixins[i], vm); + } + } + } + + var options = {}; + var key; + for (key in parent) { + mergeField(key); + } + for (key in child) { + if (!hasOwn(parent, key)) { + mergeField(key); + } + } + function mergeField (key) { + var strat = strats[key] || defaultStrat; + options[key] = strat(parent[key], child[key], vm, key); + } + return options +} + +/** + * Resolve an asset. + * This function is used because child instances need access + * to assets defined in its ancestor chain. + */ +function resolveAsset ( + options, + type, + id, + warnMissing +) { + /* istanbul ignore if */ + if (typeof id !== 'string') { + return + } + var assets = options[type]; + // check local registration variations first + if (hasOwn(assets, id)) { return assets[id] } + var camelizedId = camelize(id); + if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } + var PascalCaseId = capitalize(camelizedId); + if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } + // fallback to prototype chain + var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; + if (warnMissing && !res) { + warn( + 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, + options + ); + } + return res +} + +/* */ + + + +function validateProp ( + key, + propOptions, + propsData, + vm +) { + var prop = propOptions[key]; + var absent = !hasOwn(propsData, key); + var value = propsData[key]; + // boolean casting + var booleanIndex = getTypeIndex(Boolean, prop.type); + if (booleanIndex > -1) { + if (absent && !hasOwn(prop, 'default')) { + value = false; + } else if (value === '' || value === hyphenate(key)) { + // only cast empty string / same name to boolean if + // boolean has higher priority + var stringIndex = getTypeIndex(String, prop.type); + if (stringIndex < 0 || booleanIndex < stringIndex) { + value = true; + } + } + } + // check default value + if (value === undefined) { + value = getPropDefaultValue(vm, prop, key); + // since the default value is a fresh copy, + // make sure to observe it. + var prevShouldObserve = shouldObserve; + toggleObserving(true); + observe(value); + toggleObserving(prevShouldObserve); + } + { + assertProp(prop, key, value, vm, absent); + } + return value +} + +/** + * Get the default value of a prop. + */ +function getPropDefaultValue (vm, prop, key) { + // no default, return undefined + if (!hasOwn(prop, 'default')) { + return undefined + } + var def = prop.default; + // warn against non-factory defaults for Object & Array + if (isObject(def)) { + warn( + 'Invalid default value for prop "' + key + '": ' + + 'Props with type Object/Array must use a factory function ' + + 'to return the default value.', + vm + ); + } + // the raw prop value was also undefined from previous render, + // return previous default value to avoid unnecessary watcher trigger + if (vm && vm.$options.propsData && + vm.$options.propsData[key] === undefined && + vm._props[key] !== undefined + ) { + return vm._props[key] + } + // call factory function for non-Function types + // a value is Function if its prototype is function even across different execution context + return typeof def === 'function' && getType(prop.type) !== 'Function' + ? def.call(vm) + : def +} + +/** + * Assert whether a prop is valid. + */ +function assertProp ( + prop, + name, + value, + vm, + absent +) { + if (prop.required && absent) { + warn( + 'Missing required prop: "' + name + '"', + vm + ); + return + } + if (value == null && !prop.required) { + return + } + var type = prop.type; + var valid = !type || type === true; + var expectedTypes = []; + if (type) { + if (!Array.isArray(type)) { + type = [type]; + } + for (var i = 0; i < type.length && !valid; i++) { + var assertedType = assertType(value, type[i]); + expectedTypes.push(assertedType.expectedType || ''); + valid = assertedType.valid; + } + } + + if (!valid) { + warn( + getInvalidTypeMessage(name, value, expectedTypes), + vm + ); + return + } + var validator = prop.validator; + if (validator) { + if (!validator(value)) { + warn( + 'Invalid prop: custom validator check failed for prop "' + name + '".', + vm + ); + } + } +} + +var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; + +function assertType (value, type) { + var valid; + var expectedType = getType(type); + if (simpleCheckRE.test(expectedType)) { + var t = typeof value; + valid = t === expectedType.toLowerCase(); + // for primitive wrapper objects + if (!valid && t === 'object') { + valid = value instanceof type; + } + } else if (expectedType === 'Object') { + valid = isPlainObject(value); + } else if (expectedType === 'Array') { + valid = Array.isArray(value); + } else { + valid = value instanceof type; + } + return { + valid: valid, + expectedType: expectedType + } +} + +/** + * Use function string name to check built-in types, + * because a simple equality check will fail when running + * across different vms / iframes. + */ +function getType (fn) { + var match = fn && fn.toString().match(/^\s*function (\w+)/); + return match ? match[1] : '' +} + +function isSameType (a, b) { + return getType(a) === getType(b) +} + +function getTypeIndex (type, expectedTypes) { + if (!Array.isArray(expectedTypes)) { + return isSameType(expectedTypes, type) ? 0 : -1 + } + for (var i = 0, len = expectedTypes.length; i < len; i++) { + if (isSameType(expectedTypes[i], type)) { + return i + } + } + return -1 +} + +function getInvalidTypeMessage (name, value, expectedTypes) { + var message = "Invalid prop: type check failed for prop \"" + name + "\"." + + " Expected " + (expectedTypes.map(capitalize).join(', ')); + var expectedType = expectedTypes[0]; + var receivedType = toRawType(value); + var expectedValue = styleValue(value, expectedType); + var receivedValue = styleValue(value, receivedType); + // check if we need to specify expected value + if (expectedTypes.length === 1 && + isExplicable(expectedType) && + !isBoolean(expectedType, receivedType)) { + message += " with value " + expectedValue; + } + message += ", got " + receivedType + " "; + // check if we need to specify received value + if (isExplicable(receivedType)) { + message += "with value " + receivedValue + "."; + } + return message +} + +function styleValue (value, type) { + if (type === 'String') { + return ("\"" + value + "\"") + } else if (type === 'Number') { + return ("" + (Number(value))) + } else { + return ("" + value) + } +} + +function isExplicable (value) { + var explicitTypes = ['string', 'number', 'boolean']; + return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) +} + +function isBoolean () { + var args = [], len = arguments.length; + while ( len-- ) args[ len ] = arguments[ len ]; + + return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) +} + +/* */ + +function handleError (err, vm, info) { + // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. + // See: https://github.com/vuejs/vuex/issues/1505 + pushTarget(); + try { + if (vm) { + var cur = vm; + while ((cur = cur.$parent)) { + var hooks = cur.$options.errorCaptured; + if (hooks) { + for (var i = 0; i < hooks.length; i++) { + try { + var capture = hooks[i].call(cur, err, vm, info) === false; + if (capture) { return } + } catch (e) { + globalHandleError(e, cur, 'errorCaptured hook'); + } + } + } + } + } + globalHandleError(err, vm, info); + } finally { + popTarget(); + } +} + +function invokeWithErrorHandling ( + handler, + context, + args, + vm, + info +) { + var res; + try { + res = args ? handler.apply(context, args) : handler.call(context); + if (res && !res._isVue && isPromise(res) && !res._handled) { + res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); + // issue #9511 + // avoid catch triggering multiple times when nested calls + res._handled = true; + } + } catch (e) { + handleError(e, vm, info); + } + return res +} + +function globalHandleError (err, vm, info) { + if (config.errorHandler) { + try { + return config.errorHandler.call(null, err, vm, info) + } catch (e) { + // if the user intentionally throws the original error in the handler, + // do not log it twice + if (e !== err) { + logError(e, null, 'config.errorHandler'); + } + } + } + logError(err, vm, info); +} + +function logError (err, vm, info) { + { + warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); + } + /* istanbul ignore else */ + if ((inBrowser || inWeex) && typeof console !== 'undefined') { + console.error(err); + } else { + throw err + } +} + +/* */ + +var isUsingMicroTask = false; + +var callbacks = []; +var pending = false; + +function flushCallbacks () { + pending = false; + var copies = callbacks.slice(0); + callbacks.length = 0; + for (var i = 0; i < copies.length; i++) { + copies[i](); + } +} + +// Here we have async deferring wrappers using microtasks. +// In 2.5 we used (macro) tasks (in combination with microtasks). +// However, it has subtle problems when state is changed right before repaint +// (e.g. #6813, out-in transitions). +// Also, using (macro) tasks in event handler would cause some weird behaviors +// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). +// So we now use microtasks everywhere, again. +// A major drawback of this tradeoff is that there are some scenarios +// where microtasks have too high a priority and fire in between supposedly +// sequential events (e.g. #4521, #6690, which have workarounds) +// or even between bubbling of the same event (#6566). +var timerFunc; + +// The nextTick behavior leverages the microtask queue, which can be accessed +// via either native Promise.then or MutationObserver. +// MutationObserver has wider support, however it is seriously bugged in +// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It +// completely stops working after triggering a few times... so, if native +// Promise is available, we will use it: +/* istanbul ignore next, $flow-disable-line */ +if (typeof Promise !== 'undefined' && isNative(Promise)) { + var p = Promise.resolve(); + timerFunc = function () { + p.then(flushCallbacks); + // In problematic UIWebViews, Promise.then doesn't completely break, but + // it can get stuck in a weird state where callbacks are pushed into the + // microtask queue but the queue isn't being flushed, until the browser + // needs to do some other work, e.g. handle a timer. Therefore we can + // "force" the microtask queue to be flushed by adding an empty timer. + if (isIOS) { setTimeout(noop); } + }; + isUsingMicroTask = true; +} else if (!isIE && typeof MutationObserver !== 'undefined' && ( + isNative(MutationObserver) || + // PhantomJS and iOS 7.x + MutationObserver.toString() === '[object MutationObserverConstructor]' +)) { + // Use MutationObserver where native Promise is not available, + // e.g. PhantomJS, iOS7, Android 4.4 + // (#6466 MutationObserver is unreliable in IE11) + var counter = 1; + var observer = new MutationObserver(flushCallbacks); + var textNode = document.createTextNode(String(counter)); + observer.observe(textNode, { + characterData: true + }); + timerFunc = function () { + counter = (counter + 1) % 2; + textNode.data = String(counter); + }; + isUsingMicroTask = true; +} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { + // Fallback to setImmediate. + // Techinically it leverages the (macro) task queue, + // but it is still a better choice than setTimeout. + timerFunc = function () { + setImmediate(flushCallbacks); + }; +} else { + // Fallback to setTimeout. + timerFunc = function () { + setTimeout(flushCallbacks, 0); + }; +} + +function nextTick (cb, ctx) { + var _resolve; + callbacks.push(function () { + if (cb) { + try { + cb.call(ctx); + } catch (e) { + handleError(e, ctx, 'nextTick'); + } + } else if (_resolve) { + _resolve(ctx); + } + }); + if (!pending) { + pending = true; + timerFunc(); + } + // $flow-disable-line + if (!cb && typeof Promise !== 'undefined') { + return new Promise(function (resolve) { + _resolve = resolve; + }) + } +} + +/* */ + +var mark; +var measure; + +{ + var perf = inBrowser && window.performance; + /* istanbul ignore if */ + if ( + perf && + perf.mark && + perf.measure && + perf.clearMarks && + perf.clearMeasures + ) { + mark = function (tag) { return perf.mark(tag); }; + measure = function (name, startTag, endTag) { + perf.measure(name, startTag, endTag); + perf.clearMarks(startTag); + perf.clearMarks(endTag); + // perf.clearMeasures(name) + }; + } +} + +/* not type checking this file because flow doesn't play well with Proxy */ + +var initProxy; + +{ + var allowedGlobals = makeMap( + 'Infinity,undefined,NaN,isFinite,isNaN,' + + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + + 'require' // for Webpack/Browserify + ); + + var warnNonPresent = function (target, key) { + warn( + "Property or method \"" + key + "\" is not defined on the instance but " + + 'referenced during render. Make sure that this property is reactive, ' + + 'either in the data option, or for class-based components, by ' + + 'initializing the property. ' + + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', + target + ); + }; + + var warnReservedPrefix = function (target, key) { + warn( + "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + + 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + + 'prevent conflicts with Vue internals' + + 'See: https://vuejs.org/v2/api/#data', + target + ); + }; + + var hasProxy = + typeof Proxy !== 'undefined' && isNative(Proxy); + + if (hasProxy) { + var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); + config.keyCodes = new Proxy(config.keyCodes, { + set: function set (target, key, value) { + if (isBuiltInModifier(key)) { + warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); + return false + } else { + target[key] = value; + return true + } + } + }); + } + + var hasHandler = { + has: function has (target, key) { + var has = key in target; + var isAllowed = allowedGlobals(key) || + (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data)); + if (!has && !isAllowed) { + if (key in target.$data) { warnReservedPrefix(target, key); } + else { warnNonPresent(target, key); } + } + return has || !isAllowed + } + }; + + var getHandler = { + get: function get (target, key) { + if (typeof key === 'string' && !(key in target)) { + if (key in target.$data) { warnReservedPrefix(target, key); } + else { warnNonPresent(target, key); } + } + return target[key] + } + }; + + initProxy = function initProxy (vm) { + if (hasProxy) { + // determine which proxy handler to use + var options = vm.$options; + var handlers = options.render && options.render._withStripped + ? getHandler + : hasHandler; + vm._renderProxy = new Proxy(vm, handlers); + } else { + vm._renderProxy = vm; + } + }; +} + +/* */ + +var seenObjects = new _Set(); + +/** + * Recursively traverse an object to evoke all converted + * getters, so that every nested property inside the object + * is collected as a "deep" dependency. + */ +function traverse (val) { + _traverse(val, seenObjects); + seenObjects.clear(); +} + +function _traverse (val, seen) { + var i, keys; + var isA = Array.isArray(val); + if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { + return + } + if (val.__ob__) { + var depId = val.__ob__.dep.id; + if (seen.has(depId)) { + return + } + seen.add(depId); + } + if (isA) { + i = val.length; + while (i--) { _traverse(val[i], seen); } + } else { + keys = Object.keys(val); + i = keys.length; + while (i--) { _traverse(val[keys[i]], seen); } + } +} + +/* */ + +var normalizeEvent = cached(function (name) { + var passive = name.charAt(0) === '&'; + name = passive ? name.slice(1) : name; + var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first + name = once$$1 ? name.slice(1) : name; + var capture = name.charAt(0) === '!'; + name = capture ? name.slice(1) : name; + return { + name: name, + once: once$$1, + capture: capture, + passive: passive + } +}); + +function createFnInvoker (fns, vm) { + function invoker () { + var arguments$1 = arguments; + + var fns = invoker.fns; + if (Array.isArray(fns)) { + var cloned = fns.slice(); + for (var i = 0; i < cloned.length; i++) { + invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); + } + } else { + // return handler return value for single handlers + return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") + } + } + invoker.fns = fns; + return invoker +} + +function updateListeners ( + on, + oldOn, + add, + remove$$1, + createOnceHandler, + vm +) { + var name, def$$1, cur, old, event; + for (name in on) { + def$$1 = cur = on[name]; + old = oldOn[name]; + event = normalizeEvent(name); + if (isUndef(cur)) { + warn( + "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), + vm + ); + } else if (isUndef(old)) { + if (isUndef(cur.fns)) { + cur = on[name] = createFnInvoker(cur, vm); + } + if (isTrue(event.once)) { + cur = on[name] = createOnceHandler(event.name, cur, event.capture); + } + add(event.name, cur, event.capture, event.passive, event.params); + } else if (cur !== old) { + old.fns = cur; + on[name] = old; + } + } + for (name in oldOn) { + if (isUndef(on[name])) { + event = normalizeEvent(name); + remove$$1(event.name, oldOn[name], event.capture); + } + } +} + +/* */ + +function mergeVNodeHook (def, hookKey, hook) { + if (def instanceof VNode) { + def = def.data.hook || (def.data.hook = {}); + } + var invoker; + var oldHook = def[hookKey]; + + function wrappedHook () { + hook.apply(this, arguments); + // important: remove merged hook to ensure it's called only once + // and prevent memory leak + remove(invoker.fns, wrappedHook); + } + + if (isUndef(oldHook)) { + // no existing hook + invoker = createFnInvoker([wrappedHook]); + } else { + /* istanbul ignore if */ + if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { + // already a merged invoker + invoker = oldHook; + invoker.fns.push(wrappedHook); + } else { + // existing plain hook + invoker = createFnInvoker([oldHook, wrappedHook]); + } + } + + invoker.merged = true; + def[hookKey] = invoker; +} + +/* */ + +function extractPropsFromVNodeData ( + data, + Ctor, + tag +) { + // we are only extracting raw values here. + // validation and default values are handled in the child + // component itself. + var propOptions = Ctor.options.props; + if (isUndef(propOptions)) { + return + } + var res = {}; + var attrs = data.attrs; + var props = data.props; + if (isDef(attrs) || isDef(props)) { + for (var key in propOptions) { + var altKey = hyphenate(key); + { + var keyInLowerCase = key.toLowerCase(); + if ( + key !== keyInLowerCase && + attrs && hasOwn(attrs, keyInLowerCase) + ) { + tip( + "Prop \"" + keyInLowerCase + "\" is passed to component " + + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + + " \"" + key + "\". " + + "Note that HTML attributes are case-insensitive and camelCased " + + "props need to use their kebab-case equivalents when using in-DOM " + + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." + ); + } + } + checkProp(res, props, key, altKey, true) || + checkProp(res, attrs, key, altKey, false); + } + } + return res +} + +function checkProp ( + res, + hash, + key, + altKey, + preserve +) { + if (isDef(hash)) { + if (hasOwn(hash, key)) { + res[key] = hash[key]; + if (!preserve) { + delete hash[key]; + } + return true + } else if (hasOwn(hash, altKey)) { + res[key] = hash[altKey]; + if (!preserve) { + delete hash[altKey]; + } + return true + } + } + return false +} + +/* */ + +// The template compiler attempts to minimize the need for normalization by +// statically analyzing the template at compile time. +// +// For plain HTML markup, normalization can be completely skipped because the +// generated render function is guaranteed to return Array. There are +// two cases where extra normalization is needed: + +// 1. When the children contains components - because a functional component +// may return an Array instead of a single root. In this case, just a simple +// normalization is needed - if any child is an Array, we flatten the whole +// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep +// because functional components already normalize their own children. +function simpleNormalizeChildren (children) { + for (var i = 0; i < children.length; i++) { + if (Array.isArray(children[i])) { + return Array.prototype.concat.apply([], children) + } + } + return children +} + +// 2. When the children contains constructs that always generated nested Arrays, +// e.g.
- + + + + + - - - - - + - - + + - - + + - - + +
- + - + - - + + - - - - - + - - + + + + + +
- - + + - - + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + +